"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 { UserProfile, Team } from "@/lib/types";
import { Search, Building2, ChevronDown, Check } from "lucide-react";

interface ProfileFormProps {
  teams: Team[];
  initialProfile?: UserProfile;
  onSubmit: (profile: UserProfile) => void;
}

export function ProfileForm({
  teams,
  initialProfile,
  onSubmit,
}: ProfileFormProps) {
  const [firstName, setFirstName] = useState(initialProfile?.firstName || "");
  const [lastName, setLastName] = useState(initialProfile?.lastName || "");
  const [teamId, setTeamId] = useState(initialProfile?.teamId || "");
  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 (firstName && lastName && teamId) {
      onSubmit({ firstName, lastName, teamId });
    }
  };

  const isValid =
    firstName.length > 0 && lastName.length > 0 && 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; // max-height of dropdown

      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 (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>Informations personnelles</CardTitle>
        <CardDescription>
          Renseignez vos informations pour commencer votre auto-évaluation
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="firstName">Prénom</Label>
            <Input
              id="firstName"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              placeholder="Votre prénom"
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="lastName">Nom</Label>
            <Input
              id="lastName"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              placeholder="Votre nom"
              required
            />
          </div>

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

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

                  {/* Liste des équipes groupées par direction */}
                  {Object.entries(teamsByDirection).map(
                    ([direction, directionTeams]) => (
                      <div key={direction}>
                        {/* En-tête de direction (non-cliquable) */}
                        <div className="px-3 py-2 text-sm font-semibold text-muted-foreground bg-muted/30 border-b border-border flex items-center gap-2">
                          <Building2 className="h-3 w-3" />
                          {direction}
                        </div>
                        {/* Équipes de cette direction */}
                        {directionTeams.map((team) => (
                          <button
                            key={team.id}
                            type="button"
                            className={`w-full px-3 py-2 text-left hover:bg-muted/50 flex items-center justify-between ${
                              team.id === teamId ? "bg-muted" : ""
                            }`}
                            onClick={() => {
                              setTeamId(team.id);
                              setIsTeamDropdownOpen(false);
                              setSearchTerm("");
                            }}
                          >
                            <span>{team.name}</span>
                            {team.id === teamId && (
                              <Check className="h-4 w-4 text-primary" />
                            )}
                          </button>
                        ))}
                      </div>
                    )
                  )}

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

          <Button type="submit" className="w-full" disabled={!isValid}>
            {initialProfile ? "Mettre à jour" : "Commencer l'évaluation"}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
