import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Loader2 } from "lucide-react";
import { useLanguage } from "@/hooks/use-language";
import { useMutation, useQuery } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/use-auth";
import { Card, CardContent } from "@/components/ui/card";

interface QuestionFormProps {
  sessionId?: number | null;
  onSuccess?: () => void;
}

// Form schema
const formSchema = z.object({
  question: z.string().min(1, "Question is required"),
});

type FormData = z.infer<typeof formSchema>;

export function QuestionForm({ sessionId, onSuccess }: QuestionFormProps) {
  const { t, language } = useLanguage();
  const { toast } = useToast();
  const { user } = useAuth();

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      question: "",
    },
  });

  // Query to fetch user's questions
  const { data: questions } = useQuery({
    queryKey: ["/api/questions", { sessionId }],
    queryFn: async () => {
      const url = new URL("/api/questions", window.location.origin);
      if (sessionId) {
        url.searchParams.append("sessionId", sessionId.toString());
      }
      const res = await fetch(url);
      if (!res.ok) {
        throw new Error("Failed to fetch questions");
      }
      return res.json();
    },
  });

  const submitQuestionMutation = useMutation({
    mutationFn: async (data: FormData) => {
      const questionData = {
        question: data.question,
        questionAr: "", // Default to empty string as required by schema
        ...(sessionId && { sessionId }), // Only include sessionId if it exists
      };

      const response = await apiRequest("POST", "/api/questions", questionData);

      if (!response.ok) {
        const error = await response.json().catch(() => ({ error: "Failed to submit question" }));
        throw new Error(error.error || "Failed to submit question");
      }

      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/questions"] });
      toast({
        title: t("Question submitted", "تم إرسال السؤال"),
        description: t(
          "Your question has been submitted successfully",
          "تم إرسال سؤالك بنجاح"
        ),
      });
      form.reset();
      onSuccess?.();
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  // Sort questions by timestamp, most recent first
  const userQuestions = (questions || [])
    .filter(q => q.userId === user?.id)
    .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

  return (
    <div className="space-y-6">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit((data) => submitQuestionMutation.mutate(data))}
          className="space-y-4"
        >
          <FormField
            control={form.control}
            name="question"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Textarea 
                    {...field} 
                    placeholder={t(
                      "Type your question here...",
                      "اكتب سؤالك هنا..."
                    )}
                    dir={language === 'ar' ? 'rtl' : 'ltr'}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <div className="flex justify-end">
            <Button
              type="submit"
              disabled={submitQuestionMutation.isPending}
            >
              {submitQuestionMutation.isPending && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              {t("Submit Question", "إرسال السؤال")}
            </Button>
          </div>
        </form>
      </Form>

      {userQuestions.length > 0 && (
        <div className="space-y-4">
          <h3 className="font-semibold text-lg">
            {t("Your Questions", "أسئلتك")}
          </h3>
          {userQuestions.map((question) => (
            <Card key={question.id}>
              <CardContent className="pt-6">
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <p className="text-sm text-muted-foreground">
                      {new Date(question.timestamp).toLocaleString()}
                    </p>
                  </div>
                  <p>{question.question}</p>
                  {question.response && (
                    <div className="border-t pt-4 mt-4">
                      <p className="font-medium text-sm text-muted-foreground">
                        {t("Response", "الرد")}:
                      </p>
                      <p>{question.response}</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}