/**
 * DashboardPage — same statistics surface as the Shopify embed Analytics page,
 * scoped to a tenant the CP user owns. KPI hero (today/week/month-adaptive),
 * range picker, 4 full bar-chart sections (commands / visits / suggested
 * products / AI revenue), error breakdown.
 *
 * @layer Presentation
 */

import { useEffect, useMemo, useState } from 'react';
import { useSearch, useNavigate } from '@tanstack/react-router';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import { PageLayout } from '../../components/shared';
import { useTranslation } from '@/i18n/TranslationProvider';
import { useTenants } from '@/features/tenants/hooks/useTenants';
import {
  useTodayKpis,
  useAnalyticsOverview,
  useAnalyticsErrors,
  useAnalyticsTimeseries,
  useKpiTimeseries,
} from '@/features/intelligence/hooks/useIntelligence';
import { resolveRange, kpiWindow, type TimeRange, type KpiWindowScope } from '@/features/intelligence/components/time-range';
import { TimeRangePicker } from '@/features/intelligence/components/TimeRangePicker';
import { KpiCard, IconVisits, IconCommands, IconProducts, IconRevenue } from '@/features/intelligence/components/KpiCard';
import { KpiBarChart } from '@/features/intelligence/components/KpiBarChart';

const USD_FMT = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
const formatCents = (c: number) => USD_FMT.format(Math.round(c / 100));
const formatPercent = (n: number) => `${(n * 100).toFixed(1)}%`;
const formatMs = (n: number) => `${Math.round(n)} ms`;

const ERROR_LABELS_EN: Record<string, string> = {
  internal:    'Internal server error — the request crashed before completing.',
  ai_service:  'AI service unavailable — voice transcription or NLU call failed.',
  compilation: "Could not build an action plan from the customer's request.",
  not_found:   'Target element could not be found on the page (DOM mismatch).',
};

interface DashSearch { range?: TimeRange; tenant?: string }

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

  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((tn: any) => tn.id === search.tenant) ? search.tenant : fallbackTenantId;

  // Stable ISO strings — recomputed only when the URL range param changes.
  // Hooks accept ISO strings (not Date objects) so the queryKey stays
  // referentially stable and React Query doesn't enter a refetch loop.
  const rangeParam = (search.range ?? 'daily') as TimeRange;
  const [stable, setStable] = useState(() => {
    const r = resolveRange(rangeParam); const k = kpiWindow(rangeParam);
    return { range: r.range, granularity: r.granularity, scope: k.scope,
      rangeStartISO: r.startDate.toISOString(), rangeEndISO: r.endDate.toISOString(),
      kpiStartISO: k.startDate.toISOString(), kpiEndISO: k.endDate.toISOString() };
  });
  useEffect(() => {
    const r = resolveRange(rangeParam); const k = kpiWindow(rangeParam);
    setStable({ range: r.range, granularity: r.granularity, scope: k.scope,
      rangeStartISO: r.startDate.toISOString(), rangeEndISO: r.endDate.toISOString(),
      kpiStartISO: k.startDate.toISOString(), kpiEndISO: k.endDate.toISOString() });
  }, [rangeParam]);
  const { range, granularity, scope, rangeStartISO, rangeEndISO, kpiStartISO, kpiEndISO } = stable;

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

  const { data: today } = useTodayKpis(tenantId, { startISO: kpiStartISO, endISO: kpiEndISO });
  const { data: overview } = useAnalyticsOverview(tenantId, { startISO: rangeStartISO, endISO: rangeEndISO });
  const { data: errors } = useAnalyticsErrors(tenantId, { startISO: rangeStartISO, endISO: rangeEndISO });
  const { data: timeseries } = useAnalyticsTimeseries(tenantId, granularity, { startISO: rangeStartISO, endISO: rangeEndISO });
  const { data: kpiSeries } = useKpiTimeseries(tenantId, granularity, { startISO: rangeStartISO, endISO: rangeEndISO });

  const heroHeading = scope === 'week' ? 'This week at a glance' : scope === 'month' ? 'This month at a glance' : 'Today at a glance';

  const cmdsBarData = (timeseries ?? []).map((p) => ({
    period: new Date(p.period).toLocaleDateString(locale, granularity === 'hour' ? { hour: '2-digit', minute: '2-digit', hour12: false } : { month: 'short', day: 'numeric' }),
    total: p.total,
  }));

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

  return (
    <PageLayout title={t('dashboard.title')}>
      {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={range} lang={lang} onChange={setRange} />

      {today && (
        <div className="mb-7">
          <h3 className="text-center text-lg font-semibold mb-3">{heroHeading}</h3>
          <div className="grid gap-4" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))' }}>
            <KpiCard label="Visits"             value={today.visits.toLocaleString()}            accent="#1e5ba8" bg="rgba(30,91,168,0.10)"  icon={IconVisits} />
            <KpiCard label="Commands"           value={today.commands.toLocaleString()}          accent="#2a7"    bg="rgba(42,119,72,0.10)" icon={IconCommands} />
            <KpiCard label="Products suggested" value={today.suggestedProducts.toLocaleString()} accent="#bc6c25" bg="rgba(188,108,37,0.10)" icon={IconProducts} />
            <KpiCard label="AI revenue"         value={formatCents(today.revenueCents)}          accent="#7a3da9" bg="rgba(122,61,169,0.10)" icon={IconRevenue} />
          </div>
        </div>
      )}

      <div className="flex flex-col gap-7">
        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-3">Commands over time</h3>
          {!timeseries || timeseries.length === 0 ? (
            <p className="text-muted-foreground text-sm">No commands in this period yet.</p>
          ) : (
            <div className="w-full h-72">
              <ResponsiveContainer>
                <BarChart data={cmdsBarData} margin={{ top: 10, right: 20, left: 0, bottom: 0 }} barCategoryGap="20%">
                  <CartesianGrid stroke="#e1e3e5" strokeDasharray="3 3" vertical={false} />
                  <XAxis dataKey="period" stroke="#6d7175" tick={{ fontSize: 12 }} />
                  <YAxis stroke="#6d7175" tick={{ fontSize: 12 }} allowDecimals={false} />
                  <Tooltip contentStyle={{ background: '#fff', border: '1px solid #e1e3e5', borderRadius: 8, fontSize: 12 }} />
                  <Bar dataKey="total" name="Commands" fill="#2a7" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </section>

        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-3">Visits over time</h3>
          {kpiSeries && kpiSeries.some((p) => p.visits > 0) ? (
            <KpiBarChart points={kpiSeries} granularity={granularity} metricKey="visits" seriesLabel="Visits" color="#1e5ba8" />
          ) : <p className="text-muted-foreground text-sm">No visits recorded in this period yet.</p>}
        </section>

        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-3">Products suggested over time</h3>
          {kpiSeries && kpiSeries.some((p) => p.suggestedProducts > 0) ? (
            <KpiBarChart points={kpiSeries} granularity={granularity} metricKey="suggestedProducts" seriesLabel="Products" color="#bc6c25" />
          ) : <p className="text-muted-foreground text-sm">No products suggested in this period yet.</p>}
        </section>

        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-3">AI revenue over time</h3>
          {kpiSeries && kpiSeries.some((p) => p.revenueCents > 0) ? (
            <KpiBarChart points={kpiSeries} granularity={granularity} metricKey="revenueCents" seriesLabel="Revenue" color="#7a3da9" valueFormatter={formatCents} />
          ) : <p className="text-muted-foreground text-sm">No AI-attributed revenue in this period yet.</p>}
        </section>

        <section className="rounded-2xl border border-border bg-card p-5">
          <h3 className="text-center text-base font-semibold mb-3">Error breakdown</h3>
          {!errors || errors.length === 0 ? <p className="text-muted-foreground text-sm">No errors in this period.</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">What went wrong</th><th className="py-2">Occurrences</th><th className="py-2">Share</th></tr>
              </thead>
              <tbody>
                {errors.map((e) => (
                  <tr key={e.errorType} className="border-b border-border/60">
                    <td className="py-2">{ERROR_LABELS_EN[e.errorType] ?? e.errorType}</td>
                    <td className="py-2 tabular-nums">{e.count.toLocaleString()}</td>
                    <td className="py-2 tabular-nums">{formatPercent(e.percentage)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </section>

        {overview && (
          <div className="text-xs text-muted-foreground text-center">
            Success rate {formatPercent(overview.successRate)} · Avg processing {formatMs(overview.avgProcessingMs)}
          </div>
        )}
      </div>
    </PageLayout>
  );
}
