import { useState } from "react";
import { useProfileStore } from "../stores/profileStore";
import {
  UserCircle,
  Trash2,
  Edit2,
  Check,
  X,
  Camera,
  Dices,
  Loader2,
  Plus,
  CheckCircle2,
} from "lucide-react";
import { Card, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { PageHeader } from "../components/PageHeader";
import { Avatar } from "../components/ui/avatar";
import { resizeImage } from "../utils/image";
import { motion } from "framer-motion";

export default function Profiles() {
  const {
    profiles,
    activeProfileId,
    switchProfile,
    createProfile,
    updateProfile,
    deleteProfile,
  } = useProfileStore();

  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [isAdding, setIsAdding] = useState(false);
  const [newName, setNewName] = useState("");
  const [isGenerating, setIsGenerating] = useState<string | null>(null);

  const handleAdd = async () => {
    const name = newName.trim();
    if (!name) return;
    await createProfile(name);
    setNewName("");
    setIsAdding(false);
  };

  const handleDelete = async (id: string, name: string) => {
    if (profiles.length <= 1) {
      alert("Vous devez conserver au moins un profil.");
      return;
    }
    if (
      window.confirm(
        `Supprimer le profil "${name}" ?\n\nToutes ses parties, joueurs et emplacements seront définitivement supprimés.`,
      )
    ) {
      await deleteProfile(id);
    }
  };

  const startEdit = (id: string, name: string) => {
    setEditingId(id);
    setEditName(name);
  };

  const saveEdit = async (id: string) => {
    if (editName.trim()) {
      await updateProfile(id, { name: editName.trim() });
    }
    setEditingId(null);
  };

  const handleAvatarChange = async (
    profileId: string,
    event: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;
    try {
      const base64Image = await resizeImage(file);
      await updateProfile(profileId, { avatar: base64Image });
    } catch (e) {
      alert("Erreur lors de l'enregistrement de l'image.");
    }
  };

  const handleGenerateRandomAvatar = async (profileId: string) => {
    setIsGenerating(profileId);
    try {
      const seed = Math.random().toString(36).substring(7);
      const url = `https://api.dicebear.com/9.x/bottts-neutral/svg?seed=${seed}`;
      const response = await fetch(url);
      const svgText = await response.text();
      const encodedSvg = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`;
      await updateProfile(profileId, { avatar: encodedSvg });
    } catch (e) {
      alert(
        "Impossible de générer l'avatar. Vérifiez votre connexion internet.",
      );
    } finally {
      setIsGenerating(null);
    }
  };

  return (
    <div className="p-5 space-y-5 relative z-10">
      <PageHeader title="Profils" />

      <p className="text-sm text-muted-foreground px-2">
        Chaque profil possède ses propres parties, joueurs et emplacements.
        Touchez un profil pour l'activer.
      </p>

      {isAdding ? (
        <Card className="border-0 shadow-lg bg-background/90 backdrop-blur-md">
          <CardContent className="p-4 space-y-3">
            <Input
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="Nom du profil"
              className="h-12"
              autoFocus
            />
            <div className="flex space-x-2">
              <Button
                onClick={handleAdd}
                className="flex-1 rounded-full font-bold"
                disabled={!newName.trim()}
              >
                <Check className="w-5 h-5 mr-2" /> Créer
              </Button>
              <Button
                variant="ghost"
                onClick={() => {
                  setIsAdding(false);
                  setNewName("");
                }}
                className="rounded-full"
              >
                <X className="w-5 h-5" />
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : (
        <Button
          onClick={() => setIsAdding(true)}
          className="w-full h-14 rounded-[1.5rem] font-black text-lg shadow-lg"
        >
          <Plus className="w-6 h-6 mr-2" /> Nouveau profil
        </Button>
      )}

      <div className="space-y-4">
        {profiles.length === 0 ? (
          <div className="text-center text-muted-foreground py-12 flex flex-col items-center bg-background/60 backdrop-blur-sm rounded-[2rem]">
            <UserCircle className="w-16 h-16 mb-4 opacity-20" />
            <p className="font-bold text-lg">Aucun profil.</p>
          </div>
        ) : (
          profiles.map((profile, index) => {
            const isActive = profile.id === activeProfileId;
            return (
              <motion.div
                key={profile.id}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{
                  delay: index * 0.05,
                  type: "spring",
                  stiffness: 100,
                }}
              >
                <Card
                  className={`border-0 shadow-lg backdrop-blur-md overflow-visible relative group transition-colors ${
                    isActive
                      ? "bg-primary/10 ring-2 ring-primary/40"
                      : "bg-background/90 cursor-pointer"
                  }`}
                  onClick={() => {
                    if (!isActive && editingId !== profile.id) {
                      switchProfile(profile.id);
                    }
                  }}
                >
                  <CardContent className="p-4 flex items-center justify-between">
                    {editingId === profile.id ? (
                      <div className="flex items-center space-x-2 flex-1 mr-2 relative z-10">
                        <Input
                          value={editName}
                          onChange={(e) => setEditName(e.target.value)}
                          className="h-12"
                          autoFocus
                        />
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => saveEdit(profile.id)}
                          className="text-green-600 bg-green-500/10 hover:bg-green-500/20"
                        >
                          <Check className="w-6 h-6" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => setEditingId(null)}
                          className="text-muted-foreground bg-black/5 hover:bg-black/10 dark:bg-white/5 dark:hover:bg-white/10"
                        >
                          <X className="w-6 h-6" />
                        </Button>
                      </div>
                    ) : (
                      <>
                        <div className="flex flex-col items-center mr-4 shrink-0 gap-1.5">
                          <div
                            className="relative group/avatar cursor-pointer"
                            onClick={(e) => {
                              e.stopPropagation();
                              document
                                .getElementById(`profile-avatar-${profile.id}`)
                                ?.click();
                            }}
                          >
                            <Avatar
                              src={profile.avatar}
                              name={profile.name}
                              size="lg"
                              className="shadow-md border-4 border-background"
                            />
                            <div className="absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover/avatar:opacity-100 transition-opacity">
                              <Camera className="w-5 h-5 text-white" />
                            </div>
                            <input
                              type="file"
                              id={`profile-avatar-${profile.id}`}
                              className="hidden"
                              accept="image/*"
                              onChange={(e) =>
                                handleAvatarChange(profile.id, e)
                              }
                            />
                          </div>
                          <Button
                            variant="ghost"
                            size="sm"
                            disabled={isGenerating === profile.id}
                            className="h-6 px-3 rounded-full text-[10px] font-black uppercase tracking-wider bg-primary/10 text-primary hover:bg-primary/20 transition-colors"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleGenerateRandomAvatar(profile.id);
                            }}
                          >
                            {isGenerating === profile.id ? (
                              <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                            ) : (
                              <Dices className="w-3 h-3 mr-1" />
                            )}
                            Aléatoire
                          </Button>
                        </div>
                        <div className="flex-1 min-w-0">
                          <span className="font-black text-xl truncate block tracking-tight">
                            {profile.name}
                          </span>
                          {isActive && (
                            <span className="inline-flex items-center text-xs font-bold text-primary mt-0.5">
                              <CheckCircle2 className="w-3.5 h-3.5 mr-1" />
                              Profil actif
                            </span>
                          )}
                        </div>
                        <div className="flex items-center shrink-0 space-x-1 relative z-10">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={(e) => {
                              e.stopPropagation();
                              startEdit(profile.id, profile.name);
                            }}
                            className="text-muted-foreground hover:bg-black/5 dark:hover:bg-white/5"
                          >
                            <Edit2 className="w-5 h-5" />
                          </Button>
                          {profiles.length > 1 && (
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDelete(profile.id, profile.name);
                              }}
                              className="text-destructive hover:bg-destructive/10"
                            >
                              <Trash2 className="w-5 h-5" />
                            </Button>
                          )}
                        </div>
                      </>
                    )}
                  </CardContent>
                </Card>
              </motion.div>
            );
          })
        )}
      </div>
    </div>
  );
}
