'use client';

import { useState, useEffect } from 'react';
import { 
  Search, 
  Trash2, 
  Download, 
  Mail, 
  Phone, 
  Globe, 
  MoreVertical,
  Filter,
  Loader2,
  AlertCircle,
  Activity,
  ArrowRight,
  X,
  MapPin,
  ExternalLink
} from 'lucide-react';
import { DashboardHeader } from '@/components/DashboardHeader';

interface Lead {
  id: string;
  name: string;
  email: string | null;
  phone: string | null;
  website: string | null;
  address: string | null;
  industry: string;
  source: string;
  qualityScore: number;
  status: string;
}

export default function LeadsPage() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedLeads, setSelectedLeads] = useState<Set<string>>(new Set());
  const [selectedLeadData, setSelectedLeadData] = useState<Lead | null>(null);

  const toggleLead = (id: string) => {
    const next = new Set(selectedLeads);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelectedLeads(next);
  };

  useEffect(() => {
    fetchLeads();
    const interval = setInterval(fetchLeads, 5000);
    return () => clearInterval(interval);
  }, []);

  const fetchLeads = async () => {
    try {
      const res = await fetch('/api/leads?complete=true');
      const data = await res.json();
      setLeads(data.leads || []);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  const deleteLeads = async (ids: string[]) => {
    if (!confirm(`Are you sure you want to delete ${ids.length} records?`)) return;
    try {
      await fetch('/api/leads', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids })
      });
      fetchLeads();
      setSelectedLeads(new Set());
    } catch (e) {
      console.error(e);
    }
  };

  const exportLeads = async () => {
    const res = await fetch('/api/export', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ids: Array.from(selectedLeads) })
    });
    const blob = await res.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `leads_export_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
  };

  const filteredLeads = leads.filter(l => 
    (l.name ?? '').toLowerCase().includes(searchQuery.toLowerCase()) ||
    (l.industry ?? '').toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="flex-1 flex flex-col bg-white text-slate-900 font-sans">

      <main className="flex-1 p-4 lg:p-10 space-y-8 lg:space-y-12 overflow-y-auto w-full max-w-[1400px] mx-auto animate-fade-in shadow-inner bg-slate-50/20">
        
        {/* Search & Actions */}
        <section className="space-y-6">
           <div className="bg-white border border-slate-100 p-3 lg:p-4 rounded-[24px] lg:rounded-[32px] shadow-sm flex flex-col md:flex-row gap-4 items-center justify-between">
             <div className="relative w-full lg:w-[500px] group">
               <Search className="absolute left-6 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-slate-900 transition-colors" />
               <input 
                 type="text" 
                 placeholder="Search by name, industry..."
                 className="w-full bg-slate-50 border border-transparent rounded-[18px] lg:rounded-[22px] pl-14 pr-6 py-3.5 lg:py-4 text-[14px] lg:text-[15px] text-slate-900 focus:bg-white focus:border-slate-200 transition-all outline-none font-medium placeholder:text-slate-300"
                 value={searchQuery}
                 onChange={(e) => setSearchQuery(e.target.value)}
               />
             </div>

             <div className="flex items-center gap-3 w-full sm:w-auto">
                {selectedLeads.size > 0 && (
                  <div className="flex items-center gap-2 animate-in fade-in slide-in-from-right-4 duration-500 w-full sm:w-auto">
                     <button 
                       onClick={() => deleteLeads(Array.from(selectedLeads))}
                       className="flex-1 sm:flex-none px-4 lg:px-6 py-2.5 bg-red-50 text-red-600 hover:bg-red-100 rounded-full text-[12px] lg:text-[13px] font-bold transition-all"
                     >
                       Delete
                     </button>
                     <button 
                       onClick={exportLeads}
                       className="flex-1 sm:flex-none px-4 lg:px-6 py-2.5 bg-[#121212] text-white hover:bg-black rounded-full text-[12px] lg:text-[13px] font-bold transition-all shadow-sm"
                     >
                       Export {selectedLeads.size}
                     </button>
                  </div>
                )}
             </div>
           </div>
        </section>

        {/* Inventory Table / Card View */}
        <section className="bg-white border border-slate-100 rounded-[24px] lg:rounded-[40px] overflow-hidden shadow-sm min-h-[400px]">
          
          {/* Mobile Card View (shown only on small screens) */}
          <div className="lg:hidden divide-y divide-slate-100">
            {loading ? (
              <div className="py-20 text-center flex flex-col items-center gap-4">
                <Loader2 className="w-6 h-6 text-slate-900 animate-spin" />
                <p className="text-[14px] font-serif italic text-slate-400">Syncing database...</p>
              </div>
            ) : filteredLeads.length === 0 ? (
               <div className="py-20 text-center px-6">
                <p className="text-[14px] font-serif italic text-slate-400">No matching tactical data found.</p>
              </div>
            ) : filteredLeads.map((lead) => (
              <div key={lead.id} className="p-5 space-y-4">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <input 
                      type="checkbox" 
                      className="w-4 h-4 rounded border-slate-200"
                      checked={selectedLeads.has(lead.id)}
                      onChange={() => toggleLead(lead.id)}
                    />
                    <div>
                      <h4 className="font-bold text-slate-900 text-[15px] leading-tight">{lead.name}</h4>
                      <p className="text-[12px] text-slate-400 font-medium">{lead.industry}</p>
                    </div>
                  </div>
                  <div className="h-8 w-8 rounded-full bg-slate-50 border border-slate-100 flex items-center justify-center font-bold text-[10px]">
                    {lead.qualityScore}%
                  </div>
                </div>
                
                <div className="grid grid-cols-1 gap-2 pl-7">
                  {lead.phone && (
                    <div className="flex items-center gap-2 text-[13px] text-slate-600">
                      <Phone className="w-3.5 h-3.5 text-slate-300" />
                      {lead.phone}
                    </div>
                  )}
                  {lead.email && (
                    <div className="flex items-center gap-2 text-[13px] text-slate-600">
                      <Mail className="w-3.5 h-3.5 text-slate-300" />
                      {lead.email}
                    </div>
                  )}
                  {lead.website && (
                    <div className="flex items-center gap-2 text-[13px] text-blue-500 font-medium truncate">
                      <ExternalLink className="w-3.5 h-3.5 text-blue-300" />
                      {lead.website}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* Desktop Table View (hidden on mobile) */}
          <div className="hidden lg:block overflow-auto relative">
            <table className="w-full text-left border-collapse min-w-[1000px]">
              <thead>
                <tr className="border-b border-slate-100 bg-slate-50/50">
                  <th className="p-8 w-16 text-center">
                    <input 
                      type="checkbox" 
                      className="w-4 h-4 rounded border-slate-200 text-slate-900 focus:ring-slate-900"
                      checked={selectedLeads.size === filteredLeads.length && filteredLeads.length > 0}
                      onChange={(e) => {
                        if (e.target.checked) setSelectedLeads(new Set(filteredLeads.map(l => l.id)));
                        else setSelectedLeads(new Set());
                      }}
                    />
                  </th>
                  <th className="p-8 text-[11px] font-black text-slate-400 uppercase tracking-widest">Entity Metadata</th>
                  <th className="p-8 text-[11px] font-black text-slate-400 uppercase tracking-widest">Communications</th>
                  <th className="p-8 text-[11px] font-black text-slate-400 uppercase tracking-widest text-center">Integrity</th>
                  <th className="p-8 text-[11px] font-black text-slate-400 uppercase tracking-widest text-right">Context</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {loading ? (
                  <tr>
                    <td colSpan={5} className="py-32 text-center">
                      <div className="flex flex-col items-center gap-4">
                        <Loader2 className="w-8 h-8 text-slate-900 animate-spin" />
                        <p className="text-[16px] font-serif italic text-slate-400 tracking-tight">Syncing with neural database...</p>
                      </div>
                    </td>
                  </tr>
                ) : filteredLeads.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="py-32 text-center">
                      <p className="text-[16px] font-serif italic text-slate-400 tracking-tight">No intelligence matches found in current sector.</p>
                    </td>
                  </tr>
                ) : (
                  filteredLeads.map((lead) => (
                    <tr 
                      key={lead.id} 
                      className={`
                        group border-slate-100 transition-all hover:bg-slate-50/50
                        ${selectedLeads.has(lead.id) ? 'bg-blue-50/20' : ''}
                      `}
                    >
                      <td className="p-8 text-center">
                        <input 
                          type="checkbox" 
                          className="w-4 h-4 rounded border-slate-200 text-slate-900 focus:ring-slate-900" 
                          checked={selectedLeads.has(lead.id)}
                          onChange={() => toggleLead(lead.id)}
                        />
                      </td>
                      <td className="p-8">
                        <div className="space-y-1">
                          <p className="text-[16px] font-bold text-slate-900 tracking-tight leading-none mb-1.5">{lead.name}</p>
                          <div className="flex items-center gap-3">
                             <span className="text-[11px] font-black text-slate-400 border border-slate-100 px-2 py-0.5 rounded uppercase tracking-widest">{lead.industry}</span>
                             <span className="text-[11px] font-bold text-slate-300 uppercase tracking-tighter">{lead.source}</span>
                          </div>
                        </div>
                      </td>
                      <td className="p-8">
                        <div className="flex items-center gap-3">
                           {lead.email && (
                             <a 
                               href={`mailto:${lead.email}`}
                               onClick={(e) => e.stopPropagation()}
                               className="h-10 w-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-900 hover:border-slate-900 transition-all shadow-sm"
                               title={lead.email}
                             >
                               <Mail className="w-3.5 h-3.5" />
                             </a>
                           )}
                           {lead.phone && (
                             <a 
                               href={`tel:${lead.phone}`}
                               onClick={(e) => e.stopPropagation()}
                               className="h-10 w-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-900 hover:border-slate-900 transition-all shadow-sm"
                               title={lead.phone}
                             >
                               <Phone className="w-3.5 h-3.5" />
                             </a>
                           )}
                           {lead.website && (
                             <a 
                               href={lead.website.startsWith('http') ? lead.website : `https://${lead.website}`} 
                               target="_blank" 
                               rel="noopener noreferrer"
                               onClick={(e) => e.stopPropagation()}
                               className="h-10 w-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-900 hover:border-slate-900 transition-all shadow-sm"
                               title={lead.website}
                             >
                               <Globe className="w-3.5 h-3.5" />
                             </a>
                           )}
                        </div>
                      </td>
                      <td className="p-8">
                         <div className="flex flex-col items-center gap-1.5">
                            <span className={`text-[13px] font-serif italic tracking-tight ${lead.qualityScore >= 80 ? 'text-emerald-600' : 'text-slate-400'}`}>
                               {lead.qualityScore}% match
                            </span>
                            <div className="w-20 h-0.5 bg-slate-100 rounded-full overflow-hidden">
                               <div 
                                 className={`h-full ${lead.qualityScore >= 80 ? 'bg-emerald-500' : 'bg-slate-300'}`} 
                                 style={{ width: `${lead.qualityScore}%` }}
                               />
                            </div>
                         </div>
                      </td>
                      <td className="p-8 text-right">
                        <button 
                          onClick={(e) => { e.stopPropagation(); setSelectedLeadData(lead); }}
                          className="h-10 w-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-900 hover:border-slate-900 opacity-0 group-hover:opacity-100 transition-all shadow-sm ml-auto"
                        >
                          <MoreVertical className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </section>

        {/* Summary Metric Strip */}
        {!loading && leads.length > 0 && (
          <div className="p-8 bg-[#fcfcfc] border border-slate-100 rounded-[32px] flex items-center justify-between px-12">
             <div className="flex items-center gap-10">
                <div className="space-y-0.5">
                   <p className="text-[11px] font-black text-slate-300 uppercase tracking-widest">Total Inventory</p>
                   <p className="text-[20px] font-bold text-slate-900">{leads.length} records</p>
                </div>
                <div className="w-px h-8 bg-slate-100" />
                <div className="space-y-0.5">
                   <p className="text-[11px] font-black text-slate-300 uppercase tracking-widest">Growth</p>
                   <p className="text-[20px] font-bold text-slate-900">+12.4% <span className="text-[12px] text-emerald-500">MOM</span></p>
                </div>
             </div>
             
             <button className="flex items-center gap-2 text-[13px] font-bold text-slate-900 group">
                Database Management <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
             </button>
          </div>
        )}
      </main>

      {/* Lead Details Modal */}
      {selectedLeadData && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-4 animate-in fade-in duration-200">
           <div className="bg-white rounded-[32px] shadow-2xl w-full max-w-2xl overflow-hidden border border-slate-100 animate-in zoom-in-95 duration-200">
             <div className="p-8 pb-6 border-b border-slate-100 flex items-start justify-between">
                <div>
                  <h3 className="text-2xl font-bold text-slate-900 tracking-tight">{selectedLeadData.name}</h3>
                  <div className="flex items-center gap-3 mt-2">
                     <span className="px-3 py-1 bg-slate-50 border border-slate-100 text-slate-500 rounded-full text-xs font-bold uppercase tracking-widest">{selectedLeadData.industry}</span>
                     <span className="text-xs font-medium text-slate-400 uppercase tracking-widest">Source: {selectedLeadData.source}</span>
                  </div>
                </div>
                <button 
                  onClick={() => setSelectedLeadData(null)}
                  className="w-10 h-10 bg-slate-50 hover:bg-slate-100 text-slate-400 hover:text-slate-900 rounded-full flex items-center justify-center transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
             </div>
             <div className="p-8 space-y-8">
                {/* Contact Intel */}
                <div>
                   <h4 className="text-[11px] font-black text-slate-300 uppercase tracking-[0.2em] mb-4">Contact Intelligence</h4>
                   <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {selectedLeadData.email && (
                        <div className="p-4 rounded-2xl border border-slate-100 bg-slate-50/50 flex items-center gap-3">
                           <div className="w-10 h-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-400">
                             <Mail className="w-4 h-4" />
                           </div>
                           <div className="overflow-hidden">
                             <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">Primary Email</p>
                             <p className="text-sm font-medium text-slate-900 truncate">{selectedLeadData.email}</p>
                           </div>
                        </div>
                      )}
                      
                      {selectedLeadData.phone && (
                        <div className="p-4 rounded-2xl border border-slate-100 bg-slate-50/50 flex items-center gap-3">
                           <div className="w-10 h-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-400">
                             <Phone className="w-4 h-4" />
                           </div>
                           <div className="overflow-hidden">
                             <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">Direct Line</p>
                             <p className="text-sm font-medium text-slate-900 truncate">{selectedLeadData.phone}</p>
                           </div>
                        </div>
                      )}

                      {selectedLeadData.website && (
                        <div className="p-4 rounded-2xl border border-slate-100 bg-slate-50/50 flex items-center gap-3">
                           <div className="w-10 h-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-400">
                             <Globe className="w-4 h-4" />
                           </div>
                           <div className="overflow-hidden">
                             <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">Domain Node</p>
                             <a href={selectedLeadData.website.startsWith('http') ? selectedLeadData.website : `https://${selectedLeadData.website}`} target="_blank" rel="noopener noreferrer" className="text-sm font-medium text-blue-600 hover:underline truncate block">{selectedLeadData.website.replace(/^https?:\/\//, '')}</a>
                           </div>
                        </div>
                      )}

                      {selectedLeadData.address && (
                        <div className="p-4 rounded-2xl border border-slate-100 bg-slate-50/50 flex items-center gap-3">
                           <div className="w-10 h-10 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-400">
                             <MapPin className="w-4 h-4" />
                           </div>
                           <div className="overflow-hidden">
                             <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">Physical HQ</p>
                             <p className="text-sm font-medium text-slate-900 truncate" title={selectedLeadData.address}>{selectedLeadData.address}</p>
                           </div>
                        </div>
                      )}
                   </div>
                </div>

                {/* Score Intel */}
                <div>
                   <h4 className="text-[11px] font-black text-slate-300 uppercase tracking-[0.2em] mb-4">Integrity Matrix</h4>
                   <div className="p-5 rounded-2xl border border-slate-100 bg-slate-50 flex items-center justify-between">
                     <span className="text-sm font-bold text-slate-900">Neural Confidence Score</span>
                     <div className="flex items-center gap-3">
                       <span className={`text-lg font-serif italic tracking-tight ${selectedLeadData.qualityScore >= 80 ? 'text-emerald-600' : 'text-slate-400'}`}>
                          {selectedLeadData.qualityScore}% match
                       </span>
                       <div className="w-32 h-1 bg-slate-200 rounded-full overflow-hidden">
                          <div 
                            className={`h-full ${selectedLeadData.qualityScore >= 80 ? 'bg-emerald-500' : 'bg-slate-400'}`} 
                            style={{ width: `${selectedLeadData.qualityScore}%` }}
                          />
                       </div>
                     </div>
                   </div>
                </div>
             </div>
             <div className="p-6 bg-slate-50 border-t border-slate-100 flex justify-end">
                <button 
                  onClick={() => setSelectedLeadData(null)}
                  className="px-6 py-2.5 bg-slate-900 text-white rounded-full text-[13px] font-bold hover:bg-black transition-all"
                >
                  Close Intel
                </button>
             </div>
           </div>
        </div>
      )}
    </div>
  );
}
