'use client'

import { useState, useMemo } from 'react'
import type { Prospect, LeadTag, LeadStatus } from '@/lib/types'

interface ProspectsTableProps {
  prospects: Prospect[]
  selectedId: string | null
  onSelect: (p: Prospect) => void
  onSaveLead: (p: Prospect) => void
  onExcludeLead: (p: Prospect) => void
}

const TAG_STYLES: Record<LeadTag, string> = {
  'High Potential': 'bg-[#ac8aff]/10 text-[#ac8aff] border border-[#ac8aff]/20',
  'Medium Potential': 'bg-[#ee9800]/10 text-[#ee9800] border border-[#ee9800]/20',
  'Low Potential': 'bg-[#574143]/20 text-slate-400',
}

const SCORE_COLOR = (score: number) =>
  score >= 80 ? 'text-[#ac8aff]' : score >= 50 ? 'text-[#ee9800]' : 'text-slate-500'

const STATUS_BADGE: Record<LeadStatus, { label: string; style: string }> = {
  new: { label: 'New', style: 'bg-[#22c55e]/10 text-[#22c55e] border border-[#22c55e]/20' },
  existing: { label: 'Existing', style: 'bg-[#60a5fa]/10 text-[#60a5fa] border border-[#60a5fa]/20' },
  saved: { label: 'Saved', style: 'bg-[#ffb95f]/10 text-[#ffb95f] border border-[#ffb95f]/20' },
  excluded: { label: 'Excluded', style: 'bg-[#574143]/20 text-slate-500 border border-[#574143]/20' },
}

type SortKey = 'score' | 'business_name' | 'normalized_category' | 'lead_tag'
type StatusFilter = LeadStatus | 'all'

export default function ProspectsTable({
  prospects, selectedId, onSelect, onSaveLead, onExcludeLead,
}: ProspectsTableProps) {
  const [sortKey, setSortKey] = useState<SortKey>('score')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
  const [filterTag, setFilterTag] = useState<LeadTag | ''>('')
  const [filterCategory, setFilterCategory] = useState('')
  const [filterBranch, setFilterBranch] = useState('')
  const [filterStatus, setFilterStatus] = useState<StatusFilter>('all')
  const [search, setSearch] = useState('')
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [showExcluded, setShowExcluded] = useState(false)

  const uniqueCategories = useMemo(() => Array.from(new Set(prospects.map(p => p.normalized_category))), [prospects])
  const uniqueBranches = useMemo(() => Array.from(new Set(prospects.map(p => p.suggested_branch))), [prospects])

  const statusCounts = useMemo(() => ({
    all: prospects.length,
    new: prospects.filter(p => p.lead_status === 'new').length,
    existing: prospects.filter(p => p.lead_status === 'existing').length,
    saved: prospects.filter(p => p.lead_status === 'saved').length,
    excluded: prospects.filter(p => p.lead_status === 'excluded').length,
  }), [prospects])

  const filtered = useMemo(() => {
    let result = prospects
    if (!showExcluded) result = result.filter(p => p.lead_status !== 'excluded')
    if (filterStatus !== 'all') result = result.filter(p => p.lead_status === filterStatus)
    if (filterTag) result = result.filter(p => p.lead_tag === filterTag)
    if (filterCategory) result = result.filter(p => p.normalized_category === filterCategory)
    if (filterBranch) result = result.filter(p => p.suggested_branch === filterBranch)
    if (search) {
      const s = search.toLowerCase()
      result = result.filter(p =>
        p.business_name.toLowerCase().includes(s) ||
        p.city.toLowerCase().includes(s) ||
        p.normalized_category.toLowerCase().includes(s)
      )
    }
    return [...result].sort((a, b) => {
      let va: string | number = a[sortKey]
      let vb: string | number = b[sortKey]
      if (typeof va === 'number' && typeof vb === 'number') return sortDir === 'asc' ? va - vb : vb - va
      return sortDir === 'asc'
        ? String(va).localeCompare(String(vb))
        : String(vb).localeCompare(String(va))
    })
  }, [prospects, sortKey, sortDir, filterTag, filterCategory, filterBranch, filterStatus, search, showExcluded])

  const toggleSort = (key: SortKey) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setSortKey(key); setSortDir('desc') }
  }

  const toggleSelectAll = () =>
    setSelected(selected.size === filtered.length ? new Set() : new Set(filtered.map(p => p.id)))

  const toggleSelect = (id: string) =>
    setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n })

  const getSelectedActionableProspects = () =>
    Array.from(selected)
      .map(id => prospects.find(item => item.id === id))
      .filter((item): item is Prospect => Boolean(item))
      .filter(item => !(item.lead_status === 'existing' && item.matched_scope === 'team'))

  const SortIcon = ({ k }: { k: SortKey }) => (
    <span className="material-symbols-outlined text-[12px] ml-1 opacity-50">
      {sortKey === k ? (sortDir === 'asc' ? 'arrow_upward' : 'arrow_downward') : 'unfold_more'}
    </span>
  )

  if (prospects.length === 0) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center text-center p-12">
        <span className="material-symbols-outlined text-6xl text-slate-700 mb-4">manage_search</span>
        <h3 className="text-lg font-bold text-slate-400 mb-2" style={{ fontFamily: 'Manrope, sans-serif' }}>No prospects yet</h3>
        <p className="text-sm text-slate-600">Configure your search or paste a URL and extract leads.</p>
      </div>
    )
  }

  return (
    <div className="flex-1 flex flex-col overflow-hidden">
      {/* Status tabs */}
      <div className="px-4 pt-3 flex gap-1 border-b border-[#574143]/10">
        {([
          { key: 'all', label: 'All' },
          { key: 'new', label: 'New' },
          { key: 'existing', label: 'Existing' },
          { key: 'saved', label: 'Saved' },
        ] as { key: StatusFilter; label: string }[]).map(tab => (
          <button
            key={tab.key}
            onClick={() => setFilterStatus(tab.key)}
            className={`px-3 py-2 text-[10px] font-black uppercase tracking-widest transition-all border-b-2 ${filterStatus === tab.key ? 'text-[#ffb2b9] border-[#ffb2b9]' : 'text-slate-500 border-transparent hover:text-slate-300'}`}
          >
            {tab.label}
            <span className="ml-1.5 text-[9px] font-bold opacity-60">{statusCounts[tab.key]}</span>
          </button>
        ))}
        <button
          onClick={() => setShowExcluded(!showExcluded)}
          className={`ml-auto px-3 py-2 text-[10px] font-black uppercase tracking-widest transition-all ${showExcluded ? 'text-slate-400' : 'text-slate-600 hover:text-slate-400'}`}
        >
          {showExcluded ? 'Hide Excluded' : 'Show Excluded'} ({statusCounts.excluded})
        </button>
      </div>

      {/* Filters row */}
      <div className="px-4 py-2.5 flex items-center gap-2 flex-wrap border-b border-[#574143]/10">
        <input
          type="text" value={search} onChange={e => setSearch(e.target.value)}
          placeholder="Search leads…"
          className="bg-[#131b2e] px-3 py-1.5 rounded-xl border border-[#574143]/10 text-xs text-[#dae2fd] focus:outline-none focus:ring-1 focus:ring-[#fb7185]/50 placeholder-slate-600 w-36"
        />
        <select value={filterTag} onChange={e => setFilterTag(e.target.value as LeadTag | '')}
          className="bg-[#131b2e] px-2 py-1.5 rounded-xl border border-[#574143]/10 text-xs text-[#dae2fd] focus:outline-none">
          <option value="">All Tags</option>
          <option>High Potential</option><option>Medium Potential</option><option>Low Potential</option>
        </select>
        <select value={filterCategory} onChange={e => setFilterCategory(e.target.value)}
          className="bg-[#131b2e] px-2 py-1.5 rounded-xl border border-[#574143]/10 text-xs text-[#dae2fd] focus:outline-none">
          <option value="">All Categories</option>
          {uniqueCategories.map(c => <option key={c}>{c}</option>)}
        </select>
        <select value={filterBranch} onChange={e => setFilterBranch(e.target.value)}
          className="bg-[#131b2e] px-2 py-1.5 rounded-xl border border-[#574143]/10 text-xs text-[#dae2fd] focus:outline-none">
          <option value="">All Branches</option>
          {uniqueBranches.map(b => <option key={b}>{b}</option>)}
        </select>
        <span className="ml-auto text-[11px] text-slate-500">
          {filtered.length} of {prospects.length}
          {selected.size > 0 && ` · ${selected.size} selected`}
        </span>
        {selected.size > 0 && (
          <div className="flex gap-1">
            <button
              onClick={() => { getSelectedActionableProspects().forEach(onSaveLead); setSelected(new Set()) }}
              className="px-2 py-1 bg-[#ffb95f]/10 text-[#ffb95f] text-[10px] font-bold rounded-lg border border-[#ffb95f]/20 hover:bg-[#ffb95f]/20"
            >
              Save Selected
            </button>
            <button
              onClick={() => { getSelectedActionableProspects().forEach(onExcludeLead); setSelected(new Set()) }}
              className="px-2 py-1 bg-[#574143]/20 text-slate-400 text-[10px] font-bold rounded-lg border border-[#574143]/20 hover:bg-[#574143]/30"
            >
              Exclude Selected
            </button>
          </div>
        )}
      </div>

      {/* Table */}
      <div className="flex-1 overflow-auto">
        <table className="w-full text-left">
          <thead className="sticky top-0 bg-[#131b2e] z-10">
            <tr>
              <th className="px-3 py-3 w-8">
                <input type="checkbox"
                  checked={selected.size === filtered.length && filtered.length > 0}
                  onChange={toggleSelectAll} className="accent-[#fb7185]" />
              </th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest cursor-pointer" onClick={() => toggleSort('business_name')}>
                Business Name <SortIcon k="business_name" />
              </th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest cursor-pointer hidden lg:table-cell" onClick={() => toggleSort('normalized_category')}>
                Category <SortIcon k="normalized_category" />
              </th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest hidden xl:table-cell">Phone</th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest">City</th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest text-center cursor-pointer" onClick={() => toggleSort('score')}>
                Score <SortIcon k="score" />
              </th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest hidden lg:table-cell" onClick={() => toggleSort('lead_tag')}>
                Tag
              </th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest">Status</th>
              <th className="px-3 py-3 text-[10px] font-black text-slate-500 uppercase tracking-widest hidden lg:table-cell">Branch</th>
              <th className="px-3 py-3 w-16"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(p => {
              const statusBadge = STATUS_BADGE[p.lead_status]
              const isExcluded = p.lead_status === 'excluded'
              const isTeamExisting = p.lead_status === 'existing' && p.matched_scope === 'team'
              return (
                <tr
                  key={p.id}
                  onClick={() => onSelect(p)}
                  className={`cursor-pointer transition-colors border-b border-[#574143]/5 ${isExcluded ? 'opacity-40' : ''} ${selectedId === p.id ? 'bg-[#ffb2b9]/5 border-l-4 border-l-[#ffb2b9]' : 'hover:bg-[#222a3d]/50'}`}
                >
                  <td className="px-3 py-3" onClick={e => { e.stopPropagation(); toggleSelect(p.id) }}>
                    <input type="checkbox" checked={selected.has(p.id)} onChange={() => toggleSelect(p.id)} className="accent-[#fb7185]" />
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex flex-col">
                      <span className="text-sm font-bold text-[#dae2fd]">{p.business_name}</span>
                      <span className="text-[10px] text-slate-500">
                        {p.source_label}
                        {isTeamExisting && p.matched_owner_name ? ` · Owned by ${p.matched_owner_name}` : ''}
                      </span>
                      <span className="text-[10px] text-slate-600">
                        {p.acquisition_mode === 'real' ? 'Live Retrieved' : 'Demo Fallback'} · {p.result_confidence}% confidence · {p.data_completeness}% complete
                      </span>
                      {isTeamExisting && (
                        <span className="text-[10px] text-slate-600">
                          {p.matched_assigned_name ? `Assigned to ${p.matched_assigned_name}` : 'Currently unassigned'}
                          {p.matched_visibility_scope ? ` · ${p.matched_visibility_scope}` : ''}
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-3 py-3 hidden lg:table-cell">
                    <span className="text-[10px] font-semibold bg-[#222a3d] px-2 py-0.5 rounded-full text-slate-200">{p.normalized_category}</span>
                  </td>
                  <td className="px-3 py-3 hidden xl:table-cell">
                    <span className="text-[11px] text-slate-400">{p.phone || '—'}</span>
                  </td>
                  <td className="px-3 py-3">
                    <span className="text-[11px] text-slate-300">{p.city}</span>
                  </td>
                  <td className="px-3 py-3 text-center">
                    <span className={`text-sm font-mono font-bold ${SCORE_COLOR(p.score)}`}>{p.score}</span>
                  </td>
                  <td className="px-3 py-3 hidden lg:table-cell">
                    <span className={`px-2 py-0.5 text-[9px] font-black rounded uppercase tracking-widest ${TAG_STYLES[p.lead_tag]}`}>
                      {p.lead_tag === 'High Potential' ? 'High' : p.lead_tag === 'Medium Potential' ? 'Med' : 'Low'}
                    </span>
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex flex-col gap-1">
                      <span className={`px-2 py-0.5 text-[9px] font-black rounded-full uppercase tracking-widest ${statusBadge.style}`}>
                        {isTeamExisting ? 'Existing Team' : statusBadge.label}
                      </span>
                      {p.matched_stage && (
                        <span className="text-[10px] text-slate-500">{p.matched_stage.replace(/_/g, ' ')}</span>
                      )}
                    </div>
                  </td>
                  <td className="px-3 py-3 hidden lg:table-cell">
                    <span className="text-[10px] font-bold text-slate-400">{p.suggested_branch}</span>
                  </td>
                  <td className="px-3 py-3" onClick={e => e.stopPropagation()}>
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => onSaveLead(p)}
                        title="Save lead"
                        disabled={isTeamExisting}
                        className={`p-1 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${p.lead_status === 'saved' ? 'text-[#ffb95f]' : 'text-slate-600 hover:text-[#ffb95f]'}`}
                      >
                        <span className="material-symbols-outlined text-[16px]">
                          {p.lead_status === 'saved' ? 'bookmark' : 'bookmark_border'}
                        </span>
                      </button>
                      <button
                        onClick={() => onExcludeLead(p)}
                        title="Exclude lead"
                        disabled={isTeamExisting}
                        className={`p-1 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${p.lead_status === 'excluded' ? 'text-slate-400' : 'text-slate-600 hover:text-slate-400'}`}
                      >
                        <span className="material-symbols-outlined text-[16px]">
                          {p.lead_status === 'excluded' ? 'block' : 'remove_circle_outline'}
                        </span>
                      </button>
                    </div>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    </div>
  )
}
