'use client';
import { useState } from 'react';
import { trainingRecords, budgetData, trainingEvaluations } from './trainingModuleData';
import { initialPrograms } from './trainingData';
import {
  PieChart, Pie, Cell, Tooltip, ResponsiveContainer,
  BarChart, Bar, XAxis, YAxis, Legend,
} from 'recharts';

const COLORS = ['#b22698', '#3b82f6', '#f59e0b', '#10b981', '#8b5cf6', '#ef4444'];

const REPORTS = [
  { id: 'completion', title: 'Training Completion Report', desc: 'Completion rates by department and program', icon: 'ri-checkbox-circle-line', color: 'text-green-600 bg-green-50' },
  { id: 'certificate', title: 'Certificate Compliance Report', desc: 'Certificate upload status per employee and course', icon: 'ri-award-line', color: 'text-purple-600 bg-purple-50' },
  { id: 'evaluation', title: 'Evaluation Summary Report', desc: 'Kirkpatrick L1–L4 aggregated results', icon: 'ri-survey-line', color: 'text-blue-600 bg-blue-50' },
  { id: 'expiry', title: 'Expiring Certificates Report', desc: 'Certificates expiring within 30/60/90 days', icon: 'ri-alarm-warning-line', color: 'text-red-600 bg-red-50' },
  { id: 'cost', title: 'Cost Analysis Report', desc: 'Budget vs actual spend per department', icon: 'ri-money-dollar-circle-line', color: 'text-orange-600 bg-orange-50' },
];

export default function TrainingReportsTab() {
  const [exportFormat, setExportFormat] = useState<Record<string, 'excel' | 'pdf'>>({});
  const [generating, setGenerating] = useState<string | null>(null);
  const [toast, setToast] = useState('');

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const handleExport = (reportId: string) => {
    setGenerating(reportId);
    setTimeout(() => {
      setGenerating(null);
      const fmt = exportFormat[reportId] || 'excel';
      showToast(`${REPORTS.find(r => r.id === reportId)?.title} exported as ${fmt.toUpperCase()}`);
    }, 1200);
  };

  const handleDownload = (reportId: string) => {
    setGenerating(reportId);
    setTimeout(() => {
      setGenerating(null);
      const today = new Date().toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' });
      const title = REPORTS.find(r => r.id === reportId)?.title || 'Training Report';
      const rows: string[][] = [['UWEZO FUND OVERSIGHT BOARD — ' + title, 'Generated: ' + today], []];
      if (reportId === 'completion') {
        rows.push(['Department', 'Programs Completed', 'Programs Ongoing', 'Programs Upcoming']);
        depts.forEach(d => {
          const completed = initialPrograms.filter(p => p.dept === d && p.status === 'Completed').length;
          const ongoing = initialPrograms.filter(p => p.dept === d && p.status === 'Ongoing').length;
          const upcoming = initialPrograms.filter(p => p.dept === d && p.status === 'Upcoming').length;
          rows.push([d, String(completed), String(ongoing), String(upcoming)]);
        });
      } else if (reportId === 'certificate') {
        rows.push(['Employee', 'Department', 'Course', 'Certificate Status', 'Completion Date']);
        trainingRecords.forEach(r => rows.push([r.employeeName, r.dept, r.courseName, r.certStatus, r.completionDate]));
      } else if (reportId === 'evaluation') {
        rows.push(['Course', 'Employee', 'L1 Rating', 'L2 Gain', 'L3 Status', 'L4 Improved']);
        trainingEvaluations.forEach(e => rows.push([e.programTitle, e.employeeName, String(e.l1Rating) + '/5', '+' + String(e.l2PostScore - e.l2PreScore) + '%', e.l3Status, e.l4MetricsImproved ? 'Yes' : 'No']));
      } else if (reportId === 'expiry') {
        rows.push(['Employee', 'Department', 'Course', 'Days to Expiry', 'Expiry Date']);
        trainingRecords.filter(r => r.daysToExpiry !== undefined && r.daysToExpiry <= 90).forEach(r => rows.push([r.employeeName, r.dept, r.courseName, String(r.daysToExpiry), r.expiryDate || 'N/A']));
      } else if (reportId === 'cost') {
        rows.push(['Department', 'Planned Budget (KES)', 'Actual Spend (KES)', 'Variance']);
        budgetData.forEach(b => rows.push([b.dept, String(b.planned), String(b.actual), String(b.planned - b.actual)]));
      }
      const csv = rows.map(row => row.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${reportId}-report-${new Date().toISOString().split('T')[0]}.csv`;
      a.click();
      URL.revokeObjectURL(url);
      showToast(`${title} downloaded as CSV`);
    }, 800);
  };

  const depts = Array.from(new Set(trainingRecords.map(r => r.dept)));

  const hoursByDept = depts.map(d => ({
    dept: d.replace('Corporate Communication', 'Corp. Comm').replace('Monitoring & Evaluation', 'M&E'),
    hours: trainingRecords.filter(r => r.dept === d).reduce((s, r) => s + r.hoursAwarded, 0),
  }));

  const certComplianceData = depts.map(d => ({
    dept: d.replace('Corporate Communication', 'Corp. Comm').replace('Monitoring & Evaluation', 'M&E'),
    submitted: trainingRecords.filter(r => r.dept === d && r.certStatus === 'Submitted').length,
    pending: trainingRecords.filter(r => r.dept === d && r.certStatus === 'Pending').length,
    missing: trainingRecords.filter(r => r.dept === d && r.certStatus === 'Missing').length,
  }));

  const pieData = depts.map(d => ({
    name: d.replace('Corporate Communication', 'Corp. Comm').replace('Monitoring & Evaluation', 'M&E'),
    value: trainingRecords.filter(r => r.dept === d).reduce((s, r) => s + r.hoursAwarded, 0),
  }));

  const avgL1 = (trainingEvaluations.reduce((s, e) => s + e.l1Rating, 0) / trainingEvaluations.length).toFixed(1);
  const avgGain = Math.round(trainingEvaluations.reduce((s, e) => s + (e.l2PostScore - e.l2PreScore), 0) / trainingEvaluations.length);
  const l3Applied = trainingEvaluations.filter(e => e.l3Status === 'Completed' && e.l3ManagerRating >= 4).length;
  const l4Improved = trainingEvaluations.filter(e => e.l4MetricsImproved).length;

  const totalSubmitted = trainingRecords.filter(r => r.certStatus === 'Submitted').length;
  const totalMissing = trainingRecords.filter(r => r.certStatus === 'Missing').length;
  const totalPending = trainingRecords.filter(r => r.certStatus === 'Pending').length;
  const complianceRate = Math.round((totalSubmitted / trainingRecords.length) * 100);

  return (
    <div className="space-y-6">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium">{toast}</div>
      )}

      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
        <h3 className="font-semibold text-gray-800 mb-4">Pre-Built Reports</h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Report</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Description</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Format</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Action</th>
              </tr>
            </thead>
            <tbody>
              {REPORTS.map(r => (
                <tr key={r.id} className="border-b border-gray-50 hover:bg-gray-50">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${r.color}`}>
                        <i className={`${r.icon} text-sm`}></i>
                      </div>
                      <span className="text-sm font-semibold text-gray-800">{r.title}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-500">{r.desc}</td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1 bg-gray-100 rounded-lg p-0.5 w-fit">
                      {(['excel', 'pdf'] as const).map(fmt => (
                        <button key={fmt} onClick={() => setExportFormat(p => ({ ...p, [r.id]: fmt }))}
                          className={`px-3 py-1 rounded-md text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${(exportFormat[r.id] || 'excel') === fmt ? 'bg-white shadow text-gray-800' : 'text-gray-500'}`}>
                          {fmt.toUpperCase()}
                        </button>
                      ))}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <button onClick={() => handleDownload(r.id)}
                      disabled={generating === r.id}
                      className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg cursor-pointer font-medium text-white whitespace-nowrap hover:opacity-80 disabled:opacity-60"
                      style={{ background: '#b22698' }}>
                      {generating === r.id ? (
                        <><i className="ri-loader-4-line animate-spin"></i> Generating...</>
                      ) : (
                        <><i className="ri-download-line"></i> Download</>
                      )}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Certificate Compliance', value: `${complianceRate}%`, sub: `${totalSubmitted}/${trainingRecords.length} submitted`, color: 'text-green-600 bg-green-50', icon: 'ri-award-line' },
          { label: 'Missing Certificates', value: totalMissing, sub: 'Overdue >7 days', color: 'text-red-600 bg-red-50', icon: 'ri-close-circle-line' },
          { label: 'Pending Upload', value: totalPending, sub: 'Within 7-day window', color: 'text-yellow-600 bg-yellow-50', icon: 'ri-time-line' },
          { label: 'Avg. Satisfaction', value: `${avgL1}/5`, sub: 'L1 Reaction score', color: 'text-blue-600 bg-blue-50', icon: 'ri-emotion-happy-line' },
        ].map(({ label, value, sub, color, icon }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-xl ${color} flex items-center justify-center mb-3`}>
              <i className={`${icon} text-lg`}></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{value}</p>
            <p className="text-sm font-medium text-gray-700 mt-0.5">{label}</p>
            <p className="text-xs text-gray-400">{sub}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-2 gap-5">
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
          <h4 className="font-semibold text-gray-800 mb-4">Certificate Compliance by Department</h4>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={certComplianceData} barCategoryGap="30%" barGap={2}>
              <XAxis dataKey="dept" tick={{ fontSize: 10 }} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip />
              <Legend iconSize={10} iconType="circle" />
              <Bar dataKey="submitted" name="Submitted" fill="#22c55e" radius={[4, 4, 0, 0]} />
              <Bar dataKey="pending" name="Pending" fill="#f59e0b" radius={[4, 4, 0, 0]} />
              <Bar dataKey="missing" name="Missing" fill="#ef4444" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
          <h4 className="font-semibold text-gray-800 mb-4">Training Hours by Department</h4>
          <div className="flex items-center gap-4">
            <ResponsiveContainer width="60%" height={200}>
              <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} dataKey="value" paddingAngle={3}>
                  {pieData.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                </Pie>
                <Tooltip formatter={(v: number) => `${v} hrs`} />
              </PieChart>
            </ResponsiveContainer>
            <div className="space-y-2">
              {pieData.map((d, i) => (
                <div key={d.name} className="flex items-center gap-2">
                  <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ background: COLORS[i % COLORS.length] }}></div>
                  <span className="text-xs text-gray-600">{d.name}</span>
                  <span className="text-xs font-semibold text-gray-800">{d.value}h</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
          <h4 className="font-semibold text-gray-800 mb-4">Budget vs Actual Spend (KES)</h4>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={budgetData.map(d => ({ ...d, dept: d.dept.replace('Corporate Communication', 'Corp. Comm').replace('Monitoring & Evaluation', 'M&E') }))} barCategoryGap="30%" barGap={4}>
              <XAxis dataKey="dept" tick={{ fontSize: 10 }} />
              <YAxis tick={{ fontSize: 10 }} tickFormatter={v => `${v / 1000}K`} />
              <Tooltip formatter={(v: number) => `KES ${v.toLocaleString()}`} />
              <Legend iconSize={10} iconType="circle" />
              <Bar dataKey="planned" name="Planned" fill="#b22698" radius={[4, 4, 0, 0]} />
              <Bar dataKey="actual" name="Actual" fill="#f9a8d4" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
          <h4 className="font-semibold text-gray-800 mb-4">Evaluation Summary — Kirkpatrick Levels</h4>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-100">
                  <th className="text-left text-xs font-semibold text-gray-500 px-3 py-2">Level</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-3 py-2">Value</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-3 py-2">Benchmark</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-3 py-2">Status</th>
                </tr>
              </thead>
              <tbody>
                {[
                  { level: 'L1 Reaction', value: `${avgL1}/5`, benchmark: '≥ 4.0/5', pass: parseFloat(avgL1) >= 4.0 },
                  { level: 'L2 Learning', value: `+${avgGain}%`, benchmark: '≥ 20%', pass: avgGain >= 20 },
                  { level: 'L3 Behavior', value: `${l3Applied}/${trainingEvaluations.filter(e => e.l3Status === 'Completed').length}`, benchmark: '≥ 2/3', pass: l3Applied >= 2 },
                  { level: 'L4 Results', value: `${l4Improved}/${trainingEvaluations.length}`, benchmark: '≥ 2/3', pass: l4Improved >= 2 },
                ].map(row => (
                  <tr key={row.level} className="border-b border-gray-50 hover:bg-gray-50">
                    <td className="px-3 py-2.5">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-bold ${row.level.startsWith('L1') ? 'bg-blue-100 text-blue-700' : row.level.startsWith('L2') ? 'bg-purple-100 text-purple-700' : row.level.startsWith('L3') ? 'bg-orange-100 text-orange-700' : 'bg-green-100 text-green-700'}`}>
                        {row.level}
                      </span>
                    </td>
                    <td className="px-3 py-2.5 text-sm font-bold text-gray-800">{row.value}</td>
                    <td className="px-3 py-2.5 text-xs text-gray-500">{row.benchmark}</td>
                    <td className="px-3 py-2.5">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${row.pass ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                        {row.pass ? 'Met' : 'Below Target'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
