"use client";

import React, { useState, useEffect } from "react";
import { db } from "@/lib/firebase";
import { collection, onSnapshot, addDoc, deleteDoc, doc } from "firebase/firestore";
import Link from "next/link";

interface Client {
  id: string;
  name: string;
  email: string;
  phone: string;
}

export default function ClientsPage() {
  const [clients, setClients] = useState<Client[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newClient, setNewClient] = useState({ name: "", email: "", phone: "" });

  useEffect(() => {
    const unsub = onSnapshot(collection(db, "clients"), (snap) => {
      const data = snap.docs.map(doc => ({ id: doc.id, ...doc.data() } as Client));
      setClients(data);
    });
    return () => unsub();
  }, []);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    await addDoc(collection(db, "clients"), newClient);
    setIsModalOpen(false);
    setNewClient({ name: "", email: "", phone: "" });
  };

  return (
    <div className="min-h-screen bg-[#0f172a] text-white p-6">
      <header className="flex justify-between items-center mb-10">
        <div>
          <Link href="/" className="text-blue-400 hover:text-blue-300 transition-colors flex items-center gap-2 mb-2">
            ← Dashboard
          </Link>
          <h1 className="text-4xl font-black">Directorio de Clientes</h1>
        </div>
        <button 
          onClick={() => setIsModalOpen(true)}
          className="px-8 py-3 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 rounded-2xl font-bold transition-all shadow-xl shadow-purple-900/20"
        >
          ➕ Nuevo Cliente
        </button>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {clients.map((c) => (
          <div key={c.id} className="bg-white/5 border border-white/10 rounded-[32px] p-8 backdrop-blur-xl relative overflow-hidden group hover:border-white/20 transition-all">
            <div className="absolute -right-4 -top-4 w-24 h-24 bg-purple-500/10 blur-3xl rounded-full"></div>
            <div className="relative z-10">
              <div className="w-14 h-14 bg-white/10 rounded-2xl flex items-center justify-center text-2xl mb-6">👤</div>
              <h3 className="text-xl font-bold mb-2 group-hover:text-purple-400 transition-colors">{c.name}</h3>
              <p className="text-gray-400 text-sm mb-4">{c.email}</p>
              <div className="flex items-center gap-2 text-xs font-mono text-purple-300 bg-purple-500/10 w-fit px-3 py-1 rounded-full border border-purple-500/20">
                📞 {c.phone}
              </div>
              <div className="mt-8 pt-6 border-t border-white/5 flex gap-4">
                <button className="text-xs font-bold text-gray-500 hover:text-white transition-colors uppercase tracking-widest">Editar</button>
                <button onClick={() => deleteDoc(doc(db, "clients", c.id))} className="text-xs font-bold text-gray-700 hover:text-red-400 transition-colors uppercase tracking-widest ml-auto">Eliminar</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {isModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-md flex items-center justify-center p-6 z-50">
          <div className="bg-[#1e293b] border border-white/10 p-10 rounded-[48px] w-full max-w-md shadow-2xl animate-in fade-in slide-in-from-bottom-5">
            <h2 className="text-3xl font-black mb-8 text-center uppercase tracking-tighter">Registrar Cliente</h2>
            <form onSubmit={handleAdd} className="space-y-4">
              <input 
                type="text" placeholder="Nombre completo" required
                value={newClient.name} onChange={e => setNewClient({...newClient, name: e.target.value})}
                className="w-full bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-purple-500/50"
              />
              <input 
                type="email" placeholder="Email" required
                value={newClient.email} onChange={e => setNewClient({...newClient, email: e.target.value})}
                className="w-full bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-purple-500/50"
              />
              <input 
                type="tel" placeholder="Teléfono" required
                value={newClient.phone} onChange={e => setNewClient({...newClient, phone: e.target.value})}
                className="w-full bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-purple-500/50"
              />
              <div className="flex flex-col gap-3 mt-10">
                <button type="submit" className="w-full bg-white text-[#0f172a] py-5 rounded-2xl font-black transition-all hover:bg-gray-200">CREAR CLIENTE</button>
                <button type="button" onClick={() => setIsModalOpen(false)} className="w-full py-4 text-gray-500 font-bold hover:text-white transition-colors">CANCELAR</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
