import { useState } from "react";
import { useLiveQuery } from "dexie-react-hooks";
import { db } from "../database/db";
import { MapPin, Trash2, Edit2, Check, X, Plus, Home } 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 { generateId } from "../utils/id";
import { useProfileStore } from "../stores/profileStore";
import { motion } from "framer-motion";

export default function Locations() {
  const activeProfileId = useProfileStore((s) => s.activeProfileId);
  const locations = useLiveQuery(
    async () => {
      if (!activeProfileId) return [];
      return db.locations
        .where("profileId")
        .equals(activeProfileId)
        .and((l) => !l.deletedAt)
        .sortBy("name");
    },
    [activeProfileId],
  );
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [editAddress, setEditAddress] = useState("");
  const [isAdding, setIsAdding] = useState(false);
  const [newName, setNewName] = useState("");
  const [newAddress, setNewAddress] = useState("");

  const handleAdd = async () => {
    const name = newName.trim();
    if (!name || !activeProfileId) return;

    const now = Date.now();
    await db.locations.add({
      id: generateId(),
      name,
      address: newAddress.trim() || undefined,
      createdAt: now,
      updatedAt: now,
      profileId: activeProfileId,
    });

    setNewName("");
    setNewAddress("");
    setIsAdding(false);
  };

  const handleDelete = async (id: string, name: string) => {
    if (window.confirm(`Êtes-vous sûr de vouloir supprimer "${name}" ?`)) {
      // Soft-delete (tombstone) so the deletion can propagate to the server.
      await db.locations.update(id, { deletedAt: Date.now() });
    }
  };

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

  const saveEdit = async (id: string) => {
    const name = editName.trim();
    if (name) {
      await db.locations.update(id, {
        name,
        address: editAddress.trim() || undefined,
        updatedAt: Date.now(),
      });
    }
    setEditingId(null);
  };

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

      {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 (ex: Maison, Le Valet d'Or...)"
              className="h-12"
              autoFocus
            />
            <Input
              value={newAddress}
              onChange={(e) => setNewAddress(e.target.value)}
              placeholder="Adresse (optionnel)"
              className="h-12"
            />
            <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" /> Ajouter
              </Button>
              <Button
                variant="ghost"
                onClick={() => {
                  setIsAdding(false);
                  setNewName("");
                  setNewAddress("");
                }}
                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" /> Nouvel emplacement
        </Button>
      )}

      <div className="space-y-4">
        {!locations || locations.length === 0 ? (
          <div className="text-center text-muted-foreground py-12 flex flex-col items-center bg-background/60 backdrop-blur-sm rounded-[2rem]">
            <MapPin className="w-16 h-16 mb-4 opacity-20" />
            <p className="font-bold text-lg">Aucun emplacement enregistré.</p>
            <p className="text-sm mt-1 max-w-[250px]">
              Ajoutez votre maison ou vos enseignes de jeux favorites.
            </p>
          </div>
        ) : (
          locations.map((location, index) => (
            <motion.div
              key={location.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 bg-background/90 backdrop-blur-md overflow-visible relative group">
                <div className="absolute -left-2 -top-2 w-8 h-8 rounded-full bg-primary/20 blur-md pointer-events-none group-hover:bg-primary/40 transition-colors" />

                <CardContent className="p-4 flex items-center justify-between">
                  {editingId === location.id ? (
                    <div className="flex flex-col space-y-2 flex-1 mr-2 relative z-10">
                      <Input
                        value={editName}
                        onChange={(e) => setEditName(e.target.value)}
                        className="h-12"
                        autoFocus
                      />
                      <Input
                        value={editAddress}
                        onChange={(e) => setEditAddress(e.target.value)}
                        placeholder="Adresse (optionnel)"
                        className="h-12"
                      />
                      <div className="flex space-x-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => saveEdit(location.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>
                  ) : (
                    <>
                      <div className="flex items-center mr-4 shrink-0">
                        <div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center shadow-md border-4 border-background">
                          <Home className="w-6 h-6 text-primary" />
                        </div>
                      </div>
                      <div className="flex-1 min-w-0">
                        <span className="font-black text-xl truncate block tracking-tight">
                          {location.name}
                        </span>
                        {location.address && (
                          <span className="text-sm text-muted-foreground truncate block">
                            {location.address}
                          </span>
                        )}
                      </div>
                      <div className="flex items-center shrink-0 space-x-1 relative z-10">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() =>
                            startEdit(location.id, location.name, location.address)
                          }
                          className="text-muted-foreground hover:bg-black/5 dark:hover:bg-white/5"
                        >
                          <Edit2 className="w-5 h-5" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDelete(location.id, location.name)}
                          className="text-destructive hover:bg-destructive/10"
                        >
                          <Trash2 className="w-5 h-5" />
                        </Button>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            </motion.div>
          ))
        )}
      </div>
    </div>
  );
}
