'use client'

import { useState } from 'react'
import type { SearchParams, Source, InputMode, ScrapeProgress } from '@/lib/types'
import { ALL_CATEGORIES, COUNTRIES, CITIES_BY_COUNTRY, FEATURED_CATEGORIES } from '@/lib/acquisition/config'

interface SearchPanelProps {
  onSearch: (params: SearchParams) => void
  onUrlScrape: (url: string, maxResults: number, progress: (p: ScrapeProgress) => void) => Promise<void>
  isSearching: boolean
  scrapeProgress: ScrapeProgress | null
}

const SOURCES: { id: Source; icon: string; label: string }[] = [
  { id: 'google_maps', icon: 'location_on', label: 'Maps' },
  { id: 'directory', icon: 'list_alt', label: 'Directory' },
  { id: 'linkedin', icon: 'share', label: 'LinkedIn' },
  { id: 'facebook', icon: 'public', label: 'Facebook' },
]

const MAX_RESULTS_OPTIONS = [50, 100, 200, 500]

export default function SearchPanel({ onSearch, onUrlScrape, isSearching, scrapeProgress }: SearchPanelProps) {
  const [inputMode, setInputMode] = useState<InputMode>('search')
  const [country, setCountry] = useState('EG')
  const [city, setCity] = useState('Cairo')
  const [district, setDistrict] = useState('')
  const [selectedCategories, setSelectedCategories] = useState<string[]>(FEATURED_CATEGORIES.slice(0, 2))
  const [keyword, setKeyword] = useState('')
  const [maxResults, setMaxResults] = useState(100)
  const [sources, setSources] = useState<Source[]>(['google_maps'])
  const [showCategoryPicker, setShowCategoryPicker] = useState(false)
  // URL mode
  const [scrapeUrl, setScrapeUrl] = useState('')
  const [urlMaxResults, setUrlMaxResults] = useState(100)

  const cities: string[] = CITIES_BY_COUNTRY[country] || []

  const toggleCategory = (cat: string) =>
    setSelectedCategories(prev => prev.includes(cat) ? prev.filter(c => c !== cat) : [...prev, cat])

  const toggleSource = (s: Source) =>
    setSources(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s])

  const handleSearch = () => {
    if (!city || selectedCategories.length === 0 || sources.length === 0) return
    onSearch({ country, city, district, categories: selectedCategories, keyword, max_results: maxResults, sources })
  }

  const handleUrlScrape = () => {
    if (!scrapeUrl.trim()) return
    onUrlScrape(scrapeUrl.trim(), urlMaxResults, () => {})
  }

  const handleClear = () => {
    setSelectedCategories(FEATURED_CATEGORIES.slice(0, 2))
    setDistrict('')
    setKeyword('')
    setMaxResults(100)
    setSources(['google_maps'])
    setScrapeUrl('')
  }

  const isRunning = isSearching

  return (
    <aside className="w-72 bg-[#060e20] flex flex-col gap-0 overflow-y-auto border-r border-[#574143]/10 flex-shrink-0">
      {/* Mode Toggle */}
      <div className="p-4 pb-0">
        <div className="flex bg-[#131b2e] p-1 rounded-xl mb-4">
          <button
            onClick={() => setInputMode('search')}
            className={`flex-1 py-2 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${inputMode === 'search' ? 'bg-[#222a3d] text-white' : 'text-slate-500 hover:text-white'}`}
          >
            Search
          </button>
          <button
            onClick={() => setInputMode('url')}
            className={`flex-1 py-2 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${inputMode === 'url' ? 'bg-[#222a3d] text-white' : 'text-slate-500 hover:text-white'}`}
          >
            Ingest URL
          </button>
        </div>
      </div>

      {inputMode === 'search' ? (
        <div className="px-4 pb-4 flex flex-col gap-4 flex-1">
          <h3 className="text-xs font-black text-slate-500 uppercase tracking-widest">Search Parameters</h3>
          <p className="text-[11px] text-slate-600 leading-relaxed -mt-2">
            Search mode expands your geography and category filters into a bounded acquisition plan. Google Places runs live when configured, while unsupported search sources stay explicitly labeled as demo instead of pretending to be live retrieval.
          </p>

          {/* Country */}
          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Country</label>
            <select
              value={country}
              onChange={e => { setCountry(e.target.value); setCity('') }}
              className="bg-[#222a3d] px-3 py-2.5 rounded-xl border border-[#574143]/10 text-sm text-[#dae2fd] focus:outline-none focus:ring-1 focus:ring-[#fb7185]/50"
            >
              {COUNTRIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
            </select>
          </div>

          {/* City */}
          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">City</label>
            <select
              value={city}
              onChange={e => setCity(e.target.value)}
              className="bg-[#222a3d] px-3 py-2.5 rounded-xl border border-[#574143]/10 text-sm text-[#dae2fd] focus:outline-none focus:ring-1 focus:ring-[#fb7185]/50"
            >
              <option value="">Select city…</option>
              {cities.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>

          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">District / Area (optional)</label>
            <input
              type="text"
              value={district}
              onChange={e => setDistrict(e.target.value)}
              placeholder="e.g. Nasr City, New Cairo, Maadi"
              className="bg-[#222a3d] px-3 py-2.5 rounded-xl border border-[#574143]/10 text-sm text-[#dae2fd] focus:outline-none focus:ring-1 focus:ring-[#fb7185]/50 placeholder-slate-600"
            />
          </div>

          {/* Categories */}
          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Categories</label>
            <div className="flex flex-wrap gap-2">
              {selectedCategories.map(cat => (
                <span
                  key={cat}
                  onClick={() => toggleCategory(cat)}
                  className="px-2 py-1 bg-[#ffb2b9]/10 text-[#ffb2b9] text-[10px] font-bold rounded-lg flex items-center gap-1 border border-[#ffb2b9]/20 cursor-pointer"
                >
                  {cat} <span className="material-symbols-outlined text-[11px]">close</span>
                </span>
              ))}
              <button
                onClick={() => setShowCategoryPicker(!showCategoryPicker)}
                className="px-2 py-1 bg-[#222a3d] text-slate-400 text-[10px] font-bold rounded-lg border border-[#574143]/10 hover:text-white"
              >
                + Add
              </button>
            </div>
            {showCategoryPicker && (
              <div className="mt-1 bg-[#131b2e] rounded-xl border border-[#574143]/20 p-3 max-h-48 overflow-y-auto">
                {ALL_CATEGORIES.filter(c => !selectedCategories.includes(c)).map(cat => (
                  <button
                    key={cat}
                    onClick={() => { toggleCategory(cat); setShowCategoryPicker(false) }}
                    className="w-full text-left text-[11px] text-slate-400 hover:text-white px-2 py-1.5 rounded-lg hover:bg-[#222a3d] transition-colors"
                  >
                    {cat}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Keyword */}
          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Keyword (optional)</label>
            <input
              type="text" value={keyword} onChange={e => setKeyword(e.target.value)}
              placeholder="e.g. legal consultant"
              className="bg-[#222a3d] px-3 py-2.5 rounded-xl border border-[#574143]/10 text-sm text-[#dae2fd] focus:outline-none focus:ring-1 focus:ring-[#fb7185]/50 placeholder-slate-600"
            />
          </div>

          {/* Max Results */}
          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Max Results</label>
            <div className="grid grid-cols-4 gap-1.5">
              {MAX_RESULTS_OPTIONS.map(n => (
                <button key={n} onClick={() => setMaxResults(n)}
                  className={`py-2 rounded-xl text-xs font-bold transition-all ${maxResults === n ? 'bg-[#ffb2b9]/20 text-[#ffb2b9] border border-[#ffb2b9]/30' : 'bg-[#222a3d] text-slate-400 border border-[#574143]/10 hover:text-white'}`}
                >
                  {n}
                </button>
              ))}
            </div>
          </div>

          {/* Sources */}
          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Sources</label>
            <div className="grid grid-cols-2 gap-2">
              {SOURCES.map(s => (
                <button key={s.id} onClick={() => toggleSource(s.id)} title={s.id}
                  className={`p-2.5 rounded-xl flex flex-col items-center gap-1 cursor-pointer transition-all ${sources.includes(s.id) ? 'bg-[#ffb2b9]/20 border border-[#ffb2b9]/40' : 'bg-[#222a3d] border border-[#574143]/10 hover:bg-[#2d3449]'}`}
                >
                  <span className={`material-symbols-outlined text-xl ${sources.includes(s.id) ? 'text-[#ffb2b9]' : 'text-slate-400'}`}>{s.icon}</span>
                  <span className={`text-[9px] font-bold ${sources.includes(s.id) ? 'text-[#ffb2b9]' : 'text-slate-500'}`}>{s.label}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="mt-auto pt-2 space-y-2">
            <button
              onClick={handleSearch}
              disabled={isRunning || !city || selectedCategories.length === 0 || sources.length === 0}
              className="w-full py-3.5 bg-[#dae2fd] text-[#0b1326] font-black rounded-xl hover:opacity-90 active:scale-95 transition-all shadow-xl disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isRunning ? (
                <><span className="material-symbols-outlined animate-spin text-lg">refresh</span>Searching…</>
              ) : 'RUN SOURCE-AWARE SEARCH'}
            </button>
            <button onClick={handleClear} className="w-full py-2 text-slate-500 text-xs font-bold hover:text-slate-300 transition-colors">
              Clear Filters
            </button>
          </div>
        </div>
      ) : (
        /* URL Mode */
        <div className="px-4 pb-4 flex flex-col gap-4 flex-1">
          <div>
            <h3 className="text-xs font-black text-slate-500 uppercase tracking-widest mb-1">URL Ingestion</h3>
            <p className="text-[11px] text-slate-600 leading-relaxed">
              URL mode inspects the link, detects the source type, and routes it into the correct ingestion path. Some URLs are parsed only for context, while supported directory pages use best-effort HTML extraction when the target site allows it.
            </p>
          </div>

          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Source URL</label>
            <textarea
              value={scrapeUrl}
              onChange={e => setScrapeUrl(e.target.value)}
              placeholder="https://www.google.com/maps/search/law+firms+cairo/&#10;https://yello.com.eg/search?what=law+firm&#10;https://example.com/directory/businesses"
              rows={4}
              className="bg-[#222a3d] px-3 py-2.5 rounded-xl border border-[#574143]/10 text-sm text-[#dae2fd] focus:outline-none focus:ring-1 focus:ring-[#fb7185]/50 placeholder-slate-600 resize-none font-mono text-[11px]"
            />
          </div>

          <div className="flex flex-col gap-1.5">
            <label className="text-[11px] font-bold text-slate-400 uppercase tracking-tighter">Max Results</label>
            <div className="grid grid-cols-4 gap-1.5">
              {MAX_RESULTS_OPTIONS.map(n => (
                <button key={n} onClick={() => setUrlMaxResults(n)}
                  className={`py-2 rounded-xl text-xs font-bold transition-all ${urlMaxResults === n ? 'bg-[#ffb2b9]/20 text-[#ffb2b9] border border-[#ffb2b9]/30' : 'bg-[#222a3d] text-slate-400 border border-[#574143]/10 hover:text-white'}`}
                >
                  {n}
                </button>
              ))}
            </div>
          </div>

          {/* Supported sources reference */}
          <div className="bg-[#131b2e] rounded-xl p-4 border border-[#574143]/10">
            <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-2">Supported URLs</p>
            <div className="space-y-1.5">
              {[
                { icon: 'location_on', label: 'Google Maps URLs: parsed for search context, then routed into Places when configured', color: 'text-[#ffb2b9]' },
                { icon: 'list_alt', label: 'Yello / Yellow Pages / directory pages: best-effort live HTML extraction', color: 'text-[#ffb95f]' },
                { icon: 'share', label: 'LinkedIn URLs: explicitly unsupported in this phase', color: 'text-slate-400' },
                { icon: 'public', label: 'Facebook URLs: explicitly unsupported in this phase', color: 'text-slate-400' },
              ].map(s => (
                <div key={s.label} className="flex items-center gap-2">
                  <span className={`material-symbols-outlined text-[14px] ${s.color}`}>{s.icon}</span>
                  <span className="text-[10px] text-slate-400">{s.label}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Progress display */}
          {scrapeProgress && scrapeProgress.status !== 'idle' && (
            <div className="bg-[#131b2e] rounded-xl p-4 border border-[#574143]/10 space-y-3">
              <div className="flex items-center gap-2">
                {scrapeProgress.status === 'done' ? (
                  <span className="material-symbols-outlined text-[#22c55e] text-lg">check_circle</span>
                ) : scrapeProgress.status === 'error' ? (
                  <span className="material-symbols-outlined text-red-400 text-lg">error</span>
                ) : (
                  <span className="material-symbols-outlined text-[#ffb95f] animate-spin text-lg">refresh</span>
                )}
                <span className="text-[11px] font-bold text-slate-300 capitalize">{scrapeProgress.status}</span>
                {scrapeProgress.source_type && (
                  <span className="text-[10px] text-slate-500 ml-auto">{scrapeProgress.source_type.replace('_', ' ')}</span>
                )}
              </div>
              <p className="text-[11px] text-slate-400 leading-relaxed">{scrapeProgress.message}</p>
              {(scrapeProgress.found > 0 || scrapeProgress.processed > 0) && (
                <div className="grid grid-cols-3 gap-2">
                  {[
                    { label: 'Found', value: scrapeProgress.found },
                    { label: 'Processed', value: scrapeProgress.processed },
                    { label: 'Skipped', value: scrapeProgress.skipped_duplicates },
                  ].map(s => (
                    <div key={s.label} className="bg-[#0b1326] p-2 rounded-lg text-center">
                      <p className="text-xs font-black text-white">{s.value}</p>
                      <p className="text-[9px] text-slate-500 uppercase">{s.label}</p>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          <div className="mt-auto pt-2 space-y-2">
            <button
              onClick={handleUrlScrape}
              disabled={isRunning || !scrapeUrl.trim()}
              className="w-full py-3.5 bg-[#dae2fd] text-[#0b1326] font-black rounded-xl hover:opacity-90 active:scale-95 transition-all shadow-xl disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isRunning ? (
                <><span className="material-symbols-outlined animate-spin text-lg">refresh</span>Extracting…</>
              ) : (
                <><span className="material-symbols-outlined text-lg">travel_explore</span>RUN URL INGESTION</>
              )}
            </button>
            <button onClick={handleClear} className="w-full py-2 text-slate-500 text-xs font-bold hover:text-slate-300 transition-colors">
              Clear
            </button>
          </div>
        </div>
      )}
    </aside>
  )
}
