"use client";

import { useState, useMemo, useRef, useEffect } from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Team } from "@/lib/types";
import { Search, Building2, ChevronDown, Check, Code2 } from "lucide-react";

interface RegisterFormProps {
  teams: Team[];
  onSubmit: (data: {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    teamId: string;
  }) => void;
  onSwitchToLogin: () => void;
  loading?: boolean;
}

export function RegisterForm({
  teams,
  onSubmit,
  onSwitchToLogin,
  loading = false,
}: RegisterFormProps) {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [teamId, setTeamId] = useState("");
  const [searchTerm, setSearchTerm] = useState("");
  const [isTeamDropdownOpen, setIsTeamDropdownOpen] = useState(false);
  const teamDropdownRef = useRef<HTMLDivElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState<"below" | "above">(
    "below"
  );

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      alert("Les mots de passe ne correspondent pas");
      return;
    }
    if (firstName && lastName && email && password && teamId) {
      onSubmit({ firstName, lastName, email, password, teamId });
    }
  };

  const isValid =
    firstName.length > 0 &&
    lastName.length > 0 &&
    email.length > 0 &&
    password.length > 0 &&
    password === confirmPassword &&
    teamId.length > 0;

  // Group teams by direction and filter by search term
  const teamsByDirection = useMemo(() => {
    const filteredTeams = teams.filter(
      (team) =>
        team.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        team.direction.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return filteredTeams.reduce((acc, team) => {
      if (!acc[team.direction]) {
        acc[team.direction] = [];
      }
      acc[team.direction].push(team);
      return acc;
    }, {} as Record<string, Team[]>);
  }, [teams, searchTerm]);

  // Calculate dropdown position when opening
  const handleDropdownToggle = () => {
    if (!isTeamDropdownOpen && teamDropdownRef.current) {
      const rect = teamDropdownRef.current.getBoundingClientRect();
      const viewportHeight = window.innerHeight;
      const spaceBelow = viewportHeight - rect.bottom;
      const spaceAbove = rect.top;
      const dropdownHeight = 300;

      setDropdownPosition(
        spaceBelow >= dropdownHeight || spaceBelow > spaceAbove
          ? "below"
          : "above"
      );
    }
    setIsTeamDropdownOpen(!isTeamDropdownOpen);
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        teamDropdownRef.current &&
        !teamDropdownRef.current.contains(event.target as Node)
      ) {
        setIsTeamDropdownOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const selectedTeam = teams.find((team) => team.id === teamId);

  return (
    <div className="text-center mb-12">
      <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/5 border border-white/10 backdrop-blur-sm mb-6">
        <Code2 className="h-4 w-4 text-blue-400" />
        <span className="text-sm font-medium text-slate-200">PeakSkills</span>
      </div>

      <h1 className="text-4xl font-bold mb-4 text-white">Créer un compte</h1>
      <p className="text-lg text-slate-400 mb-8">
        Rejoignez PeakSkills et commencez votre évaluation
      </p>

      <div className="max-w-md mx-auto">
        <Card className="bg-white/5 border-white/10 backdrop-blur-sm">
          <CardHeader>
            <CardTitle className="text-white">Inscription</CardTitle>
            <CardDescription className="text-slate-400">
              Créez votre compte pour commencer
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="firstName" className="text-slate-300">
                    Prénom
                  </Label>
                  <Input
                    id="firstName"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    placeholder="Votre prénom"
                    required
                    className="bg-white/10 border-white/20 text-white placeholder:text-slate-400"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="lastName" className="text-slate-300">
                    Nom
                  </Label>
                  <Input
                    id="lastName"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    placeholder="Votre nom"
                    required
                    className="bg-white/10 border-white/20 text-white placeholder:text-slate-400"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="email" className="text-slate-300">
                  Email
                </Label>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="votre@email.com"
                  required
                  className="bg-white/10 border-white/20 text-white placeholder:text-slate-400"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="password" className="text-slate-300">
                    Mot de passe
                  </Label>
                  <Input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="Mot de passe"
                    required
                    className="bg-white/10 border-white/20 text-white placeholder:text-slate-400"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword" className="text-slate-300">
                    Confirmer
                  </Label>
                  <Input
                    id="confirmPassword"
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    placeholder="Confirmer"
                    required
                    className="bg-white/10 border-white/20 text-white placeholder:text-slate-400"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="team" className="text-slate-300">
                  Équipe
                </Label>
                <div className="relative" ref={teamDropdownRef}>
                  <Button
                    type="button"
                    variant="outline"
                    className="w-full justify-between bg-white/10 border-white/20 text-white hover:bg-white/20"
                    onClick={handleDropdownToggle}
                  >
                    <span
                      className={selectedTeam ? "text-white" : "text-slate-400"}
                    >
                      {selectedTeam
                        ? selectedTeam.name
                        : "Sélectionnez votre équipe"}
                    </span>
                    <ChevronDown className="h-4 w-4" />
                  </Button>

                  {isTeamDropdownOpen && (
                    <div
                      className={`absolute left-0 right-0 bg-gray-800 border border-white/20 rounded-md shadow-lg z-50 max-h-[300px] overflow-y-auto ${
                        dropdownPosition === "below"
                          ? "top-full mt-1"
                          : "bottom-full mb-1"
                      }`}
                    >
                      <div className="sticky top-0 bg-gray-800 border-b border-white/20 p-2">
                        <div className="relative">
                          <Search className="absolute left-2 top-2.5 h-4 w-4 text-slate-400" />
                          <Input
                            placeholder="Rechercher une équipe..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="pl-8 h-8 text-sm bg-gray-700 border-white/20 text-white"
                            autoFocus
                          />
                        </div>
                      </div>

                      {Object.entries(teamsByDirection).map(
                        ([direction, directionTeams]) => (
                          <div key={direction}>
                            <div className="px-3 py-2 text-sm font-semibold text-slate-400 bg-gray-700/50 border-b border-white/20 flex items-center gap-2">
                              <Building2 className="h-3 w-3" />
                              {direction}
                            </div>
                            {directionTeams.map((team) => (
                              <button
                                key={team.id}
                                type="button"
                                className={`w-full px-3 py-2 text-left hover:bg-gray-700/50 flex items-center justify-between text-white ${
                                  team.id === teamId ? "bg-blue-600/20" : ""
                                }`}
                                onClick={() => {
                                  setTeamId(team.id);
                                  setIsTeamDropdownOpen(false);
                                  setSearchTerm("");
                                }}
                              >
                                <span>{team.name}</span>
                                {team.id === teamId && (
                                  <Check className="h-4 w-4 text-blue-400" />
                                )}
                              </button>
                            ))}
                          </div>
                        )
                      )}

                      {Object.keys(teamsByDirection).length === 0 && (
                        <div className="px-3 py-4 text-center text-sm text-slate-400">
                          Aucune équipe trouvée pour "{searchTerm}"
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>

              <Button
                type="submit"
                className="w-full bg-blue-500 hover:bg-blue-600 text-white"
                disabled={!isValid || loading}
              >
                {loading ? "Création..." : "Créer le compte"}
              </Button>
            </form>

            <div className="mt-6 pt-6 border-t border-white/10">
              <p className="text-sm text-slate-400">
                Déjà un compte ?{" "}
                <button
                  type="button"
                  onClick={onSwitchToLogin}
                  className="text-blue-400 hover:text-blue-300 underline"
                >
                  Se connecter
                </button>
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
