import React, { useState, useCallback } from 'react';
import { FilterPanel } from '../components/FilterPanel';
import { LocationPicker } from '../components/LocationPicker';
import { PropertyTypeSelector } from '../components/PropertyTypeSelector';
import { OwnerFilters } from '../components/OwnerFilters';
import { OutputFieldSelector } from '../components/OutputFieldSelector';

interface SearchBuilderProps {
  onStartScrape: (config: any) => void;
  loading?: boolean;
}

const SIDEBAR_SECTIONS = [
  { id: 'location', label: 'Location', icon: '📍' },
  { id: 'propertyType', label: 'Property Type', icon: '🏢' },
  { id: 'building', label: 'Building & Lot', icon: '🏗️' },
  { id: 'owner', label: 'Owner', icon: '👤' },
  { id: 'sales', label: 'Sales', icon: '💰' },
  { id: 'output', label: 'Output Fields', icon: '📋' },
];

export function SearchBuilder({ onStartScrape, loading = false }: SearchBuilderProps) {
  const [activeSection, setActiveSection] = useState('location');
  const [location, setLocation] = useState('');
  const [propertyTypes, setPropertyTypes] = useState<string[]>([]);
  const [building, setBuilding] = useState({
    yearBuiltFrom: '' as number | '',
    yearBuiltUntil: '' as number | '',
    totalUnitsMin: '' as number | '',
    totalUnitsMax: '' as number | '',
    buildingAreaMin: '' as number | '',
    buildingAreaMax: '' as number | '',
    lotSizeSfMin: '' as number | '',
    lotSizeSfMax: '' as number | '',
    zoning: '',
    opportunityZone: false,
  });
  const [owner, setOwner] = useState({
    includesPhone: false,
    includesEmail: false,
    portfolioMin: '' as number | '',
    portfolioMax: '' as number | '',
    ownerOccupied: false,
    ownerType: '' as '' | 'Company' | 'Person',
  });
  const [sales, setSales] = useState({
    dateFrom: '',
    dateUntil: '',
    priceMin: '' as number | '',
    priceMax: '' as number | '',
    likelyToSell: false,
  });
  const [outputFields, setOutputFields] = useState<Record<string, string[]>>({
    propertyInfo: ['address', 'type', 'units', 'sqft'],
    ownerInfo: ['name', 'company'],
    contactInfo: ['phones', 'emails'],
  });
  const [maxProperties, setMaxProperties] = useState(25);

  const buildConfig = useCallback(() => {
    const config: any = { location };

    if (propertyTypes.length > 0) config.propertyTypes = propertyTypes;

    // Building
    const b: any = {};
    if (building.yearBuiltFrom !== '') b.yearBuiltFrom = building.yearBuiltFrom;
    if (building.yearBuiltUntil !== '') b.yearBuiltUntil = building.yearBuiltUntil;
    if (building.totalUnitsMin !== '') b.totalUnitsMin = building.totalUnitsMin;
    if (building.totalUnitsMax !== '') b.totalUnitsMax = building.totalUnitsMax;
    if (building.buildingAreaMin !== '') b.buildingAreaMin = building.buildingAreaMin;
    if (building.buildingAreaMax !== '') b.buildingAreaMax = building.buildingAreaMax;
    if (building.lotSizeSfMin !== '') b.lotSizeSfMin = building.lotSizeSfMin;
    if (building.lotSizeSfMax !== '') b.lotSizeSfMax = building.lotSizeSfMax;
    if (building.zoning) b.zoning = building.zoning;
    if (building.opportunityZone) b.opportunityZone = true;
    if (Object.keys(b).length > 0) config.building = b;

    // Owner
    const o: any = {};
    if (owner.includesPhone) o.includesPhone = true;
    if (owner.includesEmail) o.includesEmail = true;
    if (owner.portfolioMin !== '') o.portfolioMin = owner.portfolioMin;
    if (owner.portfolioMax !== '') o.portfolioMax = owner.portfolioMax;
    if (owner.ownerOccupied) o.ownerOccupied = true;
    if (owner.ownerType) o.ownerType = owner.ownerType;
    if (Object.keys(o).length > 0) config.owner = o;

    // Sales
    const s: any = {};
    if (sales.dateFrom) s.dateRange = `${sales.dateFrom}:${sales.dateUntil || ''}`;
    if (sales.priceMin !== '') s.priceMin = sales.priceMin;
    if (sales.priceMax !== '') s.priceMax = sales.priceMax;
    if (sales.likelyToSell) s.likelyToSell = true;
    if (Object.keys(s).length > 0) config.sales = s;

    // Output fields
    const output: any = {};
    for (const [group, fields] of Object.entries(outputFields)) {
      if (fields.length > 0) output[group] = fields;
    }
    config.outputConfig = output;
    config.maxProperties = maxProperties;

    return config;
  }, [location, propertyTypes, building, owner, sales, outputFields, maxProperties]);

  const handleStart = () => {
    const config = buildConfig();
    if (!config.location) return;
    onStartScrape(config);
  };

  const numVal = (v: string) => (v === '' ? '' : Number(v)) as number | '';

  const filterCount = () => {
    let count = 0;
    if (location) count++;
    count += propertyTypes.length;
    if (building.yearBuiltFrom !== '' || building.yearBuiltUntil !== '') count++;
    if (building.totalUnitsMin !== '' || building.totalUnitsMax !== '') count++;
    if (building.buildingAreaMin !== '' || building.buildingAreaMax !== '') count++;
    if (building.zoning) count++;
    if (building.opportunityZone) count++;
    if (owner.includesPhone) count++;
    if (owner.includesEmail) count++;
    if (owner.ownerType) count++;
    if (sales.likelyToSell) count++;
    if (sales.priceMin !== '' || sales.priceMax !== '') count++;
    return count;
  };

  return (
    <div className="flex h-screen bg-white">
      {/* Sidebar */}
      <div className="w-64 bg-reo-dark flex flex-col flex-shrink-0">
        {/* Logo */}
        <div className="px-5 py-4 border-b border-gray-700/30">
          <h1 className="text-lg font-bold text-white flex items-center gap-2">
            <span className="w-7 h-7 bg-reo-teal rounded-lg flex items-center justify-center text-sm font-bold">R</span>
            Reonomy Search
          </h1>
          <p className="text-xs text-gray-500 mt-1">Property Intelligence</p>
        </div>

        {/* Nav */}
        <nav className="flex-1 py-2 overflow-y-auto">
          {SIDEBAR_SECTIONS.map((section) => (
            <button
              key={section.id}
              onClick={() => setActiveSection(section.id)}
              className={`w-full flex items-center gap-2.5 px-5 py-2.5 text-sm transition-colors ${
                activeSection === section.id
                  ? 'bg-reo-teal/10 text-reo-teal border-r-2 border-reo-teal font-medium'
                  : 'text-gray-400 hover:text-gray-200 hover:bg-white/5'
              }`}
            >
              <span>{section.icon}</span>
              {section.label}
            </button>
          ))}
        </nav>

        {/* Filter summary */}
        <div className="px-5 py-3 border-t border-gray-700/30">
          <p className="text-xs text-gray-500">{filterCount()} active filters</p>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Header */}
        <div className="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-reo-dark">
              {SIDEBAR_SECTIONS.find((s) => s.id === activeSection)?.label || 'Search'}
            </h2>
            <p className="text-xs text-gray-500 mt-0.5">Configure your property search filters</p>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2">
              <label className="text-xs text-gray-500">Max:</label>
              <input
                type="range"
                min={1}
                max={50}
                value={maxProperties}
                onChange={(e) => setMaxProperties(Number(e.target.value))}
                className="w-24 accent-reo-teal"
              />
              <span className="text-sm font-semibold text-reo-dark w-8">{maxProperties}</span>
            </div>
            <button
              onClick={handleStart}
              disabled={!location || loading}
              className="btn-primary flex items-center gap-2"
            >
              {loading ? (
                <>
                  <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                  </svg>
                  Running...
                </>
              ) : (
                <>
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                  Start Scrape
                </>
              )}
            </button>
          </div>
        </div>

        {/* Content area */}
        <div className="flex-1 overflow-y-auto px-6 py-5">
          {/* Location */}
          {activeSection === 'location' && (
            <div className="max-w-lg space-y-4">
              <div className="bg-reo-dark rounded-xl p-5">
                <LocationPicker value={location} onChange={setLocation} />
              </div>
              <div className="bg-gray-50 rounded-lg p-4 text-sm text-gray-600">
                <p className="font-medium mb-1">💡 Location Tips</p>
                <ul className="space-y-1 text-xs text-gray-500">
                  <li>• Use county format: "Miami-Dade, FL"</li>
                  <li>• Or city/state: "Austin, TX"</li>
                  <li>• Or ZIP code: "33130"</li>
                </ul>
              </div>
            </div>
          )}

          {/* Property Type */}
          {activeSection === 'propertyType' && (
            <div className="max-w-lg">
              <div className="bg-reo-dark rounded-xl p-5">
                <PropertyTypeSelector selected={propertyTypes} onChange={setPropertyTypes} />
              </div>
              {propertyTypes.length > 0 && (
                <div className="mt-3 flex flex-wrap gap-1.5">
                  {propertyTypes.map((t) => (
                    <span key={t} className="inline-flex items-center gap-1 bg-reo-teal/10 text-reo-teal text-xs px-2 py-1 rounded-full">
                      {t}
                      <button onClick={() => setPropertyTypes(propertyTypes.filter((p) => p !== t))} className="hover:text-white">×</button>
                    </span>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Building & Lot */}
          {activeSection === 'building' && (
            <div className="max-w-lg space-y-4">
              <div className="bg-reo-dark rounded-xl p-5 space-y-4">
                {/* Year Built */}
                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Year Built</label>
                  <div className="flex gap-2">
                    <input type="number" value={building.yearBuiltFrom} onChange={(e) => setBuilding({ ...building, yearBuiltFrom: numVal(e.target.value) })} placeholder="From" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                    <input type="number" value={building.yearBuiltUntil} onChange={(e) => setBuilding({ ...building, yearBuiltUntil: numVal(e.target.value) })} placeholder="Until" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                  </div>
                </div>

                {/* Units */}
                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Total Units</label>
                  <div className="flex gap-2">
                    <input type="number" value={building.totalUnitsMin} onChange={(e) => setBuilding({ ...building, totalUnitsMin: numVal(e.target.value) })} placeholder="Min" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                    <input type="number" value={building.totalUnitsMax} onChange={(e) => setBuilding({ ...building, totalUnitsMax: numVal(e.target.value) })} placeholder="Max" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                  </div>
                </div>

                {/* Building Area */}
                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Building Area (sqft)</label>
                  <div className="flex gap-2">
                    <input type="number" value={building.buildingAreaMin} onChange={(e) => setBuilding({ ...building, buildingAreaMin: numVal(e.target.value) })} placeholder="Min" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                    <input type="number" value={building.buildingAreaMax} onChange={(e) => setBuilding({ ...building, buildingAreaMax: numVal(e.target.value) })} placeholder="Max" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                  </div>
                </div>

                {/* Lot Size */}
                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Lot Size (sqft)</label>
                  <div className="flex gap-2">
                    <input type="number" value={building.lotSizeSfMin} onChange={(e) => setBuilding({ ...building, lotSizeSfMin: numVal(e.target.value) })} placeholder="Min" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                    <input type="number" value={building.lotSizeSfMax} onChange={(e) => setBuilding({ ...building, lotSizeSfMax: numVal(e.target.value) })} placeholder="Max" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                  </div>
                </div>

                {/* Zoning */}
                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Zoning</label>
                  <input type="text" value={building.zoning} onChange={(e) => setBuilding({ ...building, zoning: e.target.value })} placeholder="e.g., C-1, R-3" className="w-full bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                </div>

                {/* Opportunity Zone */}
                <label className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">
                  <div
                    onClick={() => setBuilding({ ...building, opportunityZone: !building.opportunityZone })}
                    className={`w-9 h-5 rounded-full relative transition-colors cursor-pointer ${building.opportunityZone ? 'bg-reo-teal' : 'bg-gray-600'}`}
                  >
                    <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${building.opportunityZone ? 'translate-x-4' : 'translate-x-0.5'}`} />
                  </div>
                  Opportunity Zone Only
                </label>
              </div>
            </div>
          )}

          {/* Owner */}
          {activeSection === 'owner' && (
            <div className="max-w-lg">
              <div className="bg-reo-dark rounded-xl p-5">
                <OwnerFilters config={owner} onChange={setOwner} />
              </div>
            </div>
          )}

          {/* Sales */}
          {activeSection === 'sales' && (
            <div className="max-w-lg">
              <div className="bg-reo-dark rounded-xl p-5 space-y-4">
                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Sale Date Range</label>
                  <div className="flex gap-2">
                    <input type="date" value={sales.dateFrom} onChange={(e) => setSales({ ...sales, dateFrom: e.target.value })} className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white focus:ring-2 focus:ring-reo-teal outline-none" />
                    <input type="date" value={sales.dateUntil} onChange={(e) => setSales({ ...sales, dateUntil: e.target.value })} className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white focus:ring-2 focus:ring-reo-teal outline-none" />
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1.5">Price Range</label>
                  <div className="flex gap-2">
                    <input type="number" value={sales.priceMin} onChange={(e) => setSales({ ...sales, priceMin: numVal(e.target.value) })} placeholder="Min ($)" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                    <input type="number" value={sales.priceMax} onChange={(e) => setSales({ ...sales, priceMax: numVal(e.target.value) })} placeholder="Max ($)" className="w-1/2 bg-white/10 border border-gray-600 rounded px-2 py-1.5 text-sm text-white placeholder-gray-500 focus:ring-2 focus:ring-reo-teal outline-none" />
                  </div>
                </div>

                <label className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">
                  <div
                    onClick={() => setSales({ ...sales, likelyToSell: !sales.likelyToSell })}
                    className={`w-9 h-5 rounded-full relative transition-colors cursor-pointer ${sales.likelyToSell ? 'bg-reo-teal' : 'bg-gray-600'}`}
                  >
                    <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${sales.likelyToSell ? 'translate-x-4' : 'translate-x-0.5'}`} />
                  </div>
                  Likely to Sell
                </label>
              </div>
            </div>
          )}

          {/* Output Fields */}
          {activeSection === 'output' && (
            <div className="max-w-lg">
              <div className="bg-reo-dark rounded-xl p-5">
                <OutputFieldSelector selected={outputFields} onChange={setOutputFields} />
              </div>
            </div>
          )}
        </div>

        {/* Bottom summary bar */}
        <div className="bg-gray-50 border-t border-gray-200 px-6 py-3 flex items-center justify-between text-sm">
          <div className="flex items-center gap-4 text-gray-500">
            {location && <span className="badge badge-info">📍 {location}</span>}
            {propertyTypes.length > 0 && <span className="badge badge-info">🏢 {propertyTypes.length} types</span>}
            {owner.includesPhone && <span className="badge badge-success">📞 With phone</span>}
            {owner.includesEmail && <span className="badge badge-success">📧 With email</span>}
          </div>
          <span className="text-gray-400">Up to {maxProperties} properties</span>
        </div>
      </div>
    </div>
  );
}
