import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useLanguage } from "@/hooks/use-language";
import { Question, Session, User } from "@shared/schema";
import { Card, CardContent } from "@/components/ui/card";
import { format } from "date-fns";
import { Loader2, Check, X, Lock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { useRoleCheck } from "@/hooks/use-role-check";
import { useLocation } from "wouter";
import { Alert, AlertDescription } from "@/components/ui/alert";

type QuestionWithDetails = {
  id: number;
  userId: number;
  sessionId: number | null;
  question: string;
  questionAr: string;
  status: string;
  response: string | null;
  responseAr: string | null;
  timestamp: string;
  user: User | undefined;
  session: Session | null;
};

const responseSchema = z.object({
  response: z.string().min(1, "Response is required"),
});

type ResponseData = z.infer<typeof responseSchema>;

export default function QuestionsPage() {
  const { language, t } = useLanguage();
  const { toast } = useToast();
  const { isAdminOrModerator } = useRoleCheck();
  const [, setLocation] = useLocation();

  // Check for admin or moderator access
  if (!isAdminOrModerator()) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen space-y-4">
        <Lock className="h-12 w-12 text-muted-foreground" />
        <Alert variant="destructive" className="max-w-lg">
          <AlertDescription>
            {t(
              "Access Denied. Only administrators and moderators can access this page.",
              "تم رفض الوصول. يمكن للمسؤولين والمشرفين فقط الوصول إلى هذه الصفحة."
            )}
          </AlertDescription>
        </Alert>
        <Button variant="link" onClick={() => setLocation("/")}>
          {t("Return to Home", "العودة إلى الصفحة الرئيسية")}
        </Button>
      </div>
    );
  }

  const { data: questions = [], isLoading } = useQuery<QuestionWithDetails[]>({
    queryKey: ["/api/questions"],
  });

  // Sort questions by timestamp, most recent first
  const sortedQuestions = [...questions].sort(
    (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
  );

  const updateStatusMutation = useMutation({
    mutationFn: async ({ id, status }: { id: number; status: string }) => {
      const res = await apiRequest("POST", `/api/questions/${id}/status`, { status });
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/questions"] });
      toast({
        title: t("Status updated", "تم تحديث الحالة"),
        description: t("Question status has been updated", "تم تحديث حالة السؤال"),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const respondMutation = useMutation({
    mutationFn: async ({ id, response }: { id: number; response: string }) => {
      const res = await apiRequest("POST", `/api/questions/${id}/respond`, { response });
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/questions"] });
      toast({
        title: t("Response submitted", "تم إرسال الرد"),
        description: t("Your response has been submitted successfully", "تم إرسال ردك بنجاح"),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const ResponseForm = ({ questionId }: { questionId: number }) => {
    const form = useForm<ResponseData>({
      resolver: zodResolver(responseSchema),
      defaultValues: {
        response: "",
      },
    });

    return (
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit((data) =>
            respondMutation.mutate({ id: questionId, response: data.response })
          )}
          className="space-y-4"
        >
          <FormField
            control={form.control}
            name="response"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Textarea
                    {...field}
                    placeholder={t("Type your response here...", "اكتب ردك هنا...")}
                    dir={language === "ar" ? "rtl" : "ltr"}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <div className="flex justify-end">
            <Button type="submit" disabled={respondMutation.isPending}>
              {respondMutation.isPending && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              {t("Submit Response", "إرسال الرد")}
            </Button>
          </div>
        </form>
      </Form>
    );
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "approved":
        return "text-green-600";
      case "rejected":
        return "text-red-600";
      default:
        return "text-yellow-600";
    }
  };

  const QuestionsList = ({ questions }: { questions: QuestionWithDetails[] }) => (
    <div className="space-y-4">
      {questions.map((question) => (
        <Card key={question.id}>
          <CardContent className="pt-6">
            <div className="space-y-4">
              <div>
                <div className="flex justify-between items-start mb-4">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="font-semibold">
                        {question.user ? (
                          <>
                            {question.user.name} ({question.user.email})
                          </>
                        ) : (
                          <span className="text-muted-foreground">Deleted User</span>
                        )}
                      </h3>
                      <Badge variant={question.sessionId ? "outline" : "secondary"}>
                        {question.sessionId ? t("Session", "الجلسة") : t("General Question", "سؤال عام")}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {format(new Date(question.timestamp), "PPp")}
                    </p>
                    {question.session && (
                      <p className="text-sm text-muted-foreground mt-1">
                        {t("Session", "الجلسة")}: {question.session.sessionTitle}
                      </p>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={`text-sm ${getStatusColor(question.status)}`}>
                      {t(
                        question.status.charAt(0).toUpperCase() + question.status.slice(1),
                        question.status === "pending"
                          ? "قيد الانتظار"
                          : question.status === "approved"
                          ? "تمت الموافقة"
                          : "مرفوض"
                      )}
                    </span>
                    {/* Show action buttons for both admin and moderator */}
                    {question.status === "pending" && (
                      <div className="flex gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() =>
                            updateStatusMutation.mutate({ id: question.id, status: "approved" })
                          }
                          className="text-green-600 hover:text-green-700 hover:bg-green-50"
                        >
                          <Check className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() =>
                            updateStatusMutation.mutate({ id: question.id, status: "rejected" })
                          }
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <p>{question.question}</p>
                  <p dir="rtl">{question.questionAr}</p>
                </div>
              </div>

              {question.response ? (
                <div className="border-t pt-4 mt-4">
                  <h4 className="font-semibold mb-2">
                    {t("Response", "الرد")}
                  </h4>
                  <div className="space-y-2">
                    <p>{question.response}</p>
                    <p dir="rtl">{question.responseAr}</p>
                  </div>
                </div>
              ) : question.status === "approved" ? (
                // Show response form for both admin and moderator
                <div className="border-t pt-4 mt-4">
                  <h4 className="font-semibold mb-2">
                    {t("Add Response", "إضافة رد")}
                  </h4>
                  <ResponseForm questionId={question.id} />
                </div>
              ) : null}
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );

  if (isLoading) {
    return (
      <div className="flex justify-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  const pendingQuestions = sortedQuestions.filter((q) => q.status === "pending");
  const approvedQuestions = sortedQuestions.filter((q) => q.status === "approved");
  const rejectedQuestions = sortedQuestions.filter((q) => q.status === "rejected");
  const answeredQuestions = sortedQuestions.filter((q) => q.response !== null);

  return (
    <div className="space-y-8">
      <h1 className="text-3xl font-bold">
        {t("Questions Management", "إدارة الأسئلة")}
      </h1>

      <Tabs defaultValue="pending">
        <TabsList>
          <TabsTrigger value="pending">
            {t("Pending", "قيد الانتظار")} ({pendingQuestions.length})
          </TabsTrigger>
          <TabsTrigger value="approved">
            {t("Approved", "تمت الموافقة")} ({approvedQuestions.length})
          </TabsTrigger>
          <TabsTrigger value="rejected">
            {t("Rejected", "مرفوض")} ({rejectedQuestions.length})
          </TabsTrigger>
          <TabsTrigger value="answered">
            {t("Answered", "تم الرد")} ({answeredQuestions.length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="pending">
          <QuestionsList questions={pendingQuestions} />
        </TabsContent>

        <TabsContent value="approved">
          <QuestionsList questions={approvedQuestions} />
        </TabsContent>

        <TabsContent value="rejected">
          <QuestionsList questions={rejectedQuestions} />
        </TabsContent>

        <TabsContent value="answered">
          <QuestionsList questions={answeredQuestions} />
        </TabsContent>
      </Tabs>
    </div>
  );
}