import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Send, Loader2 } from "lucide-react";
import { replySchema, type ReplyInput, type SupportRequest } from "@shared/schema";

interface BulkReplyDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedRequests: SupportRequest[];
  onSubmit: (message: string) => void;
  isPending: boolean;
}

export function BulkReplyDialog({
  open,
  onOpenChange,
  selectedRequests,
  onSubmit,
  isPending,
}: BulkReplyDialogProps) {
  const form = useForm<ReplyInput>({
    resolver: zodResolver(replySchema),
    defaultValues: {
      message: "",
    },
  });

  const handleSubmit = (data: ReplyInput) => {
    onSubmit(data.message);
  };

  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName.charAt(0)}${lastName.charAt(0) || ""}`.toUpperCase();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Массовый ответ</DialogTitle>
          <DialogDescription>
            Отправить сообщение {selectedRequests.length} пользователям
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div>
            <p className="text-sm font-medium mb-2">Получатели:</p>
            <ScrollArea className="h-32 rounded-md border p-3">
              <div className="space-y-2">
                {selectedRequests.map((request) => (
                  <div
                    key={request.id}
                    className="flex items-center gap-2"
                  >
                    <Avatar className="h-6 w-6">
                      <AvatarFallback className="text-xs">
                        {getInitials(request.odFirstName, request.odLastName)}
                      </AvatarFallback>
                    </Avatar>
                    <span className="text-sm">
                      {request.odFirstName} {request.odLastName}
                    </span>
                    {request.odUsername && (
                      <span className="text-xs text-muted-foreground">
                        @{request.odUsername}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </ScrollArea>
          </div>

          <Form {...form}>
            <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
              <FormField
                control={form.control}
                name="message"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Сообщение</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Введите сообщение для отправки..."
                        className="min-h-32 resize-y"
                        data-testid="input-bulk-message"
                        {...field}
                      />
                    </FormControl>
                    <div className="flex justify-between items-center">
                      <FormMessage />
                      <span className="text-xs text-muted-foreground">
                        {field.value.length} / 4096
                      </span>
                    </div>
                  </FormItem>
                )}
              />

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => onOpenChange(false)}
                  disabled={isPending}
                >
                  Отмена
                </Button>
                <Button type="submit" disabled={isPending} data-testid="button-send-bulk">
                  {isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Отправка...
                    </>
                  ) : (
                    <>
                      <Send className="h-4 w-4 mr-2" />
                      Отправить
                    </>
                  )}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </div>
      </DialogContent>
    </Dialog>
  );
}
