'use client';

import React, { useMemo } from 'react';
import type {
  MyAuditRow,
  RowStatus,
} from '@/lib/api/types/my-audits.types';
import { STATUS_CONFIG } from '@/lib/api/mappers/my-audits.mappers';

const MONTHS_SHORT = [
  'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
];

interface Props {
  audits: MyAuditRow[];
  statusFilter?: string;
  auditTypeFilter?: string;
  monthFilter?: string;
}

// ─────────────────────────────────────────────────────────────────────────
// Date helpers — STRING based, so counts never shift across timezones.
// schedule_date / updated_at arrive as 'YYYY-MM-DD' (optionally with a time
// suffix). We slice the parts we need instead of constructing Date objects.
// ─────────────────────────────────────────────────────────────────────────
const pad = (n: number) => String(n).padStart(2, '0');
const keyOf = (d: Date) =>
  `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
/** 'YYYY-MM-DD' from any date-ish string */
const dayKey = (s?: string | null) => (s ? String(s).slice(0, 10) : null);
/** 'YYYY-MM' from any date-ish string */
const monthKey = (s?: string | null) => (s ? String(s).slice(0, 7) : null);
/** 1–12 month number from 'YYYY-MM-DD' */
const monthNum = (s?: string | null) =>
  s ? Number(String(s).slice(5, 7)) : null;

// ─── KPI Card ────────────────────────────────────────────────────────────────
interface KpiCardProps {
  label: string;
  value: string | number;
  sub?: string;
  icon: React.ReactNode;
  gradientFrom: string;
  gradientTo: string;
}

function KpiCard({ label, value, sub, icon, gradientFrom, gradientTo }: KpiCardProps) {
  return (
    <div
      style={{
        flex: 1,
        minWidth: 0,
        borderRadius: 16,
        padding: '20px 22px',
        background: `linear-gradient(135deg, ${gradientFrom} 0%, ${gradientTo} 100%)`,
        display: 'flex',
        alignItems: 'center',
        gap: 16,
        boxShadow: '0 4px 20px rgba(15,23,42,0.14), 0 1px 4px rgba(15,23,42,0.08)',
        position: 'relative',
        overflow: 'hidden',
        cursor: 'default',
        transition: 'transform 0.15s ease, box-shadow 0.15s ease',
      }}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLDivElement).style.transform = 'translateY(-2px)';
        (e.currentTarget as HTMLDivElement).style.boxShadow = '0 8px 28px rgba(15,23,42,0.18)';
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLDivElement).style.transform = 'translateY(0)';
        (e.currentTarget as HTMLDivElement).style.boxShadow = '0 4px 20px rgba(15,23,42,0.14)';
      }}
    >
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'linear-gradient(135deg, rgba(255,255,255,0.08) 0%, transparent 60%)',
        borderRadius: 16,
      }} />
      <div style={{
        position: 'absolute', top: '-40%', right: '-10%', width: 140, height: 140,
        borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%)',
        pointerEvents: 'none',
      }} />

      <div style={{
        width: 48, height: 48, borderRadius: 12, flexShrink: 0,
        background: 'rgba(255,255,255,0.18)', backdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 2px 8px rgba(0,0,0,0.12), inset 0 1px 0 rgba(255,255,255,0.2)',
      }}>
        {icon}
      </div>

      <div style={{ flex: 1, minWidth: 0, position: 'relative', zIndex: 1 }}>
        <div style={{
          fontSize: 12.5, fontWeight: 500, color: 'rgba(255,255,255,0.72)',
          marginBottom: 5, letterSpacing: '0.1px',
        }}>
          {label}
        </div>
        <div style={{
          fontSize: '1.8rem', fontWeight: 800, color: '#ffffff', lineHeight: 1.05,
          letterSpacing: '-0.8px', fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
        }}>
          {value}
        </div>
        {sub && (
          <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.52)', marginTop: 4, fontWeight: 500 }}>
            {sub}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── SVG Icons ────────────────────────────────────────────────────────────────
const IconCalendar = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></svg>);
const IconFlame = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z" /></svg>);
const IconPlay = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3" /></svg>);
const IconCheck = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><polyline points="9 12 11 14 15 10" /></svg>);
const IconFlag = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" /><line x1="4" y1="22" x2="4" y2="15" /></svg>);
const IconEye = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>);
const IconRefresh = () => (<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 4 23 10 17 10" /><polyline points="1 20 1 14 7 14" /><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" /></svg>);

// ─── Main Component ───────────────────────────────────────────────────────────
export default function MyAuditsAnalytics({
  audits,
  statusFilter, // kept for API compatibility; no longer used to EXCLUDE rows
  auditTypeFilter,
  monthFilter,
}: Props) {
  // ── Exact-count philosophy ──────────────────────────────────────────────
  // Every metric below is computed from the FULL `audits` set, so the
  // dashboard always shows true totals. Table filters (status / type) do NOT
  // shrink these counts — otherwise "In Progress" would read 0 the moment you
  // filter the list to "Completed". `monthFilter` is used only to HIGHLIGHT a
  // bar in the monthly chart, never to drop rows.
  const data = useMemo(() => audits ?? [], [audits]);
  const total = data.length;

  // ── Time windows (string keys → timezone-proof) ─────────────────────────
  const now = new Date();
  const todayKey = keyOf(now);
  const curMonthKey = todayKey.slice(0, 7);

  const dow = now.getDay(); // 0 = Sun … 6 = Sat
  const monday = new Date(now);
  monday.setDate(now.getDate() - (dow === 0 ? 6 : dow - 1));
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  const monKey = keyOf(monday);
  const sunKey = keyOf(sunday);

  // ── Operational KPIs ────────────────────────────────────────────────────
  const todayCount = data.filter(
    (a) => dayKey(a.schedule?.schedule_date) === todayKey,
  ).length;

  const weekCount = data.filter((a) => {
    const k = dayKey(a.schedule?.schedule_date);
    return !!k && k >= monKey && k <= sunKey; // full Mon–Sun week
  }).length;

  const inProgressCount = data.filter((a) => a.status === 'IN_PROGRESS').length;

  const completedMonthCount = data.filter((a) => {
    if (a.status !== 'COMPLETED') return false;
    // Prefer updated_at; fall back to schedule_date if it's missing.
    const mk =
      monthKey((a as any).updated_at) ?? monthKey(a.schedule?.schedule_date);
    return mk === curMonthKey;
  }).length;

  // ── Category counts (true totals) ───────────────────────────────────────
  const initialCount = data.filter((a) => a.audit_type === 'INITIAL').length;
  const surveillanceCount = data.filter((a) => a.audit_type === 'SURVEILLANCE').length;
  const recertCount = data.filter((a) => a.audit_type === 'RECERTIFICATION').length;

  // ── Completion ──────────────────────────────────────────────────────────
  const completed = data.filter((a) => a.status === 'COMPLETED').length;
  const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;

  // ── By status ───────────────────────────────────────────────────────────
  const byStatus = (Object.keys(STATUS_CONFIG) as RowStatus[]).map((key) => ({
    key,
    label: STATUS_CONFIG[key].label,
    color: STATUS_CONFIG[key].dot,
    count: data.filter((a) => a.status === key).length,
  }));

  // ── By standard ─────────────────────────────────────────────────────────
  const standardsMap = new Map<string, number>();
  data.forEach((a) => {
    (a.standards ?? []).forEach((s) => {
      standardsMap.set(s.name, (standardsMap.get(s.name) ?? 0) + 1);
    });
  });
  const byStandard = Array.from(standardsMap.entries())
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 6);
  const standardColors = ['#7F77DD', '#5DCAA5', '#EF9F27', '#E24B4A', '#0891b2', '#a855f7'];

  // ── Monthly chart (timezone-proof month extraction) ─────────────────────
  const byMonth = useMemo(() => {
    const map: Record<string, number> = {};
    MONTHS_SHORT.forEach((m) => (map[m] = 0));
    data.forEach((a) => {
      const mn = monthNum(a.schedule?.schedule_date);
      if (mn && mn >= 1 && mn <= 12) {
        const m = MONTHS_SHORT[mn - 1];
        map[m] = (map[m] ?? 0) + 1;
      }
    });
    return MONTHS_SHORT.map((m) => ({ month: m, count: map[m] }));
  }, [data]);
  const maxMonth = Math.max(...byMonth.map((b) => b.count), 1);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginBottom: 20 }}>
      {/* ── ROW 1: Main KPIs ─────────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
        <KpiCard label="Today" value={todayCount.toLocaleString()} sub="audits scheduled" icon={<IconFlame />} gradientFrom="#92400e" gradientTo="#f59e0b" />
        <KpiCard label="This Week" value={weekCount.toLocaleString()} sub="Mon–Sun this week" icon={<IconCalendar />} gradientFrom="#1e3a8a" gradientTo="#2563eb" />
        <KpiCard label="In Progress" value={inProgressCount.toLocaleString()} sub="action required" icon={<IconPlay />} gradientFrom="#4c1d95" gradientTo="#7c3aed" />
        <KpiCard label="Completed (Month)" value={completedMonthCount.toLocaleString()} sub="closed this month" icon={<IconCheck />} gradientFrom="#065f46" gradientTo="#10b981" />
      </div>

      {/* ── ROW 2: Category KPIs ─────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
        <KpiCard label="Initial" value={initialCount.toLocaleString()} sub="first-time certifications" icon={<IconFlag />} gradientFrom="#3f6212" gradientTo="#65a30d" />
        <KpiCard label="Surveillance" value={surveillanceCount.toLocaleString()} sub="periodic follow-ups" icon={<IconEye />} gradientFrom="#854d0e" gradientTo="#d97706" />
        <KpiCard label="Re-Certification" value={recertCount.toLocaleString()} sub="3-year renewals" icon={<IconRefresh />} gradientFrom="#5b21b6" gradientTo="#a855f7" />
      </div>

      {/* ── ROW 3: Status + Standards ─────────────────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 12, padding: 18 }}>
          <h3 style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 14 }}>
            Status Distribution
            <span style={{ marginLeft: 8, fontSize: 11, color: '#9ca3af', fontWeight: 400 }}>
              ({total} audits)
            </span>
          </h3>
          {byStatus.map((s) => (
            <div key={s.key} style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                <span style={{ color: '#374151' }}>{s.label}</span>
                <span style={{ color: s.color, fontWeight: 700 }}>
                  {s.count}
                  <span style={{ color: '#9ca3af', fontWeight: 400, marginLeft: 4 }}>
                    ({total > 0 ? Math.round((s.count / total) * 100) : 0}%)
                  </span>
                </span>
              </div>
              <div style={{ height: 5, borderRadius: 3, backgroundColor: '#f3f4f6' }}>
                <div style={{
                  height: '100%', borderRadius: 3, backgroundColor: s.color,
                  width: `${total ? (s.count / total) * 100 : 0}%`, transition: 'width 0.4s',
                }} />
              </div>
            </div>
          ))}
        </div>

        <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 12, padding: 18 }}>
          <h3 style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 14 }}>
            By Standard
            <span style={{ marginLeft: 8, fontSize: 11, color: '#9ca3af', fontWeight: 400 }}>
              (top {byStandard.length})
            </span>
          </h3>
          {byStandard.length === 0 ? (
            <p style={{ margin: '20px 0', fontSize: 12, color: '#9ca3af', textAlign: 'center' }}>
              No standards data yet
            </p>
          ) : (
            byStandard.map((s, i) => {
              const max = byStandard[0].count;
              return (
                <div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: '50%',
                    backgroundColor: `${standardColors[i % standardColors.length]}20`,
                    color: standardColors[i % standardColors.length],
                    fontSize: 10, fontWeight: 700, display: 'flex',
                    alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    {i + 1}
                  </span>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                      <span style={{ color: '#374151', fontWeight: 500 }}>{s.name}</span>
                      <span style={{ color: standardColors[i % standardColors.length], fontWeight: 700 }}>
                        {s.count}
                      </span>
                    </div>
                    <div style={{ height: 4, borderRadius: 2, backgroundColor: '#f3f4f6' }}>
                      <div style={{
                        height: '100%', borderRadius: 2,
                        backgroundColor: standardColors[i % standardColors.length],
                        width: `${(s.count / max) * 100}%`, transition: 'width 0.4s',
                      }} />
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>

      {/* ── ROW 4: Monthly chart ─────────────────────────────────────────── */}
      <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 12, padding: 18 }}>
        <h3 style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 16 }}>
          Audits per Month
          <span style={{ marginLeft: 8, fontSize: 11, color: '#9ca3af', fontWeight: 400 }}>
            (total: {total})
          </span>
        </h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 6, alignItems: 'flex-end', height: 90 }}>
          {byMonth.map((b) => {
            const isActive =
              !!monthFilter &&
              monthFilter !== 'all' &&
              String(MONTHS_SHORT.indexOf(b.month) + 1).padStart(2, '0') === monthFilter;
            return (
              <div key={b.month} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, height: '100%' }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', width: '100%' }}>
                  <div title={`${b.month}: ${b.count}`} style={{
                    width: '100%',
                    backgroundColor: isActive ? '#0f766e' : b.count > 0 ? '#14b8a6' : '#f0fdfa',
                    borderRadius: '4px 4px 0 0',
                    height: `${(b.count / maxMonth) * 100}%`,
                    minHeight: b.count > 0 ? 4 : 0,
                    transition: 'height 0.4s, background-color 0.2s',
                    position: 'relative',
                  }}>
                    {b.count > 0 && (
                      <span style={{
                        position: 'absolute', top: -18, left: '50%', transform: 'translateX(-50%)',
                        fontSize: 9, color: isActive ? '#0f766e' : '#6b7280', fontWeight: 700, whiteSpace: 'nowrap',
                      }}>
                        {b.count}
                      </span>
                    )}
                  </div>
                </div>
                <span style={{ fontSize: 9, color: isActive ? '#0f766e' : '#9ca3af', fontWeight: isActive ? 700 : 500 }}>
                  {b.month}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      {/* ── ROW 5: Completion rate ───────────────────────────────────────── */}
      <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 12, padding: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <h3 style={{ fontSize: 13, fontWeight: 700, color: '#374151', margin: 0 }}>
            Completion Rate
          </h3>
          <span style={{ fontSize: 28, fontWeight: 800, color: '#065f46', fontFamily: "'JetBrains Mono', monospace" }}>
            {completionRate}%
          </span>
        </div>
        <div style={{ height: 10, background: '#f3f4f6', borderRadius: 5, overflow: 'hidden', marginBottom: 6 }}>
          <div style={{
            height: '100%', width: `${completionRate}%`,
            background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
            borderRadius: 5, transition: 'width 0.6s ease',
          }} />
        </div>
        <p style={{ margin: 0, fontSize: 11, color: '#9ca3af' }}>
          {completed} of {total} audits closed
        </p>
      </div>
    </div>
  );
}