"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, Save, X } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

interface AccountFormProps {
  initialProfile: UserProfile;
  teams: Team[];
}

export function AccountForm({ initialProfile, teams }: AccountFormProps) {
  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 [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const teamDropdownRef = useRef<HTMLDivElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState<"below" | "above">(
    "below"
  );
  const { toast } = useToast();

  const hasChanges =
    firstName !== initialProfile.firstName ||
    lastName !== initialProfile.lastName ||
    teamId !== initialProfile.teamId;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!hasChanges) return;

    setLoading(true);
    try {
      const response = await fetch("/api/auth/profile", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          firstName,
          lastName,
          teamId,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Erreur lors de la mise à jour");
      }

      const result = await response.json();

      toast({
        title: "Profil mis à jour",
        description:
          result.message || "Vos informations ont été modifiées avec succès.",
      });

      setIsEditing(false);
    } catch (error: any) {
      console.error("Update failed:", error);
      toast({
        title: "Erreur de mise à jour",
        description: error.message || "Erreur lors de la mise à jour du profil",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setFirstName(initialProfile.firstName);
    setLastName(initialProfile.lastName);
    setTeamId(initialProfile.teamId);
    setIsEditing(false);
  };

  // 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 (
    <Card>
      <CardHeader>
        <CardTitle>Informations personnelles</CardTitle>
        <CardDescription>
          Modifiez vos informations personnelles. Vos identifiants de connexion
          (email et mot de passe) ne peuvent pas être modifiés ici.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-2 gap-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"
                disabled={!isEditing}
                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"
                disabled={!isEditing}
                required
              />
            </div>
          </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}
                disabled={!isEditing}
              >
                <span
                  className={
                    selectedTeam ? "text-foreground" : "text-muted-foreground"
                  }
                >
                  {selectedTeam
                    ? selectedTeam.name
                    : "Sélectionnez votre équipe"}
                </span>
                <ChevronDown className="h-4 w-4" />
              </Button>

              {isTeamDropdownOpen && isEditing && (
                <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"
                  }`}
                >
                  <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..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-8 h-8 text-sm"
                        autoFocus
                      />
                    </div>
                  </div>

                  {Object.entries(teamsByDirection).map(
                    ([direction, directionTeams]) => (
                      <div key={direction}>
                        <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>
                        {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>
                    )
                  )}

                  {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>

          <div className="flex gap-4 justify-end">
            {!isEditing ? (
              <Button
                type="button"
                onClick={() => setIsEditing(true)}
                className="bg-blue-500 hover:bg-blue-600"
              >
                Modifier
              </Button>
            ) : (
              <>
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleCancel}
                  disabled={loading}
                >
                  <X className="w-4 h-4 mr-2" />
                  Annuler
                </Button>
                <Button
                  type="submit"
                  disabled={!hasChanges || loading}
                  className="bg-blue-500 hover:bg-blue-600"
                >
                  <Save className="w-4 h-4 mr-2" />
                  {loading ? "Sauvegarde..." : "Sauvegarder"}
                </Button>
              </>
            )}
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
