import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Send, Loader2 } from "lucide-react";
import { replySchema, type ReplyInput } from "@shared/schema";

interface ReplyFormProps {
  onSubmit: (message: string) => void;
  isPending: boolean;
}

export function ReplyForm({ onSubmit, isPending }: ReplyFormProps) {
  const form = useForm<ReplyInput>({
    resolver: zodResolver(replySchema),
    defaultValues: {
      message: "",
    },
  });

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

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="message"
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Textarea
                  placeholder="Введите ваш ответ..."
                  className="min-h-32 resize-y"
                  data-testid="input-reply-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>
          )}
        />
        <div className="flex justify-end gap-2">
          <Button type="submit" disabled={isPending} data-testid="button-send-reply">
            {isPending ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Отправка...
              </>
            ) : (
              <>
                <Send className="h-4 w-4 mr-2" />
                Отправить
              </>
            )}
          </Button>
        </div>
      </form>
    </Form>
  );
}
