'use client';

import { useState, useEffect } from 'react';
import { 
  Search, 
  MapPin, 
  Download, 
  Loader2, 
  Globe, 
  Mail, 
  ShieldCheck,
  Target,
  ArrowRight,
  Database,
  PlusIcon
} from 'lucide-react';
import { DashboardHeader } from '@/components/DashboardHeader';
import { INDUSTRIES, LOCATIONS } from '@/lib/constants';

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

export default function ScraperPage() {
  const [keyword, setKeyword] = useState('');
  const [location, setLocation] = useState('');
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<Lead[]>([]);
  const [selectedLeads, setSelectedLeads] = useState<Set<string>>(new Set());

  const [enrichingLeads, setEnrichingLeads] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);
  const [sources, setSources] = useState<any[]>([]);
  const [isLoadingSources, setIsLoadingSources] = useState(false);
  
  const [emailFilter, setEmailFilter] = useState<boolean>(true);
  const [websiteFilter, setWebsiteFilter] = useState<boolean>(true);
  const [loadingStepIndex, setLoadingStepIndex] = useState(0);

  const loadingSteps = [
    'Generating coordinates...',
    'Scraping target sectors...',
    'Validating entities...',
    'Collecting leads...',
    'Enriching data footprint...',
    'Finishing extraction...'
  ];

  useEffect(() => {
    if (loading) {
      setLoadingStepIndex(0);
      const interval = setInterval(() => {
        setLoadingStepIndex(prev => Math.min(prev + 1, loadingSteps.length - 1));
      }, 2500);
      return () => clearInterval(interval);
    }
  }, [loading]);

  const fetchSources = async () => {
    setIsLoadingSources(true);
    try {
      const res = await fetch('/api/sources');
      const data = await res.json();
      setSources(data.sources || []);
    } catch (err) {
      console.error('Failed to fetch lead sources', err);
    } finally {
      setIsLoadingSources(false);
    }
  };

  const handleSearch = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    
    if (!keyword || !location) return;

    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          keyword, 
          location,
          limit: 50
        }),
      });

      if (!res.ok) {
        throw new Error('Intelligence extraction failed. Please try again.');
      }

      const data = await res.json();
      
      const mappedLeads: Lead[] = (data.results || []).map((item: any, index: number) => ({
        id: item.id || `temp-${index}`,
        name: item.businessName || item.name || 'Unnamed Business',
        email: item.email || '',
        phone: item.phone || '',
        website: item.website || '',
        address: item.address || '',
        industry: item.category || keyword,
        source: item.source || 'Aggregated',
        qualityScore: Math.round((item.confidenceScore || 0.8) * 100),
      }));

      setResults(mappedLeads);
      setSelectedLeads(new Set());
      if (mappedLeads.length === 0) {
        setError('No tactical data found. Try broader keywords or a different location.');
      }
    } catch (error: any) {
      console.error('Search failed', error);
      setError(error.message || 'Communication failure with extraction nodes.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSources();
  }, []);

  const handleEnrich = async (leadId: string) => {
    if (enrichingLeads.has(leadId)) return;
    
    setEnrichingLeads(prev => new Set(prev).add(leadId));
    try {
      const res = await fetch('/api/enrich', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ leadId }),
      });
      
      if (!res.ok) throw new Error('Enrichment failed');
      
      const data = await res.json();
      
      setResults(prev => prev.map(l => 
        l.id === leadId 
          ? { ...l, email: data.email || l.email, phone: data.phone || l.phone, qualityScore: data.email ? 95 : l.qualityScore } 
          : l
      ));
    } catch (err) {
      console.error('Failed to enrich lead', err);
    } finally {
      setEnrichingLeads(prev => {
        const next = new Set(prev);
        next.delete(leadId);
        return next;
      });
    }
  };

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

  const filteredResults = results.filter(lead => {
    const emailMatch = emailFilter ? !!lead.email : true;
    const websiteMatch = websiteFilter ? !!lead.website : true;
    return emailMatch && websiteMatch;
  });

  const exportLeads = () => {
    if (selectedLeads.size === 0) return;
    const toExport = results.filter(r => selectedLeads.has(r.id));
    const headers = "Name,Industry,Email,Phone,Website,Address";
    const rows = toExport.map(l => `"${l.name}","${l.industry}","${l.email}","${l.phone}","${l.website}","${l.address}"`).join("\n");
    const csvContent = "data:text/csv;charset=utf-8," + headers + "\n" + rows;
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `leadforge_export_${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  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 Panel */}
        <section className="bg-white border border-slate-100 rounded-[24px] lg:rounded-[40px] p-6 lg:p-10 shadow-sm relative overflow-hidden">
          <div className="absolute top-0 right-0 p-8 lg:p-10 opacity-[0.03] pointer-events-none">
             <Target className="w-32 h-32 lg:w-48 lg:h-48 text-slate-900" />
          </div>
          
          <div className="mb-8 lg:mb-10 space-y-1 relative z-10">
            <h2 className="text-[10px] lg:text-[12px] font-bold uppercase tracking-widest text-slate-400">Search Parameters</h2>
            <p className="text-[20px] lg:text-[24px] font-medium tracking-tight">Configure extraction <span className="font-serif italic text-slate-400 font-normal lowercase">filters</span></p>
          </div>

          <form onSubmit={handleSearch} className="grid grid-cols-1 lg:grid-cols-12 gap-6 lg:gap-8 relative z-10">
            <div className="lg:col-span-5 space-y-2 lg:space-y-3">
              <label className="text-[11px] lg:text-[12px] font-bold text-slate-400 uppercase tracking-wide ml-1">Market Segment</label>
              <div className="relative group/input">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-slate-900 transition-colors" />
                <input 
                  type="text" 
                  list="industry-list"
                  placeholder="e.g. Luxury Real Estate"
                  className="w-full bg-slate-50 border border-transparent rounded-[14px] lg:rounded-[18px] pl-12 pr-4 py-3.5 lg:py-4 text-[14px] lg:text-[15px] text-slate-900 focus:bg-white focus:border-slate-300 transition-all outline-none"
                  value={keyword}
                  onChange={(e) => setKeyword(e.target.value)}
                />
                <datalist id="industry-list">
                  {INDUSTRIES.map((industry) => (
                    <option key={industry} value={industry} />
                  ))}
                </datalist>
              </div>
            </div>

            <div className="lg:col-span-4 space-y-2 lg:space-y-3">
              <label className="text-[11px] lg:text-[12px] font-bold text-slate-400 uppercase tracking-wide ml-1">Location Geometry</label>
              <div className="relative group/input">
                <MapPin className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-slate-900 transition-colors" />
                <input 
                  type="text" 
                  list="location-list"
                  placeholder="e.g. Manhattan, NY or 40.7, -74.0"
                  className="w-full bg-slate-50 border border-transparent rounded-[14px] lg:rounded-[18px] pl-12 pr-4 py-3.5 lg:py-4 text-[14px] lg:text-[15px] text-slate-900 focus:bg-white focus:border-slate-300 transition-all outline-none"
                  value={location}
                  onChange={(e) => setLocation(e.target.value)}
                />
                <datalist id="location-list">
                  {LOCATIONS.map((loc) => (
                    <option key={loc} value={loc} />
                  ))}
                </datalist>
              </div>
            </div>

            <div className="lg:col-span-3 flex items-end">
              <button 
                type="submit"
                disabled={loading}
                className="w-full bg-[#121212] text-white hover:bg-black disabled:opacity-50 font-bold text-[14px] lg:text-[15px] py-3.5 lg:py-4 px-6 rounded-[14px] lg:rounded-[18px] flex items-center justify-center gap-2 transition-all shadow-sm active:scale-[0.98]"
              >
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ShieldCheck className="w-4 h-4" />}
                {loading ? 'Processing...' : 'Execute Scan'}
              </button>
            </div>
          </form>

          {error && (
            <div className="mt-8 flex flex-col gap-4">
              <div className="p-5 rounded-2xl bg-red-50 border border-red-100 text-red-600 text-[13px] font-bold flex items-center gap-3">
                <ShieldCheck className="w-4 h-4" />
                {error}
              </div>
            </div>
          )}

          {/* Source Diagnostics */}
          <div className="mt-8 pt-8 border-t border-slate-100 flex flex-wrap items-center gap-4">
            <span className="text-[11px] font-black text-slate-300 uppercase tracking-[0.2em] mr-2">Extraction Nodes:</span>
            {isLoadingSources ? (
              <Loader2 className="w-3 h-3 animate-spin text-slate-300" />
            ) : (
              sources.map(source => (
                <div 
                  key={source.id}
                  className={`flex items-center gap-2 px-3 py-1.5 rounded-full border text-[10px] font-black uppercase tracking-wider transition-all ${
                    source.available 
                      ? 'bg-green-50 border-green-100 text-green-600' 
                      : 'bg-slate-50 border-slate-100 text-slate-400'
                  }`}
                  title={source.description}
                >
                  <div className={`w-1.5 h-1.5 rounded-full ${source.available ? 'bg-green-500 animate-pulse' : 'bg-slate-300'}`} />
                  {source.name}
                </div>
              ))
            )}
          </div>
        </section>

        {/* Intelligence Results Section */}
        <section className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 px-2">
              <div className="flex items-center gap-4">
                {results.length > 0 && (
                  <div className="flex items-center gap-2">
                     <button
                      onClick={() => setEmailFilter(!emailFilter)}
                      className={`px-3 py-1.5 rounded-full border text-[11px] font-bold transition-all flex items-center gap-1.5 shadow-sm ${
                        emailFilter ? 'bg-slate-900 text-white border-slate-900' : 'bg-white text-slate-500 border-slate-100'
                      }`}
                     >
                       <Mail className="w-3 h-3" />
                       Verified
                     </button>
                     <button
                      onClick={() => setWebsiteFilter(!websiteFilter)}
                      className={`px-3 py-1.5 rounded-full border text-[11px] font-bold transition-all flex items-center gap-1.5 shadow-sm ${
                        websiteFilter ? 'bg-slate-900 text-white border-slate-900' : 'bg-white text-slate-500 border-slate-100'
                      }`}
                     >
                       <Globe className="w-3 h-3" />
                       Web
                     </button>
                  </div>
                )}
              </div>
              
              {selectedLeads.size > 0 && (
                <button 
                  onClick={exportLeads}
                  className="w-full sm:w-auto px-6 py-2.5 bg-[#121212] text-white hover:bg-black rounded-full text-[13px] font-bold transition-all shadow-sm flex items-center justify-center gap-2"
                >
                  <Database className="w-4 h-4" />
                  Export {selectedLeads.size} leads
                </button>
              )}
            </div>

            <div className="bg-white border border-slate-100 rounded-[24px] lg:rounded-[32px] overflow-hidden shadow-sm min-h-[300px]">
              {loading ? (
                <div className="py-24 flex flex-col items-center justify-center px-6 text-center">
                  <Loader2 className="w-8 h-8 text-slate-900 animate-spin mb-4" />
                  <h3 className="text-[16px] font-bold text-slate-900">{loadingSteps[loadingStepIndex]}</h3>
                  <p className="text-[13px] text-slate-500 mt-2">Connecting to global intelligence network...</p>
                </div>
              ) : results.length === 0 ? (
                <div className="py-24 flex flex-col items-center justify-center px-6 text-center">
                  <Target className="w-10 h-10 text-slate-200 mb-4" />
                  <p className="text-[14px] font-serif italic text-slate-400">Waiting for extraction coordinates...</p>
                </div>
              ) : (
                <>
                  {/* Mobile Results View */}
                  <div className="lg:hidden divide-y divide-slate-100">
                    {filteredResults.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 text-slate-900 focus:ring-slate-900"
                              checked={selectedLeads.has(lead.id)}
                              onChange={() => toggleLead(lead.id)}
                            />
                            <div>
                               <p className="text-[15px] font-bold text-slate-900 tracking-tight">{lead.name}</p>
                               <p className="text-[11px] text-slate-400 font-bold uppercase tracking-wider">{lead.industry}</p>
                            </div>
                          </div>
                          <div className="flex flex-col items-end gap-1">
                             <span className="text-[10px] font-black text-slate-900">{lead.qualityScore}%</span>
                             <div className="h-1 w-12 bg-slate-100 rounded-full overflow-hidden">
                                <div className="h-full bg-slate-900" style={{ width: `${lead.qualityScore}%` }} />
                             </div>
                          </div>
                        </div>
                        
                        <div className="space-y-2">
                           <p className="text-[12px] text-slate-500 flex items-center gap-2">
                              <MapPin className="w-3.5 h-3.5 text-slate-300" /> {lead.address}
                           </p>
                           <div className="flex flex-wrap gap-3 pt-1">
                              {lead.email && (
                                <div className="flex items-center gap-2 text-[12px] font-bold text-slate-900">
                                  <Mail className="w-3.5 h-3.5 text-slate-400" /> {lead.email}
                                </div>
                              )}
                              {lead.website && (
                                <a 
                                  href={lead.website.startsWith('http') ? lead.website : `https://${lead.website}`}
                                  target="_blank" rel="noopener noreferrer"
                                  className="flex items-center gap-2 text-[12px] text-slate-400 hover:text-slate-900"
                                >
                                  <Globe className="w-3.5 h-3.5" /> Site
                                </a>
                              )}
                           </div>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Desktop Table View */}
                  <div className="hidden lg:block overflow-x-auto">
                    <table className="w-full border-collapse">
                      <thead>
                        <tr className="bg-slate-50/50 border-b border-slate-100">
                          <th className="p-6 text-center w-20">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4 rounded border-slate-200"
                              checked={selectedLeads.size === filteredResults.length && filteredResults.length > 0}
                              onChange={() => {
                                if (selectedLeads.size === filteredResults.length) setSelectedLeads(new Set());
                                else setSelectedLeads(new Set(filteredResults.map(l => l.id)));
                              }}
                            />
                          </th>
                          <th className="p-6 text-left text-[11px] font-black text-slate-400 uppercase tracking-widest">Entity</th>
                          <th className="p-6 text-left text-[11px] font-black text-slate-400 uppercase tracking-widest">Intelligence</th>
                          <th className="p-6 text-center text-[11px] font-black text-slate-400 uppercase tracking-widest w-40">Quality</th>
                          <th className="p-6 text-right text-[11px] font-black text-slate-400 uppercase tracking-widest w-20"></th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {filteredResults.map((lead) => (
                          <tr key={lead.id} className="group hover:bg-slate-50/30 transition-all">
                            <td className="p-6 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-6">
                              <div>
                                <p className="text-[15px] font-bold text-slate-900 tracking-tight">{lead.name}</p>
                                <p className="text-[11px] text-slate-400 font-bold uppercase tracking-wider">{lead.industry}</p>
                                <p className="text-[12px] text-slate-400 font-medium flex items-center gap-1 mt-1">
                                  <MapPin className="w-3 h-3" /> {lead.address}
                                </p>
                              </div>
                            </td>
                            <td className="p-6">
                              <div className="flex flex-col gap-2">
                                {lead.email ? (
                                  <div className="flex items-center gap-2 text-[13px] font-bold text-slate-900">
                                    <Mail className="w-3.5 h-3.5 text-slate-400" /> {lead.email}
                                  </div>
                                ) : (
                                  <button 
                                    onClick={() => handleEnrich(lead.id)}
                                    className="text-[11px] font-bold text-slate-400 hover:text-slate-900 uppercase tracking-widest flex items-center gap-2 transition-colors"
                                  >
                                    {enrichingLeads.has(lead.id) ? <Loader2 className="w-3 h-3 animate-spin"/> : <Search className="w-3 h-3"/>}
                                    Enrich Data
                                  </button>
                                )}
                                {lead.website && (
                                  <a 
                                    href={lead.website.startsWith('http') ? lead.website : `https://${lead.website}`}
                                    target="_blank" rel="noopener noreferrer"
                                    className="flex items-center gap-2 text-[12px] text-slate-400 hover:text-slate-900 transition-colors"
                                  >
                                    <Globe className="w-3.5 h-3.5 text-slate-300" /> {lead.website.replace(/https?:\/\//, '').split('/')[0]}
                                  </a>
                                )}
                              </div>
                            </td>
                            <td className="p-6">
                              <div className="flex flex-col items-center gap-2">
                                <div className="h-1 w-24 bg-slate-100 rounded-full overflow-hidden">
                                  <div className="h-full bg-slate-900" style={{ width: `${lead.qualityScore}%` }} />
                                </div>
                                <span className="text-[11px] font-black text-slate-900">{lead.qualityScore}% Match</span>
                              </div>
                            </td>
                            <td className="p-6 text-right">
                              <button className="h-9 w-9 rounded-full bg-white border border-slate-200 flex items-center justify-center text-slate-400 hover:text-slate-900 hover:border-slate-900 transition-all shadow-sm">
                                <ArrowRight className="w-4 h-4" />
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </>
              )}
            </div>
        </section>
      </main>
    </div>
  );
}
