import { useState, useEffect } from "react";
import { useRoute, useLocation } from "wouter";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { toast } from "sonner";
import { CheckCircle2 } from "lucide-react";
import { APP_LOGO, APP_TITLE } from "@/const";

export default function QuestionnaireReponse() {
  const [, params] = useRoute("/questionnaire/:token");
  const [, navigate] = useLocation();
  const token = params?.token || "";

  const [reponses, setReponses] = useState<Record<number, { reponseNumerique?: number; reponseTexte?: string }>>({});
  const [submitted, setSubmitted] = useState(false);

  const { data, isLoading, error } = trpc.reponses.getByToken.useQuery({ token }, { enabled: !!token });

  const submitMutation = trpc.reponses.submit.useMutation({
    onSuccess: () => {
      setSubmitted(true);
      toast.success("Merci pour vos réponses !");
    },
    onError: (error) => {
      toast.error("Erreur : " + error.message);
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!data) return;

    // Vérifier que toutes les questions obligatoires ont une réponse
    const questionsObligatoires = data.questions.filter(q => q.obligatoire);
    const reponsesManquantes = questionsObligatoires.filter(q => !reponses[q.id]);

    if (reponsesManquantes.length > 0) {
      toast.error("Veuillez répondre à toutes les questions obligatoires");
      return;
    }

    // Préparer les réponses
    const reponsesArray = data.questions.map(q => ({
      questionId: q.id,
      reponseNumerique: reponses[q.id]?.reponseNumerique,
      reponseTexte: reponses[q.id]?.reponseTexte,
    }));

    submitMutation.mutate({
      token,
      reponses: reponsesArray,
    });
  };

  const setReponse = (questionId: number, value: { reponseNumerique?: number; reponseTexte?: string }) => {
    setReponses({
      ...reponses,
      [questionId]: value,
    });
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <p className="text-muted-foreground">Chargement...</p>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <Card className="max-w-md">
          <CardHeader>
            <CardTitle>Questionnaire introuvable</CardTitle>
            <CardDescription>
              Ce lien de questionnaire n'est pas valide ou a expiré.
            </CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  if (data.envoi.dateReponse || submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <Card className="max-w-md">
          <CardHeader className="text-center">
            <div className="mx-auto mb-4 w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
              <CheckCircle2 className="h-10 w-10 text-green-600" />
            </div>
            <CardTitle>Merci pour vos réponses !</CardTitle>
            <CardDescription>
              Vous avez déjà répondu à ce questionnaire.
            </CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto max-w-3xl">
        <div className="mb-8 text-center">
          {APP_LOGO && (
            <img src={APP_LOGO} alt={APP_TITLE} className="h-16 mx-auto mb-4" />
          )}
          <h1 className="page-title">{data.questionnaire?.titre || 'Questionnaire'}</h1>
          {data.questionnaire?.description && (
            <p className="text-muted-foreground">{data.questionnaire.description}</p>
          )}
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {data.questions.map((question, index) => (
            <Card key={question.id}>
              <CardHeader>
                <CardTitle className="text-lg">
                  {index + 1}. {question.texte}
                  {question.obligatoire && <span className="text-red-500 ml-1">*</span>}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {question.typeQuestion === "texte_libre" && (
                  <Textarea
                    value={reponses[question.id]?.reponseTexte || ""}
                    onChange={(e) => setReponse(question.id, { reponseTexte: e.target.value })}
                    placeholder="Votre réponse"
                    rows={4}
                    required={question.obligatoire}
                  />
                )}

                {question.typeQuestion === "oui_non" && (
                  <RadioGroup
                    value={reponses[question.id]?.reponseNumerique?.toString() || ""}
                    onValueChange={(value) => setReponse(question.id, { reponseNumerique: parseInt(value) })}
                    required={question.obligatoire}
                  >
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="1" id={`${question.id}-oui`} />
                      <Label htmlFor={`${question.id}-oui`}>Oui</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="0" id={`${question.id}-non`} />
                      <Label htmlFor={`${question.id}-non`}>Non</Label>
                    </div>
                  </RadioGroup>
                )}

                {question.typeQuestion === "echelle" && (
                  <div className="space-y-4">
                    <div className="flex justify-between text-sm text-muted-foreground">
                      <span>{question.echelleLabelMin || `${question.echelleMin}`}</span>
                      <span>{question.echelleLabelMax || `${question.echelleMax}`}</span>
                    </div>
                    <RadioGroup
                      value={reponses[question.id]?.reponseNumerique?.toString() || ""}
                      onValueChange={(value) => setReponse(question.id, { reponseNumerique: parseInt(value) })}
                      className="flex justify-between"
                      required={question.obligatoire}
                    >
                      {Array.from(
                        { length: (question.echelleMax || 5) - (question.echelleMin || 1) + 1 },
                        (_, i) => (question.echelleMin || 1) + i
                      ).map((value) => (
                        <div key={value} className="flex flex-col items-center">
                          <RadioGroupItem value={value.toString()} id={`${question.id}-${value}`} />
                          <Label htmlFor={`${question.id}-${value}`} className="mt-2">
                            {value}
                          </Label>
                        </div>
                      ))}
                    </RadioGroup>
                  </div>
                )}

                {question.typeQuestion === "choix_multiple" && question.options && (
                  <RadioGroup
                    value={reponses[question.id]?.reponseTexte || ""}
                    onValueChange={(value) => setReponse(question.id, { reponseTexte: value })}
                    required={question.obligatoire}
                  >
                    {question.options.split("\n").filter(o => o.trim()).map((option, i) => (
                      <div key={i} className="flex items-center space-x-2">
                        <RadioGroupItem value={option.trim()} id={`${question.id}-${i}`} />
                        <Label htmlFor={`${question.id}-${i}`}>{option.trim()}</Label>
                      </div>
                    ))}
                  </RadioGroup>
                )}
              </CardContent>
            </Card>
          ))}

          <div className="flex justify-center pt-4">
            <Button type="submit" size="lg" disabled={submitMutation.isPending}>
              {submitMutation.isPending ? "Envoi en cours..." : "Envoyer mes réponses"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
