'use client';

import React, { useMemo } from 'react';
import type { InquiryRow } from '@/lib/api/types/inquiry.types';
import { STATUS_CONFIG, TYPE_CONFIG } from '@/lib/api/mappers/inquiry.mappers';

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

interface Props {
  inquiries:    InquiryRow[];
  statusFilter?: string;
  typeFilter?:   string;
  monthFilter?:  string;
  certBodyFilter?: string;
  auditStageFilter?: string;
}

// ─── 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 IconClipboard = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>
    <rect x="8" y="2" width="8" height="4" rx="1" ry="1"/>
  </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 IconClock = () => (
  <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="12 6 12 12 16 14"/>
  </svg>
);
const IconAlert = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
    <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
  </svg>
);

// ─── Main Component ───────────────────────────────────────────────────────────
export default function InquiryAnalytics({ inquiries, statusFilter, typeFilter, monthFilter }: Props) {

  // Apply filters to the dataset
  const filtered = useMemo(() => {
    return inquiries.filter(inq => {
      if (statusFilter && statusFilter !== 'all' && inq.status !== statusFilter) return false;
      if (typeFilter   && typeFilter   !== 'all' && inq.inquiry_type !== typeFilter) return false;
      if (monthFilter  && monthFilter  !== 'all') {
        if (!inq.created_at) return false;
        const m = String(new Date(inq.created_at).getMonth() + 1).padStart(2, '0');
        if (m !== monthFilter) return false;
      }
      return true;
    });
  }, [inquiries, statusFilter, typeFilter, monthFilter]);

  // ── KPIs ──────────────────────────────────────────────────────────────────
  const total       = filtered.length;
  const pending     = filtered.filter(i => i.status === 'PENDING').length;
  const draftReady  = filtered.filter(i => i.status === 'DRAFT_READY').length;
  const changes     = filtered.filter(i => i.status === 'CHANGES_REQUESTED').length;
  const confirmed   = filtered.filter(i => i.status === 'CLIENT_CONFIRMED').length;
  const issued      = filtered.filter(i => i.status === 'FINAL_ISSUED').length;

  // By status
  const byStatus = Object.entries(STATUS_CONFIG).map(([key, cfg]) => ({
    key, label: cfg.label, color: cfg.dot,
    count: filtered.filter(i => i.status === key).length,
  }));

  // By type
  const byType = Object.entries(TYPE_CONFIG).map(([key, cfg]) => ({
    key, label: cfg.label, color: cfg.color,
    count: filtered.filter(i => i.inquiry_type === key).length,
  }));

  // Monthly
  const byMonth = useMemo(() => {
    const map: Record<string, number> = {};
    MONTHS_SHORT.forEach(m => (map[m] = 0));
    filtered.forEach(inq => {
      if (inq.created_at) {
        const m = MONTHS_SHORT[new Date(inq.created_at).getMonth()];
        map[m] = (map[m] ?? 0) + 1;
      }
    });
    return MONTHS_SHORT.map(m => ({ month: m, count: map[m] }));
  }, [filtered]);
  const maxMonth = Math.max(...byMonth.map(b => b.count), 1);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginBottom: 20 }}>

      {/* ── KPI Cards ─────────────────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
        <KpiCard label="Total Inquiries"     value={total.toLocaleString()}    sub="all inquiries"         icon={<IconClipboard />} gradientFrom="#1e3a8a"  gradientTo="#2563eb" />
        <KpiCard label="Pending"             value={pending.toLocaleString()}  sub="awaiting scheme"       icon={<IconClock />}     gradientFrom="#92400e"  gradientTo="#f59e0b" />
        <KpiCard label="Draft Ready"         value={draftReady.toLocaleString()} sub="awaiting approval"   icon={<IconCheck />}     gradientFrom="#4c1d95"  gradientTo="#7c3aed" />
        <KpiCard label="Changes Requested"   value={changes.toLocaleString()}  sub="needs revision"        icon={<IconAlert />}     gradientFrom="#991b1b"  gradientTo="#ef4444" />
        <KpiCard label="Final Issued"        value={issued.toLocaleString()}   sub="completed"             icon={<IconCheck />}     gradientFrom="#065f46"  gradientTo="#10b981" />
      </div>

      {/* ── Status + Type breakdown ────────────────────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>

        {/* Status distribution */}
        <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 }}>({filtered.length} inquiries)</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>

        {/* Type distribution */}
        <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 12, padding: 18 }}>
          <h3 style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 14 }}>
            Inquiry Type Breakdown
          </h3>
          {byType.map((t, i) => (
            <div key={t.key} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <span style={{ width: 22, height: 22, borderRadius: '50%', backgroundColor: '#f0fdfa', color: '#0f766e', 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 }}>{t.label}</span>
                  <span style={{ color: t.color, fontWeight: 700 }}>{t.count}</span>
                </div>
                <div style={{ height: 4, borderRadius: 2, backgroundColor: '#f3f4f6' }}>
                  <div style={{ height: '100%', borderRadius: 2, backgroundColor: t.color, width: `${total ? (t.count / total) * 100 : 0}%`, transition: 'width 0.4s' }} />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Monthly chart ────────────────────────────────────────────────── */}
      <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 12, padding: 18 }}>
        <h3 style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 16 }}>
          Monthly Inquiries
          <span style={{ marginLeft: 8, fontSize: 11, color: '#9ca3af', fontWeight: 400 }}>(total: {filtered.length})</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>
    </div>
  );
}
