import { Alert, AlertDescription } from "~/components/ui/alert";
import {
  AlertCircleIcon,
  ArrowRight,
  LoaderCircle,
  LogIn,
  MailIcon,
} from "lucide-react";
import { Label } from "~/components/ui/label";
import { Input } from "~/components/ui/input";
import { Button } from "~/components/ui/button";
import { useEffect, useState } from "react";
import { AuthLayout, SUPPORT_MAIL } from "~/layout";
import { useNavigate, useSearchParams } from "react-router";
import { capitalizeFirstLetter } from "~/lib/utils";
import { Combobox } from "~/components/combobox";
import { getClasses, getNames, registerUser } from "~/lib/api";

export function meta() {
  return [
    { title: "Khollisé - Inscription" },
    { name: "description", content: "Connectez-vous à Khollisé" },
  ];
}

export default function Register() {
  const navigate = useNavigate();

  const [searchParams] = useSearchParams();
  const email = searchParams.get("email")!;
  const [emailFirst, emailLast] = getNameFromEmail(email);
  const [className, setClassName] = useState("");
  const [name, setName] = useState("");

  const token = searchParams.get("token");
  useEffect(() => {
    if (!email || !token) {
      navigate("/login", { replace: true });
      return;
    }
  }, [email, token]);

  const [classes, setClasses] = useState<{ value: string; label: string }[]>(
    []
  );
  useEffect(() => {
    getClasses().then((data) => {
      setClasses(data);
    });
  }, []);

  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const [names, setNames] = useState<{ value: string; label: string, userId: number }[]>([]);
  const hasSubmitted = names.length > 0;

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

    if (!hasSubmitted) {
      // Validate inputs
      if (!className) return setError("Veuillez sélectionner votre classe.");
      setIsLoading(true);

      await getNames(className)
        .then((names) => {
          setNames(names);
          setIsLoading(false);

          // Try to default name from email
          const possibleName = names.find(
            (n: { label: string }) => n.label === `${emailFirst} ${emailLast}`
          );
          if (possibleName) {
            setName(possibleName.value);
          }
        })
        .catch((err) => {
          setIsLoading(false);
          setError(err.message);
        });
    } else {
      // Register user
      if (!name) return setError("Veuillez compléter votre nom.");
      const userId = names.find(
        (n) => n.value === name
      )?.userId;
      if (!userId) return setError("Une erreur est survenue, veuillez réessayer.");
      await registerUser(userId, className, token!)
        .then(() => {
          setIsLoading(false);
          navigate("/", {
            replace: true,
          });
        })
        .catch((err) => {
          setIsLoading(false);
          setError(err.message);
        });
    }
  };

  return (
    <AuthLayout
      title="Inscription"
      description="Créez votre compte pour accéder à Khollisé."
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-500">
              <MailIcon className="h-5 w-5" />
            </div>
            <Input
              id="email"
              type="email"
              className="disabled:opacity-100 pl-10"
              value={email}
              disabled
              required
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="password">Classe</Label>
          <div className="block">
            <Combobox
              defaultText="Sélectionnez votre classe..."
              values={classes}
              emptyText="Aucune classe trouvée"
              placeholderText="Rechercher"
              current={className}
              setValue={setClassName}
              disabled={names.length > 0}
            />
          </div>
          <p className="text-xs text-muted-foreground">
            Si votre classe n'est pas dans la liste, contactez-nous par{" "}
            <a href={SUPPORT_MAIL} className="text-blue-500 hover:underline">
              mail
            </a>{" "}
            pour l'ajouter.
          </p>
        </div>

        {hasSubmitted && (
          <div className="space-y-2">
            <Label htmlFor="names">Prénom et Nom</Label>
            <div className="block">
              <Combobox
                defaultText="Sélectionnez votre nom..."
                values={names}
                emptyText="Aucun nom trouvé"
                placeholderText="Rechercher"
                current={name}
                setValue={setName}
              />
            </div>
          </div>
        )}

        {error && (
          <Alert variant="destructive" className="pb-2">
            <AlertCircleIcon className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <Button type="submit" className="w-full" disabled={isLoading}>
          {isLoading ? (
            <>
              <LoaderCircle className="h-4 w-4 animate-spin mr-2" />
              Validation en cours...
            </>
          ) : (
            <>
              {hasSubmitted ? (
                <LogIn className="h-4 w-4 mr-2" />
              ) : (
                <ArrowRight className="h-4 w-4 mr-2" />
              )}
              {hasSubmitted ? "S'inscrire" : "Continuer"}
            </>
          )}
        </Button>
      </form>
    </AuthLayout>
  );
}

function getNameFromEmail(email: string): [string, string] {
  const parts = email.split("@")[0].split(".");
  if (parts.length < 2) return ["", ""];
  const firstName = capitalizeFirstLetter(parts[0]);
  const lastName = parts.slice(1).join(" ").toUpperCase();
  return [firstName, lastName];
}
