'use client';

import React, { useMemo } from 'react';
import { FiBarChart2, FiAlertCircle, FiCheckCircle, FiClock, FiTrendingUp } from 'react-icons/fi';
import type { PreviousNcRow } from '@/lib/api/types/previous-nc.types';

interface Props {
  rows: PreviousNcRow[];
  loading?: boolean;
}

export default function PreviousNcAnalyticsInline({ rows, loading }: Props) {
  const stats = useMemo(() => {
    const total = rows.length;
    const open = rows.filter((r) => r.status === 'open').length;
    const closed = rows.filter((r) => r.status === 'closed').length;

    const bySource = {
      QRS: rows.filter((r) => r.source === 'QRS').length,
      TQS: rows.filter((r) => r.source === 'TQS').length,
    };

    const byNcType = rows.reduce<Record<string, number>>((acc, r) => {
      const k = r.nc_type || 'Unknown';
      acc[k] = (acc[k] || 0) + 1;
      return acc;

      
    }, {});

    const byAuditType = rows.reduce<Record<string, number>>((acc, r) => {
      const k = r.audit_type || 'Unknown';
      acc[k] = (acc[k] || 0) + 1;
      return acc;
    }, {});

    const topCompanies = Object.entries(
      rows.reduce<Record<string, number>>((acc, r) => {
        const k = r.company_name || 'Unknown';
        acc[k] = (acc[k] || 0) + 1;
        return acc;
      }, {}),
    )
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5);

    return { total, open, closed, bySource, byNcType, byAuditType, topCompanies };
  }, [rows]);

  if (loading) {
    return (
      <div style={panelStyle()}>
        <div style={{ padding: 40, textAlign: 'center', color: '#64748b', fontSize: 13 }}>
          <div
            style={{
              width: 28,
              height: 28,
              border: '3px solid #e5e7eb',
              borderTopColor: '#7c3aed',
              borderRadius: '50%',
              margin: '0 auto 10px',
              animation: 'pnc-an-spin 0.7s linear infinite',
            }}
          />
          Loading analytics…
          <style>{`@keyframes pnc-an-spin{to{transform:rotate(360deg)}}`}</style>
        </div>
      </div>
    );
  }

  return (
    <div style={panelStyle()}>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          padding: '14px 18px',
          background: 'linear-gradient(135deg, #4c1d95 0%, #7c3aed 100%)',
          color: '#fff',
        }}
      >
        <FiBarChart2 size={18} />
        <strong style={{ fontSize: 14 }}>Analytics</strong>
        <span style={{ fontSize: 12, opacity: 0.85, marginLeft: 'auto' }}>
          {stats.total.toLocaleString()} NCs analyzed
        </span>
      </div>

      <div style={{ padding: 18 }}>
        {/* Top KPI cards */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
            gap: 12,
            marginBottom: 18,
          }}
        >
          <KpiCard
            icon={<FiTrendingUp />}
            label="Total NCs"
            value={stats.total}
            color="#7c3aed"
          />
          <KpiCard
            icon={<FiAlertCircle />}
            label="Open"
            value={stats.open}
            color="#dc2626"
            sub={`${pct(stats.open, stats.total)}%`}
          />
          <KpiCard
            icon={<FiCheckCircle />}
            label="Closed"
            value={stats.closed}
            color="#16a34a"
            sub={`${pct(stats.closed, stats.total)}%`}
          />
          <KpiCard
            icon={<FiClock />}
            label="QRS / TQS"
            value={`${stats.bySource.QRS} / ${stats.bySource.TQS}`}
            color="#0f766e"
          />
        </div>

        {/* Two-column section */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
            gap: 14,
          }}
        >
          {/* NC Type breakdown */}
          <BreakdownPanel
            title="By NC Type"
            entries={Object.entries(stats.byNcType).sort((a, b) => b[1] - a[1])}
            total={stats.total}
            colorFor={(k) =>
              k.toLowerCase().includes('major')
                ? '#dc2626'
                : k.toLowerCase().includes('minor')
                  ? '#d97706'
                  : '#2563eb'
            }
          />

          {/* Audit Type breakdown */}
          <BreakdownPanel
            title="By Audit Type"
            entries={Object.entries(stats.byAuditType).sort((a, b) => b[1] - a[1])}
            total={stats.total}
            colorFor={() => '#0f766e'}
          />

          {/* Top companies */}
          <div
            style={{
              background: '#fafbfc',
              border: '1px solid #e5e7eb',
              borderRadius: 8,
              padding: 14,
            }}
          >
            <div
              style={{
                fontSize: 10,
                fontWeight: 800,
                color: '#475569',
                textTransform: 'uppercase',
                letterSpacing: '0.08em',
                marginBottom: 10,
              }}
            >
              Top 5 Companies
            </div>
            {stats.topCompanies.length === 0 ? (
              <div style={{ fontSize: 12, color: '#94a3b8', fontStyle: 'italic' }}>
                No data
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {stats.topCompanies.map(([name, count], i) => (
                  <div
                    key={name}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 8,
                      fontSize: 12,
                    }}
                  >
                    <span
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: 22,
                        height: 22,
                        background: '#7c3aed',
                        color: '#fff',
                        fontSize: 10,
                        fontWeight: 800,
                        borderRadius: '50%',
                        flexShrink: 0,
                      }}
                    >
                      {i + 1}
                    </span>
                    <span
                      style={{
                        flex: 1,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        color: '#1f2937',
                        fontWeight: 500,
                      }}
                      title={name}
                    >
                      {name}
                    </span>
                    <span style={{ fontWeight: 700, color: '#0f766e' }}>{count}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Sub-components ─────────────────────────────────────────────────

function KpiCard({
  icon,
  label,
  value,
  color,
  sub,
}: {
  icon: React.ReactNode;
  label: string;
  value: number | string;
  color: string;
  sub?: string;
}) {
  return (
    <div
      style={{
        background: '#fff',
        border: '1px solid #e5e7eb',
        borderLeft: `3px solid ${color}`,
        borderRadius: 8,
        padding: '12px 14px',
      }}
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 6,
          fontSize: 10,
          fontWeight: 700,
          color: '#94a3b8',
          textTransform: 'uppercase',
          letterSpacing: '0.06em',
          marginBottom: 6,
        }}
      >
        <span style={{ color }}>{icon}</span>
        {label}
      </div>
      <div style={{ fontSize: 22, fontWeight: 800, color: '#111827' }}>
        {typeof value === 'number' ? value.toLocaleString() : value}
      </div>
      {sub && (
        <div style={{ fontSize: 11, color: '#64748b', fontWeight: 600, marginTop: 2 }}>
          {sub}
        </div>
      )}
    </div>
  );
}

function BreakdownPanel({
  title,
  entries,
  total,
  colorFor,
}: {
  title: string;
  entries: [string, number][];
  total: number;
  colorFor: (key: string) => string;
}) {
  return (
    <div
      style={{
        background: '#fafbfc',
        border: '1px solid #e5e7eb',
        borderRadius: 8,
        padding: 14,
      }}
    >
      <div
        style={{
          fontSize: 10,
          fontWeight: 800,
          color: '#475569',
          textTransform: 'uppercase',
          letterSpacing: '0.08em',
          marginBottom: 10,
        }}
      >
        {title}
      </div>
      {entries.length === 0 ? (
        <div style={{ fontSize: 12, color: '#94a3b8', fontStyle: 'italic' }}>
          No data
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {entries.map(([key, count]) => {
            const color = colorFor(key);
            const percentage = total > 0 ? (count / total) * 100 : 0;
            return (
              <div key={key}>
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    fontSize: 12,
                    marginBottom: 3,
                  }}
                >
                  <span
                    style={{
                      color: '#1f2937',
                      fontWeight: 500,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      maxWidth: '70%',
                    }}
                    title={key}
                  >
                    {key}
                  </span>
                  <span style={{ fontWeight: 700, color }}>
                    {count} ({percentage.toFixed(0)}%)
                  </span>
                </div>
                <div
                  style={{
                    height: 6,
                    background: '#e5e7eb',
                    borderRadius: 3,
                    overflow: 'hidden',
                  }}
                >
                  <div
                    style={{
                      height: '100%',
                      width: `${percentage}%`,
                      background: color,
                      borderRadius: 3,
                      transition: 'width 0.3s',
                    }}
                  />
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function pct(n: number, total: number): string {
  if (total === 0) return '0';
  return ((n / total) * 100).toFixed(0);
}

function panelStyle(): React.CSSProperties {
  return {
    background: '#fff',
    border: '1px solid #e5e7eb',
    borderRadius: 10,
    marginBottom: 14,
    overflow: 'hidden',
    boxShadow: '0 1px 3px rgba(15,23,42,0.04)',
  };
}
