import { useState } from "react";
import { useLanguage } from "@/hooks/use-language";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "wouter";
import type { Poll, PollQuestion } from "@shared/schema";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { Loader2 } from "lucide-react";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";

type AnswerValue = string | string[] | { selected: string[], other: string };

export default function PollSubmitPage() {
  const { t } = useLanguage();
  const { toast } = useToast();
  const params = useParams<{ id: string }>("/polls/:id/submit");
  const pollId = params?.id ? Number(params.id) : null;
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState<Record<number, AnswerValue>>({});

  // Fetch both poll and its questions
  const { data: poll } = useQuery<Poll>({
    queryKey: [`/api/polls/${pollId}`],
    enabled: !!pollId,
  });

  const { data: questions } = useQuery<PollQuestion[]>({
    queryKey: [`/api/polls/${pollId}/questions`],
    enabled: !!pollId,
  });

  if (!poll || !questions) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin mr-2" />
        <p>{t("Loading...", "جاري التحميل...")}</p>
      </div>
    );
  }

  const currentQuestion = questions[currentQuestionIndex];
  if (!currentQuestion) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <p>{t("No questions available", "لا توجد أسئلة متاحة")}</p>
      </div>
    );
  }

  const isLastQuestion = currentQuestionIndex === questions.length - 1;

  const handleNext = () => {
    if (!answers[currentQuestion.id] && currentQuestion.required) {
      toast({
        title: t("Required", "مطلوب"),
        description: t(
          "Please answer this question before proceeding",
          "الرجاء الإجابة على هذا السؤال قبل المتابعة"
        ),
        variant: "destructive",
      });
      return;
    }
    setCurrentQuestionIndex((prev) => Math.min(prev + 1, questions.length - 1));
  };

  const handlePrevious = () => {
    setCurrentQuestionIndex((prev) => Math.max(prev - 1, 0));
  };

  const handleAnswer = (value: AnswerValue) => {
    setAnswers((prev) => ({
      ...prev,
      [currentQuestion.id]: value,
    }));
  };

  const handleSubmit = async () => {
    try {
      // Debug log to verify answer format
      console.log("Submitting answers:", answers);

      const response = await fetch(`/api/polls/${pollId}/submit`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ answers }),
      });

      if (!response.ok) throw new Error("Failed to submit poll");

      toast({
        title: t("Success", "نجاح"),
        description: t(
          "Thank you for completing the poll",
          "شكراً لإكمال الاستطلاع"
        ),
      });
    } catch (error) {
      toast({
        title: t("Error", "خطأ"),
        description: t(
          "Failed to submit poll",
          "فشل في إرسال الاستطلاع"
        ),
        variant: "destructive",
      });
    }
  };

  const renderQuestionInput = () => {
    if (!currentQuestion) return null;

    switch (currentQuestion.pollTypeId) {
      case 1: // Range (1-5)
        return (
          <RadioGroup
            value={answers[currentQuestion.id] as string || ""}
            onValueChange={handleAnswer}
            className="flex justify-between space-x-4"
          >
            {[1, 2, 3, 4, 5].map((value) => (
              <div key={value} className="flex flex-col items-center">
                <RadioGroupItem value={value.toString()} id={`rating-${value}`} />
                <Label htmlFor={`rating-${value}`}>{value}</Label>
              </div>
            ))}
          </RadioGroup>
        );

      case 2: // YesNo
        return (
          <RadioGroup
            value={answers[currentQuestion.id] as string || ""}
            onValueChange={handleAnswer}
            className="space-y-4"
          >
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="yes" id="yes" />
              <Label htmlFor="yes">{t("Yes", "نعم")}</Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="no" id="no" />
              <Label htmlFor="no">{t("No", "لا")}</Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="maybe" id="maybe" />
              <Label htmlFor="maybe">{t("Maybe", "ربما")}</Label>
            </div>
          </RadioGroup>
        );

      case 3: // MultipleChoice
        if (!currentQuestion.options) return null;
        const selectedOptions = (answers[currentQuestion.id] as string[]) || [];
        return (
          <div className="space-y-4">
            {currentQuestion.options.map((option, index) => (
              <div key={index} className="flex items-center space-x-2">
                <Checkbox
                  id={`option-${index}`}
                  checked={selectedOptions.includes(option)}
                  onCheckedChange={(checked) => {
                    const newSelected = checked
                      ? [...selectedOptions, option]
                      : selectedOptions.filter((opt) => opt !== option);
                    handleAnswer(newSelected);
                  }}
                />
                <Label htmlFor={`option-${index}`}>{option}</Label>
              </div>
            ))}
          </div>
        );

      case 4: // OpenEnded
        return (
          <Textarea
            value={answers[currentQuestion.id] as string || ""}
            onChange={(e) => handleAnswer(e.target.value)}
            placeholder={t("Type your answer here...", "اكتب إجابتك هنا...")}
            className="w-full"
          />
        );

      case 7: // MultipleChoicewithtext
        if (!currentQuestion.options) return null;
        const answer = answers[currentQuestion.id] as { selected: string[]; other: string } || { selected: [], other: "" };
        const hasOtherOption = currentQuestion.options.includes("Other");
        return (
          <div className="space-y-4">
            {currentQuestion.options.map((option, index) => (
              <div key={index} className="flex items-center space-x-2">
                <Checkbox
                  id={`option-${index}`}
                  checked={answer.selected?.includes(option)}
                  onCheckedChange={(checked) => {
                    const selected = answer.selected || [];
                    const newSelected = checked
                      ? [...selected, option]
                      : selected.filter((opt) => opt !== option);
                    handleAnswer({ ...answer, selected: newSelected });
                  }}
                />
                <Label htmlFor={`option-${index}`}>{option}</Label>
              </div>
            ))}
            {/* Only show text input if "Other" is selected */}
            {hasOtherOption && answer.selected?.includes("Other") && (
              <div className="mt-2 ml-6">
                <Textarea
                  placeholder={t("Please specify...", "يرجى التحديد...")}
                  value={answer.other || ""}
                  onChange={(e) => handleAnswer({ ...answer, other: e.target.value })}
                  className="w-full"
                />
              </div>
            )}
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="container mx-auto py-8 max-w-2xl">
      <Card>
        <CardHeader>
          <CardTitle>{poll.title}</CardTitle>
          <p className="text-sm text-muted-foreground">{poll.description}</p>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Progress indicator */}
          <div className="w-full bg-secondary h-2 rounded-full overflow-hidden">
            <div
              className="bg-primary h-full transition-all"
              style={{
                width: `${((currentQuestionIndex + 1) / questions.length) * 100}%`,
              }}
            />
          </div>

          {/* Question */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">
              {t("Question", "سؤال")} {currentQuestionIndex + 1} {t("of", "من")} {questions.length}
            </h3>
            <p className="text-lg mb-4">{currentQuestion.question}</p>
            {currentQuestion.required && (
              <p className="text-sm text-red-500 mb-4">
                {t("* Required", "* مطلوب")}
              </p>
            )}
            {renderQuestionInput()}
          </div>

          {/* Navigation */}
          <div className="flex justify-between pt-4">
            <Button
              variant="outline"
              onClick={handlePrevious}
              disabled={currentQuestionIndex === 0}
            >
              <ChevronLeft className="w-4 h-4 mr-2" />
              {t("Previous", "السابق")}
            </Button>
            {isLastQuestion ? (
              <Button onClick={handleSubmit}>
                {t("Submit", "إرسال")}
              </Button>
            ) : (
              <Button onClick={handleNext}>
                {t("Next", "التالي")}
                <ChevronRight className="w-4 h-4 ml-2" />
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}