import React, { useEffect, useState } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';

type Row = Record<string, any>;

interface Payload {
  summary: Record<string, number>;
  missing_model: Row[];
  missing_image: Row[];
  no_offers_sample: Row[];
  zero_price_sample: Row[];
  duplicate_ean: Row[];
  singleton_models: Row[];
  stale_products_by_brand: Row[];
  tiny_brands: Row[];
  error?: string;
}

function Tile({ label, value, tone = 'neutral', hint }: { label: string; value: number | string; tone?: 'neutral' | 'warn' | 'bad' | 'ok'; hint?: string }) {
  const toneClass =
    tone === 'bad' ? 'border-[#FF3B3B]/40 text-[#FF3B3B]' :
    tone === 'warn' ? 'border-[#FFD700]/40 text-[#FFD700]' :
    tone === 'ok' ? 'border-[#00FF6A]/40 text-[#00FF6A]' :
    'border-[#333] text-[#F5F5F5]';
  return (
    <div className={`rounded-xl border ${toneClass} bg-[#141414] p-4`}>
      <div className="text-xs uppercase tracking-wider text-[#999]">{label}</div>
      <div className="mt-1 text-2xl font-bold">{value}</div>
      {hint && <div className="mt-1 text-xs text-[#666]">{hint}</div>}
    </div>
  );
}

function Section({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
  return (
    <div className="rounded-xl border border-[#333] bg-[#141414] p-5">
      <h3 className="text-base font-semibold text-[#F5F5F5]">{title}</h3>
      {description && <p className="mt-1 text-xs text-[#999]">{description}</p>}
      <div className="mt-3">{children}</div>
    </div>
  );
}

function Table({ headers, rows, empty = 'Geen rijen' }: { headers: string[]; rows: (string | number)[][]; empty?: string }) {
  if (!rows.length) return <div className="text-sm text-[#666] italic py-2">{empty}</div>;
  return (
    <div className="overflow-x-auto">
      <table className="min-w-full text-sm">
        <thead>
          <tr className="border-b border-[#333] text-left text-xs uppercase tracking-wider text-[#999]">
            {headers.map((h, i) => <th key={i} className="py-2 pr-4">{h}</th>)}
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} className="border-b border-[#222] last:border-0">
              {r.map((c, j) => <td key={j} className="py-2 pr-4 text-[#F5F5F5]">{c}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function DataQualityContent() {
  const { token } = useAuth();
  const [data, setData] = useState<Payload | null>(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/admin/data-quality', { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.json())
      .then((res: Payload) => {
        if (res.error) setErr(res.error);
        else setData(res);
      })
      .catch(e => setErr(e.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return (
    <AdminLayout title="Data Quality">
      <div className="flex items-center justify-center py-20">
        <div className="w-8 h-8 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" />
      </div>
    </AdminLayout>
  );

  if (err || !data) return (
    <AdminLayout title="Data Quality">
      <div className="text-[#FF3B3B]">Fout: {err || 'Geen data'}</div>
    </AdminLayout>
  );

  const s = data.summary;
  const tot = Number(s.total_sneakers) || 1;
  const pct = (n: number) => `${((Number(n) / tot) * 100).toFixed(1)}%`;

  return (
    <AdminLayout title="Data Quality">
      <div className="space-y-6">
        {/* Summary tiles */}
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
          <Tile label="Totaal sneakers" value={Number(s.total_sneakers).toLocaleString('nl-NL')} tone="ok" />
          <Tile label="Zonder model" value={Number(s.missing_model).toLocaleString('nl-NL')} tone={Number(s.missing_model) / tot > 0.1 ? 'bad' : 'warn'} hint={pct(s.missing_model) + ' van totaal'} />
          <Tile label="Zonder afbeelding" value={Number(s.missing_image).toLocaleString('nl-NL')} tone={Number(s.missing_image) / tot > 0.05 ? 'bad' : 'warn'} hint={pct(s.missing_image) + ' van totaal'} />
          <Tile label="Geen offers" value={Number(s.no_offers).toLocaleString('nl-NL')} tone={Number(s.no_offers) / tot > 0.1 ? 'bad' : 'warn'} hint={pct(s.no_offers) + ' (offline)'} />
          <Tile label="Prijs €0 offers" value={Number(s.zero_price_offers).toLocaleString('nl-NL')} tone={Number(s.zero_price_offers) > 50 ? 'bad' : 'warn'} />
          <Tile label="Dubbele EANs" value={Number(s.duplicate_ean_groups).toLocaleString('nl-NL')} tone={Number(s.duplicate_ean_groups) > 100 ? 'warn' : 'neutral'} hint="groepen" />
          <Tile label="Single-variant modellen" value={Number(s.singleton_models).toLocaleString('nl-NL')} tone="warn" hint="weinig SEO-waarde" />
          <Tile label="Stale (>30d)" value={Number(s.stale_products).toLocaleString('nl-NL')} tone={Number(s.stale_products) / tot > 0.2 ? 'bad' : 'warn'} />
        </div>

        {/* Missing model breakdown */}
        <Section
          title="Sneakers zonder model — per merk"
          description="Deze producten krijgen geen model-URL, geen AI-body en geen kleurvariant-link. Hoge impact op SEO."
        >
          <Table
            headers={['Merk', 'Aantal']}
            rows={data.missing_model.map(r => [r.brand || '(leeg)', Number(r.cnt).toLocaleString('nl-NL')])}
          />
        </Section>

        {/* Missing image */}
        <Section
          title="Sneakers zonder afbeelding — per merk"
          description="Worden uitgesloten van listings (image_url IS NULL)."
        >
          <Table
            headers={['Merk', 'Aantal']}
            rows={data.missing_image.map(r => [r.brand || '(leeg)', Number(r.cnt).toLocaleString('nl-NL')])}
          />
        </Section>

        {/* No offers */}
        <Section title="Sneakers zonder actieve offers (sample)" description="Recent geüpdatet maar geen in_stock offer meer. Kandidaten voor hide of verwijderen.">
          <Table
            headers={['ID', 'Merk', 'Naam', 'Slug']}
            rows={data.no_offers_sample.map(r => [r.id, r.brand || '-', r.name || '-', r.slug || '-'])}
          />
        </Section>

        {/* Zero price */}
        <Section title="Offers met €0 of null prijs (sample)" description="Feed-parsing issue of gratis-sample producten.">
          <Table
            headers={['ID', 'Merk', 'Naam', 'Bad offers']}
            rows={data.zero_price_sample.map(r => [r.id, r.brand || '-', r.name || '-', Number(r.bad_offers)])}
          />
        </Section>

        {/* Duplicate EANs */}
        <Section title="Dubbele EANs (sample)" description="Zelfde EAN-code, meerdere productrijen. Meestal merge-kandidaten.">
          <Table
            headers={['EAN', 'Aantal', 'Titels']}
            rows={data.duplicate_ean.map(r => [r.ean, Number(r.cnt), String(r.titles).slice(0, 120)])}
          />
        </Section>

        {/* Singleton models */}
        <Section title="Modellen met 1 variant" description="Model-pagina redirect direct door naar kleurpagina — weinig SEO-lift.">
          <Table
            headers={['Merk', 'Model', 'Varianten']}
            rows={data.singleton_models.map(r => [r.brand || '-', r.model || '-', Number(r.cnt)])}
          />
        </Section>

        {/* Stale by brand */}
        <Section title="Stale producten (>30d geen update) — per merk">
          <Table
            headers={['Merk', 'Aantal', 'Oudste update']}
            rows={data.stale_products_by_brand.map(r => [
              r.brand || '-',
              Number(r.cnt).toLocaleString('nl-NL'),
              r.oldest ? new Date(r.oldest).toLocaleDateString('nl-NL') : '-',
            ])}
          />
        </Section>

        {/* Tiny brands */}
        <Section title="Merken met <5 eligible producten" description="Meestal import-noise. Kandidaten voor merge of whitelist-filter.">
          <Table
            headers={['Merk', 'Aantal']}
            rows={data.tiny_brands.map(r => [r.brand || '-', Number(r.cnt)])}
          />
        </Section>
      </div>
    </AdminLayout>
  );
}

export default function DataQuality() {
  return <AuthProvider><AuthGuard><DataQualityContent /></AuthGuard></AuthProvider>;
}
