import { Alert, AlertDescription } from "~/components/ui/alert";
import { AlertCircleIcon, IdCardIcon, 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 } from "~/layout";
import { useNavigate, useSearchParams } from "react-router";
import { capitalizeFirstLetter } from "~/lib/utils";
import { Combobox } from "~/components/combobox";
import { getClasses, 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 [firstName, setFirstName] = useState(emailFirst);
  const [lastName, setLastName] = useState(emailLast);
  const [className, setClassName] = 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 handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    // Validate inputs
    if (!firstName || !lastName) return setError("Veuillez compléter votre prénom et nom.");
    if (!className) return setError("Veuillez sélectionner votre classe.");
    setIsLoading(true);

    await registerUser(firstName, lastName, 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 flex gap-4">
          <div>
            <Label htmlFor="password">Prénom</Label>
            <Input
              id="firstName"
              type="text"
              placeholder="Claire"
              value={firstName}
              onChange={(e) => setFirstName(capitalizeFirstLetter(e.target.value))}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="password">Nom</Label>
            <Input
              id="lastName"
              type="text"
              placeholder="DUPONT"
              value={lastName}
              onChange={(e) => setLastName(e.target.value.toUpperCase())}
              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}
            />
          </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" />
              Inscription en cours...
            </>
          ) : (
            <>
              <LogIn className="h-4 w-4 mr-2" />
              S'inscrire
            </>
          )}
        </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];
}
