import { useEffect, useState } from 'react';
import { Building2, Factory } from 'lucide-react';
import { api, qs } from '../api';
import { Card, Badge, inputCls, Spinner, ErrorBox, Table } from '../components/ui';

function TabBar({ tabs, active, onChange }) {
  return (
    <div className="flex gap-1 border-b border-border-soft">
      {tabs.map(t => (
        <button
          key={t.key}
          onClick={() => onChange(t.key)}
          className={`px-3.5 py-2 text-[13px] font-medium border-b-2 -mb-px transition-colors ${
            active === t.key ? 'border-accent text-accent' : 'border-transparent text-muted hover:text-text'
          }`}
        >
          {t.label}
        </button>
      ))}
    </div>
  );
}

function leadScoreColor(score) {
  if (score >= 70) return 'green';
  if (score >= 40) return 'yellow';
  return 'muted';
}

export default function Market() {
  const [tab, setTab] = useState('datacenters');
  const [filters, setFilters] = useState(null);

  // Datacenters
  const [dcFilters, setDcFilters] = useState({ search: '', vendor: '', region: '', type: '', sort: '' });
  const [datacenters, setDatacenters] = useState(null);
  const [dcError, setDcError] = useState(null);

  // Companies
  const [coFilters, setCoFilters] = useState({ search: '', industry: '', data_warehouse: '', city: '', sort: '' });
  const [companies, setCompanies] = useState(null);
  const [coError, setCoError] = useState(null);

  useEffect(() => {
    api.get('/market/filters').then(setFilters).catch(() => setFilters({}));
  }, []);

  useEffect(() => {
    setDcError(null);
    setDatacenters(null);
    api.get(`/market/datacenters${qs(dcFilters)}`).then(setDatacenters).catch(setDcError);
  }, [dcFilters]);

  useEffect(() => {
    setCoError(null);
    setCompanies(null);
    api.get(`/market/companies${qs(coFilters)}`).then(setCompanies).catch(setCoError);
  }, [coFilters]);

  return (
    <div className="space-y-5 fade-in">
      <div>
        <h1 className="text-xl font-bold tracking-tight">Marktverkenning</h1>
        <p className="text-[13px] text-muted mt-0.5">Datacenters en tech-bedrijven in de regio</p>
      </div>

      <TabBar
        tabs={[{ key: 'datacenters', label: 'Datacenters' }, { key: 'companies', label: 'Tech-bedrijven' }]}
        active={tab}
        onChange={setTab}
      />

      {tab === 'datacenters' && (
        <Card padding={false}>
          <div className="p-4 space-y-4">
            {/* Filterbalk */}
            <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
              <input
                className={inputCls}
                placeholder="Zoeken..."
                value={dcFilters.search}
                onChange={e => setDcFilters({ ...dcFilters, search: e.target.value })}
              />
              <select className={inputCls} value={dcFilters.vendor} onChange={e => setDcFilters({ ...dcFilters, vendor: e.target.value })}>
                <option value="">Alle vendors</option>
                {(filters?.vendors || []).map(v => <option key={v} value={v}>{v}</option>)}
              </select>
              <select className={inputCls} value={dcFilters.region} onChange={e => setDcFilters({ ...dcFilters, region: e.target.value })}>
                <option value="">Alle regio's</option>
                {(filters?.regions || []).map(r => <option key={r} value={r}>{r}</option>)}
              </select>
              <select className={inputCls} value={dcFilters.type} onChange={e => setDcFilters({ ...dcFilters, type: e.target.value })}>
                <option value="">Alle types</option>
                {(filters?.types || []).map(t => <option key={t} value={t}>{t}</option>)}
              </select>
              <select className={inputCls} value={dcFilters.sort} onChange={e => setDcFilters({ ...dcFilters, sort: e.target.value })}>
                <option value="">Sorteer: vermogen</option>
                <option value="name">Sorteer: naam</option>
              </select>
            </div>

            {dcError ? <ErrorBox error={dcError} /> : !datacenters ? <Spinner /> : (
              <Table
                columns={[
                  { label: 'Naam', render: d => <span className="font-medium flex items-center gap-2"><Building2 className="w-3.5 h-3.5 text-muted" />{d.name}</span> },
                  { label: 'Stad', key: 'city' },
                  { label: 'Regio', render: d => <span className="text-muted">{d.region || '-'}</span> },
                  { label: 'Type', render: d => <span className="text-muted">{d.type || '-'}</span> },
                  { label: 'Operator', render: d => <span className="text-muted">{d.operator || '-'}</span> },
                  { label: 'Tier', render: d => d.tier ? <Badge color="accent">{d.tier}</Badge> : <span className="text-muted">-</span> },
                  { label: 'Vermogen', render: d => d.power_mw != null ? `${d.power_mw} MW` : '-' },
                  { label: 'Vendors', render: d => <span className="text-muted block max-w-[220px] truncate">{d.network_vendors || '-'}</span> }
                ]}
                rows={datacenters}
                keyFn={d => d.id}
                empty={<div className="text-center text-muted text-[13px] py-8">Geen datacenters gevonden</div>}
              />
            )}
          </div>
        </Card>
      )}

      {tab === 'companies' && (
        <Card padding={false}>
          <div className="p-4 space-y-4">
            {/* Filterbalk */}
            <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
              <input
                className={inputCls}
                placeholder="Zoeken..."
                value={coFilters.search}
                onChange={e => setCoFilters({ ...coFilters, search: e.target.value })}
              />
              <select className={inputCls} value={coFilters.industry} onChange={e => setCoFilters({ ...coFilters, industry: e.target.value })}>
                <option value="">Alle branches</option>
                {(filters?.industries || []).map(i => <option key={i} value={i}>{i}</option>)}
              </select>
              <select className={inputCls} value={coFilters.data_warehouse} onChange={e => setCoFilters({ ...coFilters, data_warehouse: e.target.value })}>
                <option value="">Alle data warehouses</option>
                {(filters?.data_warehouses || []).map(w => <option key={w} value={w}>{w}</option>)}
              </select>
              <select className={inputCls} value={coFilters.city} onChange={e => setCoFilters({ ...coFilters, city: e.target.value })}>
                <option value="">Alle steden</option>
                {(filters?.cities || []).map(c => <option key={c} value={c}>{c}</option>)}
              </select>
              <select className={inputCls} value={coFilters.sort} onChange={e => setCoFilters({ ...coFilters, sort: e.target.value })}>
                <option value="">Sorteer: lead score</option>
                <option value="name">Sorteer: naam</option>
                <option value="employees">Sorteer: werknemers</option>
              </select>
            </div>

            {coError ? <ErrorBox error={coError} /> : !companies ? <Spinner /> : (
              <Table
                columns={[
                  { label: 'Naam', render: c => <span className="font-medium flex items-center gap-2"><Factory className="w-3.5 h-3.5 text-muted" />{c.name}</span> },
                  { label: 'Branche', render: c => <span className="text-muted">{c.industry || '-'}</span> },
                  { label: 'Stad', render: c => <span className="text-muted">{c.city || '-'}</span> },
                  { label: 'Werknemers', render: c => c.employees ?? '-' },
                  { label: 'Data warehouse', render: c => <span className="text-muted block max-w-[160px] truncate">{c.data_warehouse || '-'}</span> },
                  { label: 'BI-tools', render: c => <span className="text-muted block max-w-[140px] truncate">{c.bi_tools || '-'}</span> },
                  { label: 'Cloud', render: c => <span className="text-muted">{c.cloud_provider || '-'}</span> },
                  { label: 'Lead score', render: c => <Badge color={leadScoreColor(c.lead_score)}>{c.lead_score ?? '-'}</Badge> },
                  { label: 'Lead status', render: c => <span className="text-muted">{c.lead_status || '-'}</span> }
                ]}
                rows={companies}
                keyFn={c => c.id}
                empty={<div className="text-center text-muted text-[13px] py-8">Geen bedrijven gevonden</div>}
              />
            )}
          </div>
        </Card>
      )}
    </div>
  );
}
