import { useEffect, useState } from "react";
import { Combobox } from "~/components/combobox";
import { Label } from "~/components/ui/label";
import { getStudentMatch, mergeStudent } from "~/lib/api";

type PartialStudent = {
  id: string;
  fullName: string;
};

export function MatchStudent({
  firstName,
  lastName,
  onSuccess,
}: {
  firstName: string;
  lastName: string;
  onSuccess: (student: PartialStudent) => void;
}) {
  const [pastClasses, setPastClasses] = useState<
    { value: string; label: string }[]
  >([]);
  useEffect(() => {
    fetch("/past_classes.json")
      .then((res) => res.json())
      .then((data) => {
        setPastClasses(data);
      });
  }, []);

  const [pastClassName, setPastClassName] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [matchedStudent, setMatchedStudent] = useState<PartialStudent | null>(null);

  useEffect(() => {
    if (pastClassName) {
      setIsLoading(true);
      getStudentMatch(firstName, lastName, pastClassName)
        .then((student) => {
          setMatchedStudent(student);
          setIsLoading(false);
        })
        .catch(() => {
          setMatchedStudent(null);
          setIsLoading(false);
        });
    }
  }, [pastClassName, firstName, lastName]);

  const handleValidate = () => {
    if (matchedStudent) {
      mergeStudent(matchedStudent.id).then(() => {
        onSuccess(matchedStudent);
      });
    }
  };

  return (
    <div className="space-y-2">
      <Label>Classe de l'année dernière</Label>
      <div className="block">
        <Combobox
          defaultText="Sélectionnez votre classe..."
          values={pastClasses}
          emptyText="Aucune classe trouvée"
          placeholderText="Rechercher"
          current={pastClassName}
          setValue={setPastClassName}
        />
      </div>
      {isLoading && <p>Recherche en cours...</p>}
      {matchedStudent && (
        <div className="flex items-center justify-between">
          <p>
            Correspondance trouvée: {matchedStudent.fullName}
          </p>
          <button onClick={handleValidate}>Valider</button>
        </div>
      )}
    </div>
  );
}
