/**
 * IntelligencePage — Hot Demand + Stock Gaps + Product Ideas (with podium
 * medals) + Intent Themes. Same shape as the Shopify embed Intelligence page.
 *
 * @layer Presentation
 */

import { useEffect, useMemo, useState } from 'react';
import { useSearch, useNavigate } from '@tanstack/react-router';
import { PageLayout } from '../../components/shared';
import { useTranslation } from '@/i18n/TranslationProvider';
import { useTenants } from '@/features/tenants/hooks/useTenants';
import { useProductDemand, useQueryPhrase, useIntentTheme } from './hooks/useIntelligence';
import { resolveRange, resolvePeriod, generatePeriods, type TimeRange } from './components/time-range';
import { TimeRangePicker } from './components/TimeRangePicker';
import { PeriodSlider } from './components/PeriodSlider';
import { HotDemandBarChart } from './components/HotDemandBarChart';
import { Medal } from './components/Medal';

interface IntelSearch { range?: TimeRange; period?: string; tenant?: string }

const formatPercent = (n: number) => `${(n * 100).toFixed(1)}%`;

export function IntelligencePage() {
  const { t, locale } = useTranslation();
  const lang: 'en' | 'de' = (locale as string)?.startsWith('de') ? 'de' : 'en';
  const navigate = useNavigate();
  const search = useSearch({ strict: false }) as IntelSearch;

  const { data: tenantsRes } = useTenants();
  const tenants = useMemo(() => (tenantsRes as any)?.tenants ?? (tenantsRes as any)?.items ?? (Array.isArray(tenantsRes) ? tenantsRes : []), [tenantsRes]);
  const fallbackTenantId: string | null = tenants?.[0]?.id ?? null;
  const tenantId = search.tenant && tenants.find((t: any) => t.id === search.tenant) ? search.tenant : fallbackTenantId;

  // Stable ISO strings — same loop-prevention pattern as DashboardPage.
  const rangeParam = (search.range ?? 'daily') as TimeRange;
  const periodParam = search.period ?? null;
  const [periods, setPeriods] = useState(() => generatePeriods(rangeParam));
  const [stable, setStable] = useState(() => {
    const ap = resolvePeriod(rangeParam, periodParam);
    return { range: rangeParam, activeKey: ap.key, longLabel: ap.longLabel,
      startISO: ap.start.toISOString(), endISO: ap.end.toISOString() };
  });
  useEffect(() => { setPeriods(generatePeriods(rangeParam)); }, [rangeParam]);
  useEffect(() => {
    const ap = resolvePeriod(rangeParam, periodParam);
    setStable({ range: rangeParam, activeKey: ap.key, longLabel: ap.longLabel,
      startISO: ap.start.toISOString(), endISO: ap.end.toISOString() });
  }, [rangeParam, periodParam]);
  const { startISO, endISO, activeKey } = stable;
  const resolved = { range: rangeParam };

  const setRange = (next: TimeRange) => navigate({ search: (s: any) => ({ ...s, range: next, period: undefined }) });
  const setPeriod = (key: string) => navigate({ search: (s: any) => ({ ...s, period: key }) });
  const setTenant = (id: string) => navigate({ search: (s: any) => ({ ...s, tenant: id }) });

  const { data: demand } = useProductDemand(tenantId, 'demand', { startISO, endISO, limit: 10 });
  const { data: stockGaps } = useProductDemand(tenantId, 'oos', { startISO, endISO, limit: 10 });
  const { data: phrases } = useQueryPhrase(tenantId, { startISO, endISO, limit: 10, gapOnly: true });
  const { data: themes } = useIntentTheme(tenantId, { startISO, endISO });

  if (!tenantId) {
    return <PageLayout title="Customer Intelligence"><div className="text-muted-foreground p-6">No tenants yet.</div></PageLayout>;
  }

  return (
    <PageLayout title="Customer Intelligence" subtitle="What your customers ask — products in demand, stock gaps, ideas, top themes.">
      {tenants.length > 1 && (
        <div className="mb-4 flex items-center gap-2">
          <label className="text-xs text-muted-foreground">Tenant</label>
          <select value={tenantId ?? ''} onChange={(e) => setTenant(e.target.value)}
            className="text-sm border border-border rounded-md px-2 py-1 bg-card">
            {tenants.map((tn: any) => <option key={tn.id} value={tn.id}>{tn.name || tn.domain}</option>)}
          </select>
        </div>
      )}

      <TimeRangePicker active={resolved.range} lang={lang} onChange={setRange} />
      <PeriodSlider periods={periods} activeKey={activeKey} onPick={setPeriod} />

      <div className="flex flex-col gap-7">
        <div className="grid gap-7" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(420px, 1fr))' }}>
          <section className="rounded-2xl border border-border bg-card p-5">
            <h3 className="text-center text-base font-semibold mb-3">Hot Demand — products customers ask about most</h3>
            {!demand || demand.length === 0 ? (
              <p className="text-muted-foreground text-sm">No product-matched commands in this window.</p>
            ) : (
              <>
                <HotDemandBarChart products={demand} mode="demand" label="Asks" />
                <table className="w-full text-sm mt-3">
                  <thead className="text-left text-xs text-muted-foreground border-b border-border">
                    <tr><th className="py-2">Product</th><th className="py-2">Asks</th></tr>
                  </thead>
                  <tbody>
                    {demand.map((p) => (
                      <tr key={p.productId} className="border-b border-border/60">
                        <td className="py-2">{p.productName ?? 'Unknown product'}</td>
                        <td className="py-2 tabular-nums">{p.demandHits.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </>
            )}
          </section>

          <section className="rounded-2xl border border-border bg-card p-5">
            <h3 className="text-center text-base font-semibold mb-1">Stock Gaps — products customers wanted while out of stock</h3>
            <p className="text-center text-xs text-muted-foreground mb-3">Each ask while out of stock is a missed sale.</p>
            {!stockGaps || stockGaps.length === 0 ? (
              <div className="rounded-md bg-emerald-50 text-emerald-900 px-3 py-2 text-sm">Nothing was asked for while out of stock — top products were available.</div>
            ) : (
              <>
                <HotDemandBarChart products={stockGaps} mode="oos" label="Out of stock" />
                <table className="w-full text-sm mt-3">
                  <thead className="text-left text-xs text-muted-foreground border-b border-border">
                    <tr><th className="py-2">Product</th><th className="py-2">OOS asks</th><th className="py-2">Total asks</th></tr>
                  </thead>
                  <tbody>
                    {stockGaps.map((p) => (
                      <tr key={p.productId} className="border-b border-border/60">
                        <td className="py-2">{p.productName ?? 'Unknown product'}</td>
                        <td className="py-2 tabular-nums">{p.oosHits.toLocaleString()}</td>
                        <td className="py-2 tabular-nums">{p.demandHits.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </>
            )}
          </section>
        </div>

        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-1">Product Ideas — what customers ask for that you don't sell yet</h3>
          <p className="text-center text-xs text-muted-foreground mb-3">Phrases that found no match in your catalog. Treat as a backlog.</p>
          {!phrases || phrases.length === 0 ? (
            <div className="rounded-md bg-blue-50 text-blue-900 px-3 py-2 text-sm">No ideas yet — every query matched something in your catalog.</div>
          ) : (
            <table className="w-full text-sm">
              <thead className="text-left text-xs text-muted-foreground border-b border-border">
                <tr><th className="py-2">Phrase</th><th className="py-2">Asks</th></tr>
              </thead>
              <tbody>
                {phrases.map((q, idx) => {
                  const place = (idx < 3 ? (idx + 1) : null) as 1 | 2 | 3 | null;
                  return (
                    <tr key={q.phraseHash} className="border-b border-border/60">
                      <td className="py-2">
                        <span className="inline-flex items-center gap-3" style={{ minHeight: 44 }}>
                          {place && <Medal place={place} />}
                          <span>{q.sampleText ?? '(unknown)'}</span>
                        </span>
                      </td>
                      <td className="py-2 tabular-nums">{q.gapCount.toLocaleString()}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </section>

        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-3">Intent Themes — what kinds of help customers seek</h3>
          {!themes || themes.length === 0 ? (
            <p className="text-muted-foreground text-sm">No intent themes yet.</p>
          ) : (
            <table className="w-full text-sm">
              <thead className="text-left text-xs text-muted-foreground border-b border-border">
                <tr><th className="py-2">Theme</th><th className="py-2">Asks</th><th className="py-2">Share</th></tr>
              </thead>
              <tbody>
                {themes.map((it) => (
                  <tr key={it.themeUuid} className="border-b border-border/60">
                    <td className="py-2">{it.themeLabel}</td>
                    <td className="py-2 tabular-nums">{it.hitCount.toLocaleString()}</td>
                    <td className="py-2 tabular-nums">{formatPercent(it.percentage)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </section>
      </div>
    </PageLayout>
  );
}
