'use client';

import React, { useMemo } from 'react';
import { EnterpriseLoader } from '../../../../components/loader/loader';
import type { ClientRow } from '@/lib/api/types/clients.types';
import { parseStandards } from '@/lib/api/mappers/clients.mappers';
import { TOKENS, fmt, pct } from './design-tokens';

interface Props {
  rows: ClientRow[];
  loading: boolean;
}

function StatCard({
  label,
  value,
  sub,
  color,
}: {
  label: string;
  value: string;
  sub?: string;
  color: string;
}) {
  return (
    <div
      style={{
        padding: '14px 16px',
        background: '#fff',
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        borderTop: `3px solid ${color}`,
      }}
    >
      <div
        style={{
          fontSize: 10.5,
          fontWeight: 700,
          color: TOKENS.ink4,
          textTransform: 'uppercase',
          letterSpacing: '0.05em',
        }}
      >
        {label}
      </div>
      <div style={{ fontSize: 24, fontWeight: 700, color: TOKENS.ink, marginTop: 4 }}>
        {value}
      </div>
      {sub && (
        <div style={{ fontSize: 11, color: TOKENS.ink4, marginTop: 2 }}>{sub}</div>
      )}
    </div>
  );
}

function BarList({
  title,
  items,
  total,
  color,
}: {
  title: string;
  items: { label: string; count: number }[];
  total: number;
  color: string;
}) {
  return (
    <div
      style={{
        padding: '14px 16px',
        background: '#fff',
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
      }}
    >
      <div
        style={{
          fontSize: 11,
          fontWeight: 700,
          color: TOKENS.ink3,
          textTransform: 'uppercase',
          letterSpacing: '0.05em',
          marginBottom: 10,
        }}
      >
        {title}
      </div>
      {items.length === 0 && (
        <div style={{ fontSize: 12, color: TOKENS.ink5 }}>No data</div>
      )}
      {items.map((it) => (
        <div key={it.label} style={{ marginBottom: 8 }}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              fontSize: 12,
              marginBottom: 3,
            }}
          >
            <span
              style={{
                color: TOKENS.ink2,
                fontWeight: 600,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: '70%',
              }}
              title={it.label}
            >
              {it.label}
            </span>
            <span style={{ color: TOKENS.ink4, fontWeight: 700 }}>
              {fmt(it.count)} · {pct(it.count, total)}
            </span>
          </div>
          <div
            style={{
              height: 6,
              background: TOKENS.line2,
              borderRadius: 99,
              overflow: 'hidden',
            }}
          >
            <div
              style={{
                width: pct(it.count, total),
                height: '100%',
                background: color,
                borderRadius: 99,
              }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

export default function ClientsAnalyticsInline({ rows, loading }: Props) {
  const stats = useMemo(() => {
    const total = rows.length;
    const clients = rows.filter((r) => r.client_type === 'Client').length;
    const surveillance = total - clients;
    const qrs = rows.filter((r) => r.source === 'QRS').length;
    const tqs = total - qrs;
    const active = rows.filter((r) => Number(r.status) === 1).length;

    const bySector = new Map<string, number>();
    for (const r of rows) {
      const key = (r.company_sector || 'Unspecified').trim() || 'Unspecified';
      bySector.set(key, (bySector.get(key) || 0) + 1);
    }

    const byStandard = new Map<string, number>();
    for (const r of rows) {
      for (const s of parseStandards(r.standard_name)) {
        byStandard.set(s, (byStandard.get(s) || 0) + 1);
      }
    }

    const top = (m: Map<string, number>, n: number) =>
      Array.from(m.entries())
        .map(([label, count]) => ({ label, count }))
        .sort((a, b) => b.count - a.count)
        .slice(0, n);

    return {
      total,
      clients,
      surveillance,
      qrs,
      tqs,
      active,
      sectors: top(bySector, 6),
      standards: top(byStandard, 6),
    };
  }, [rows]);

  if (loading) {
    return (
      <div
        style={{
          padding: 40,
          textAlign: 'center',
          background: '#fff',
          border: `1px solid ${TOKENS.line}`,
          borderRadius: TOKENS.rMd,
          marginBottom: 12,
        }}
      >
        <EnterpriseLoader />
      </div>
    );
  }

  return (
    <div style={{ marginBottom: 14 }}>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))',
          gap: 10,
          marginBottom: 10,
        }}
      >
        <StatCard label="Total records" value={fmt(stats.total)} color={TOKENS.brand} />
        <StatCard
          label="Clients"
          value={fmt(stats.clients)}
          sub={pct(stats.clients, stats.total)}
          color={TOKENS.client}
        />
        <StatCard
          label="Surveillance"
          value={fmt(stats.surveillance)}
          sub={pct(stats.surveillance, stats.total)}
          color={TOKENS.surveillance}
        />
        <StatCard
          label="QRS"
          value={fmt(stats.qrs)}
          sub={pct(stats.qrs, stats.total)}
          color={TOKENS.qrs}
        />
        <StatCard
          label="TQS"
          value={fmt(stats.tqs)}
          sub={pct(stats.tqs, stats.total)}
          color={TOKENS.tqs}
        />
        <StatCard
          label="Active"
          value={fmt(stats.active)}
          sub={pct(stats.active, stats.total)}
          color={TOKENS.success}
        />
      </div>

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
          gap: 10,
        }}
      >
        <BarList
          title="Top sectors"
          items={stats.sectors}
          total={stats.total}
          color={TOKENS.brand}
        />
        <BarList
          title="Top standards"
          items={stats.standards}
          total={stats.total}
          color={TOKENS.qrs}
        />
      </div>
    </div>
  );
}
