import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { insertQuestionSchema } from "@shared/schema";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useMutation } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { Loader2 } from "lucide-react";
import { z } from "zod";

type QuestionFormData = z.infer<typeof insertQuestionSchema>;

export default function QuestionForm() {
  const { toast } = useToast();
  const [submitted, setSubmitted] = useState(false);

  const { register, handleSubmit, reset, formState: { errors } } = useForm<QuestionFormData>({
    resolver: zodResolver(insertQuestionSchema),
    defaultValues: {
      question: ""
    }
  });

  const questionMutation = useMutation({
    mutationFn: async (data: QuestionFormData) => {
      const res = await apiRequest("POST", "/api/questions", data);
      return res.json();
    },
    onSuccess: () => {
      toast({
        title: "Question Submitted",
        description: "Your question has been submitted successfully.",
      });
      reset();
      setSubmitted(true);
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  if (submitted) {
    return (
      <div className="text-center py-4">
        <p className="text-muted-foreground">
          Thanks for your question! We'll address it during the Q&A session.
        </p>
        <Button
          variant="outline"
          className="mt-4"
          onClick={() => setSubmitted(false)}
        >
          Ask Another Question
        </Button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit((data) => questionMutation.mutate(data))}>
      <Textarea
        {...register("question")}
        placeholder="Type your question here..."
        className="mb-4"
      />
      {errors.question && (
        <p className="text-sm text-destructive mb-2">
          {errors.question.message}
        </p>
      )}
      <Button
        type="submit"
        className="w-full"
        disabled={questionMutation.isPending}
      >
        {questionMutation.isPending && (
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
        )}
        Submit Question
      </Button>
    </form>
  );
}