/* ============================================================
   Screen 4 — Fermerlar (Farmer Directory)
   ============================================================ */

const FARMERS_PAGE = 20;

function ScreenFarmers() {
  const [search, setSearch] = useState('');
  const [region, setRegion] = useState('');
  const [primary, setPrimary] = useState('');
  const [page, setPage] = useState(0);
  const [selected, setSelected] = useState(null);

  // Fetch
  const farmersList = useApi(`/api/farmers?limit=${FARMERS_PAGE}&offset=${page * FARMERS_PAGE}`, { pollMs: 15000 });
  const overview    = useApi('/api/stats/overview', { pollMs: 15000 });
  const byRegion    = useApi('/api/stats/by-region', { pollMs: 30000 });

  const allFarmers = farmersList.data?.items || [];
  const overviewStats = overview.data || {};

  // Top region by farmer count
  const topRegion = useMemo(() => {
    const items = byRegion.data?.items || [];
    const sorted = [...items].sort((a, b) => (b.farmers || 0) - (a.farmers || 0));
    return sorted[0] || null;
  }, [byRegion.data]);

  // Client-side filters on current page (no separate API for now)
  const filtered = useMemo(() => {
    const k = search.trim().toLowerCase();
    return allFarmers.filter((f) => {
      if (k && !(`${f.name}`.toLowerCase().includes(k) || `${f.id}`.toLowerCase().includes(k))) return false;
      if (region && f.region_id !== region) return false;
      if (primary && f.primary_topic !== primary) return false;
      return true;
    });
  }, [allFarmers, search, region, primary]);

  // Auto-select first row
  React.useEffect(() => {
    if (!selected && filtered.length > 0) setSelected(filtered[0].id);
  }, [filtered, selected]);

  const totalRegistered = overviewStats.farmers ?? allFarmers.length;
  const avgInq = totalRegistered > 0 ? (overviewStats.total / totalRegistered).toFixed(1) : '0';

  return (
    <div className="page" style={{ maxWidth: '100%' }}>
      <div className="page-head">
        <div>
          <div className="page-crumbs">
            <span>Asosiy</span><span>/</span><span style={{ color: 'var(--ink-2)' }}>Fermerlar</span>
          </div>
          <h1 className="page-title">Fermerlar<span className="ru">Фермеры · Farmer Directory</span></h1>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={farmersList.refresh}><Icon name="refresh" size={12} /> Yangilash</button>
          <button className="btn"><Icon name="download" size={12} /> Eksport</button>
        </div>
      </div>

      {/* Top KPI strip */}
      <div className="kpi-strip mb-12" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <FarmerKpi label="Roʻyxatdan oʻtgan" value={formatNum(totalRegistered)} hint="jami" />
        <FarmerKpi label="Bu sahifa"          value={formatNum(filtered.length)} hint={`sahifa ${page + 1}`} />
        <FarmerKpi label="Oʻrt. murojaat"     value={avgInq} hint="fermer boshiga" />
        <FarmerKpi label="Eng faol viloyat"   value={topRegion?.uz || '—'} hint={topRegion ? `${topRegion.farmers} ta fermer` : ''} mono={false} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 16, alignItems: 'start' }}>
        {/* LEFT: Table */}
        <Panel
          title="Fermerlar bazasi"
          sub={`${formatNum(allFarmers.length)} ta sahifada${farmersList.loading ? ' · yuklanmoqda' : ''}`}
          body={false}
          actions={
            <>
              <button className="btn btn-ghost btn-sm"><Icon name="filter" size={12} /></button>
              <button className="btn btn-ghost btn-sm"><Icon name="download" size={12} /></button>
            </>
          }
        >
          {/* Filter bar */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr auto', gap: 8, padding: '10px 14px', borderBottom: '1px solid var(--line)', alignItems: 'center', background: 'var(--bg-sunken)' }}>
            <input
              className="input"
              placeholder="Ism yoki ID..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <select className="select" value={region} onChange={(e) => setRegion(e.target.value)}>
              <option value="">Hudud: Barchasi</option>
              {REGIONS.map((r) => <option key={r.id} value={r.id}>{r.uz}</option>)}
            </select>
            <select className="select" value={primary} onChange={(e) => setPrimary(e.target.value)}>
              <option value="">Asosiy mavzu: Barchasi</option>
              {TOPICS.map((t) => <option key={t.id} value={t.id}>{t.uz}</option>)}
            </select>
            <button className="btn btn-sm" onClick={() => { setSearch(''); setRegion(''); setPrimary(''); }}>Tozalash</button>
          </div>

          <div>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Fermer</th>
                  <th>Hudud</th>
                  <th style={{ textAlign: 'right' }}>Murojaat</th>
                  <th>Oxirgi faollik</th>
                  <th>Asosiy mavzu</th>
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 && !farmersList.loading && (
                  <tr>
                    <td colSpan={5} style={{ padding: 32, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12 }}>
                      Fermerlar topilmadi. Bot orqali kelgan har bir foydalanuvchi shu yerda paydo boʻladi.
                    </td>
                  </tr>
                )}
                {filtered.map((f) => {
                  const r = f.region_id ? REGION_BY_ID[f.region_id] : null;
                  const primaryTopic = f.primary_topic ? TOPIC_BY_ID[f.primary_topic] : null;
                  const lastSeenDays = Math.max(0, Math.floor((Date.now() / 1000 - f.last_seen) / 86400));
                  return (
                    <tr
                      key={f.id}
                      style={{ cursor: 'pointer', background: selected === f.id ? 'var(--bg-sunken)' : '' }}
                      onClick={() => setSelected(f.id)}
                    >
                      <td>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <Avatar name={f.name} size={26} />
                          <div>
                            <div style={{ fontSize: 12, fontWeight: 500 }}>{f.name}</div>
                            <div style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--ink-4)' }}>
                              {f.id}{f.phone ? ` · ${f.phone}` : ''}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td>
                        <span style={{ fontSize: 11.5 }}>{r?.uz || '—'}</span>
                      </td>
                      <td style={{ textAlign: 'right' }}>
                        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                          <div style={{ width: 50 }}><MiniBar value={f.inquiries || 0} max={Math.max(40, ...filtered.map(x => x.inquiries || 0))} color="var(--accent)" height={5} /></div>
                          <span className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{f.inquiries || 0}</span>
                        </div>
                      </td>
                      <td>
                        <span className="mono" style={{ fontSize: 11, color: lastSeenDays < 3 ? 'var(--jade)' : lastSeenDays < 14 ? 'var(--ink-2)' : 'var(--ink-4)' }}>
                          {lastSeenDays === 0 ? 'bugun' : lastSeenDays < 7 ? `${lastSeenDays} kun` : lastSeenDays < 30 ? `${Math.floor(lastSeenDays / 7)} hafta` : `${Math.floor(lastSeenDays / 30)} oy`}
                        </span>
                      </td>
                      <td>
                        {primaryTopic ? (
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <TopicMark topicId={f.primary_topic} size={14} />
                            <span style={{ fontSize: 11.5 }}>{primaryTopic.uz}</span>
                          </div>
                        ) : <span style={{ color: 'var(--ink-4)', fontSize: 11 }}>—</span>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 14px', borderTop: '1px solid var(--line)', fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>
            <span>sahifa {page + 1} · {allFarmers.length} ta sahifada</span>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(p => p - 1)}>‹</button>
              <button className="btn btn-sm" disabled={allFarmers.length < FARMERS_PAGE} onClick={() => setPage(p => p + 1)}>›</button>
            </div>
          </div>
        </Panel>

        {/* RIGHT: Profile */}
        <FarmerProfile farmerId={selected} />
      </div>
    </div>
  );
}

// ============================================================
// Profile drawer
// ============================================================
function FarmerProfile({ farmerId }) {
  const { data, loading } = useApi(farmerId ? `/api/farmers/${farmerId}` : null);
  const recent = data?.recent || [];
  // Hooks must run on every render → keep this before any early returns.
  const topicDist = useMemo(() => {
    const c = {};
    recent.forEach((i) => { if (i.topic_id) c[i.topic_id] = (c[i.topic_id] || 0) + 1; });
    return Object.entries(c).sort((a, b) => b[1] - a[1])
      .map(([tid, n]) => ({ id: tid, label: TOPIC_BY_ID[tid]?.uz || tid, value: n, color: TOPIC_BY_ID[tid]?.color }));
  }, [recent]);

  if (!farmerId) {
    return (
      <div className="panel" style={{ padding: 24, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12 }}>
        Fermerni tanlang.
      </div>
    );
  }
  if (!data) {
    return (
      <div className="panel" style={{ padding: 24, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12 }}>
        {loading ? 'Yuklanmoqda…' : 'Maʼlumot yoʻq.'}
      </div>
    );
  }

  const { farmer, stats } = data;
  const region = farmer.region_id ? REGION_BY_ID[farmer.region_id] : null;
  const lastSeenDays = Math.max(0, Math.floor((Date.now() / 1000 - farmer.last_seen) / 86400));
  const status = lastSeenDays < 7 ? 'active' : lastSeenDays < 30 ? 'dormant' : 'inactive';
  const sentiment = stats.neg > stats.pos + stats.neu ? 'negative' : stats.pos > stats.neg + stats.neu ? 'positive' : 'neutral';

  return (
    <div className="panel" style={{ overflow: 'hidden' }}>
      <div style={{ padding: 18, borderBottom: '1px solid var(--line)', background: 'var(--bg-sunken)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Avatar name={farmer.name} size={56} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 500, letterSpacing: '-0.01em' }}>{farmer.name}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{farmer.id}</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
              <StatusBadge status={status} />
              {lastSeenDays < 3 && <span className="chip chip-jade">Onlayn</span>}
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: 14, borderBottom: '1px solid var(--line)' }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>Kontakt</div>
        <div style={{ display: 'grid', gap: 6, fontSize: 11.5 }}>
          <Row k="Telegram ID" v={<span className="mono">{farmer.telegram_id}</span>} />
          {farmer.phone && <Row k="Telefon" v={<span className="mono">{farmer.phone}</span>} />}
          <Row k="Hudud" v={region ? `${region.uz} (${region.code})` : '—'} />
          <Row k="Birinchi ulanish" v={<span className="mono">{new Date(farmer.first_seen * 1000).toLocaleDateString('uz')}</span>} />
          <Row k="Oxirgi faollik" v={<span className="mono">{lastSeenDays} kun oldin</span>} />
        </div>
      </div>

      <div style={{ padding: 14, borderBottom: '1px solid var(--line)' }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>Statistika</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, fontSize: 11.5 }}>
          <div>
            <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Jami murojaat</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 500 }}>{stats.total || 0}</div>
          </div>
          <div>
            <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Sentiment</div>
            <SentimentBar sentiment={sentiment} />
          </div>
        </div>
      </div>

      <div style={{ padding: 14, borderBottom: '1px solid var(--line)' }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>Mavzular taqsimoti</div>
        {topicDist.length === 0 ? (
          <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>Hali tasniflangan murojaat yoʻq.</div>
        ) : (
          topicDist.map((d) => (
            <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0', fontSize: 11.5 }}>
              <span style={{ width: 10, height: 10, background: d.color, borderRadius: 2 }} />
              <span style={{ flex: 1 }}>{d.label}</span>
              <span className="mono" style={{ color: 'var(--ink-3)' }}>{d.value}</span>
            </div>
          ))
        )}
      </div>

      <div style={{ padding: 14 }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>Soʻnggi murojaatlar</div>
        {recent.length === 0 ? (
          <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>Hali murojaat yoʻq.</div>
        ) : (
          recent.slice(0, 6).map((i) => (
            <div key={i.id} style={{ borderBottom: '1px dotted var(--line)', padding: '6px 0', fontSize: 11 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
                {i.topic_id && TOPIC_BY_ID[i.topic_id] ? (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontWeight: 500 }}>
                    <TopicMark topicId={i.topic_id} size={12} />
                    {TOPIC_BY_ID[i.topic_id].uz}
                  </span>
                ) : <span style={{ color: 'var(--ink-4)' }}>—</span>}
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-4)' }}>{formatRel(new Date(i.created_at * 1000))}</span>
              </div>
              <div style={{ color: 'var(--ink-2)', marginTop: 2, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                {i.text}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

// ============================================================
// Helpers
// ============================================================
function FarmerKpi({ label, value, hint, mono = true }) {
  return (
    <div className="kpi">
      <div className="kpi-label">{label}</div>
      <div className={mono ? 'kpi-value' : ''} style={!mono ? { fontSize: 16, fontFamily: 'var(--font-sans)', fontWeight: 500, marginTop: 4 } : {}}>{value}</div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{hint}</div>
    </div>
  );
}

function SentimentBar({ sentiment }) {
  const map = {
    positive: { neg: 1, neu: 2, pos: 7, lbl: 'Ijobiy' },
    neutral:  { neg: 2, neu: 6, pos: 2, lbl: 'Neytral' },
    negative: { neg: 6, neu: 3, pos: 1, lbl: 'Salbiy' },
  };
  const v = map[sentiment] || map.neutral;
  const total = v.neg + v.neu + v.pos;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{ width: 60, height: 5, display: 'flex', borderRadius: 1, overflow: 'hidden', background: 'var(--bg-sunken)' }}>
        <div style={{ width: `${(v.neg / total) * 100}%`, background: 'var(--rose)' }} />
        <div style={{ width: `${(v.neu / total) * 100}%`, background: 'var(--ink-4)' }} />
        <div style={{ width: `${(v.pos / total) * 100}%`, background: 'var(--jade)' }} />
      </div>
      <span style={{ fontSize: 10.5, color: sentiment === 'positive' ? 'var(--jade)' : sentiment === 'negative' ? 'var(--rose)' : 'var(--ink-3)' }}>{v.lbl}</span>
    </div>
  );
}

function StatusBadge({ status }) {
  const map = {
    active:   { uz: 'Faol',      cls: 'chip-jade' },
    dormant:  { uz: 'Sust',      cls: 'chip-amber' },
    inactive: { uz: 'Faol emas', cls: 'chip' },
    blocked:  { uz: 'Bloklangan',cls: 'chip-rose' },
  };
  const m = map[status] || map.inactive;
  return <span className={`chip ${m.cls}`}>{m.uz}</span>;
}

function Row({ k, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
      <span style={{ color: 'var(--ink-4)' }}>{k}</span>
      <span style={{ color: 'var(--ink)', textAlign: 'right' }}>{v}</span>
    </div>
  );
}

window.ScreenFarmers = ScreenFarmers;
