'use client';
import { useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line, Legend } from 'recharts';
import { LeaveRequest, LEAVE_POLICIES, EMPLOYEES } from './leaveData';

interface Props {
  requests: LeaveRequest[];
}

export default function LeaveReportsTab({ requests }: Props) {
  const [activeReport, setActiveReport] = useState<string | null>(null);

  const byType = LEAVE_POLICIES.map(p => ({
    name: p.label.replace(' Leave', ''),
    count: requests.filter(r => r.type === p.type && r.status === 'Approved').length,
    days: requests.filter(r => r.type === p.type && r.status === 'Approved').reduce((a, r) => a + r.days, 0),
    fill: p.color,
  })).filter(d => d.count > 0);

  const byDept = ['IT', 'HR', 'Finance', 'Operations'].map(dept => ({
    dept,
    approved: requests.filter(r => r.dept === dept && r.status === 'Approved').length,
    pending: requests.filter(r => r.dept === dept && r.status === 'Pending').length,
    rejected: requests.filter(r => r.dept === dept && r.status === 'Rejected').length,
  }));

  const monthlyTrend = [
    { month: 'Jan', total: 4, sick: 2, annual: 1 },
    { month: 'Feb', total: 6, sick: 3, annual: 2 },
    { month: 'Mar', total: 8, sick: 2, annual: 4 },
    { month: 'Apr', total: 12, sick: 3, annual: 6 },
    { month: 'May', total: 5, sick: 1, annual: 3 },
    { month: 'Jun', total: 9, sick: 2, annual: 5 },
  ];

  const totalApproved = requests.filter(r => r.status === 'Approved').length;
  const totalDays = requests.filter(r => r.status === 'Approved').reduce((a, r) => a + r.days, 0);
  const pendingCount = requests.filter(r => r.status === 'Pending').length;

  const reports = [
    { id: 'liability', name: 'Leave Liability Report', desc: 'Accrued but unused leave in monetary value', icon: 'ri-money-dollar-circle-line', color: '#b828a0' },
    { id: 'absenteeism', name: 'Absenteeism Report', desc: 'Sick leave frequency per employee', icon: 'ri-user-unfollow-line', color: '#ef4444' },
    { id: 'balance_summary', name: 'Leave Balance Summary', desc: 'Balance summary by department', icon: 'ri-wallet-3-line', color: '#3b82f6' },
    { id: 'utilization', name: 'Leave Utilization Report', desc: 'Leave taken vs entitlement per employee', icon: 'ri-bar-chart-line', color: '#10b981' },
    { id: 'pending', name: 'Pending Approvals Report', desc: 'All requests awaiting HR approval', icon: 'ri-time-line', color: '#f59e0b' },
  ];

  const liabilityData = [
    { name: 'Jane Mwangi', dept: 'HR', unused: 12, rate: 3800 },
    { name: 'Peter Otieno', dept: 'IT', unused: 16, rate: 4200 },
    { name: 'Grace Wanjiku', dept: 'Finance', unused: 7, rate: 3500 },
    { name: 'Samuel Kipchoge', dept: 'Operations', unused: 14, rate: 3200 },
    { name: 'Alice Odhiambo', dept: 'IT', unused: 21, rate: 3900 },
    { name: 'Linda Wambui', dept: 'Finance', unused: 17, rate: 4500 },
  ];

  const sickFreq = EMPLOYEES.map(emp => ({
    name: emp.name.split(' ')[0],
    count: requests.filter(r => r.employee === emp.name && r.type === 'Sick' && r.status === 'Approved').length,
  })).filter(e => e.count > 0).sort((a, b) => b.count - a.count);

  const handleDownloadPdf = async (reportId: string, title: string) => {
    const today = new Date().toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' });
    const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${title}</title>
    <style>body{font-family:Arial,Helvetica,sans-serif;font-size:11pt;color:#222;background:#fff;}
    .page{max-width:760px;margin:0 auto;padding:30px;}
    .logo-row{display:flex;align-items:center;justify-content:center;gap:40px;margin-bottom:12px;}
    .logo-img{height:70px;width:auto;object-fit:contain;}
    .doc-title{text-align:center;font-size:15pt;font-weight:bold;color:#b22698;letter-spacing:2px;text-transform:uppercase;margin-bottom:4px;}
    .doc-subtitle{text-align:center;font-size:10pt;color:#777;margin-bottom:20px;}
    .divider{border:none;border-top:3px solid #b22698;margin:8px 0 18px;}
    table{width:100%;border-collapse:collapse;margin-top:12px;}
    th{background:#f8f0fc;border-bottom:2px solid #b22698;padding:8px 10px;text-align:left;font-size:10pt;color:#555;text-transform:uppercase;}
    td{padding:7px 10px;border-bottom:1px solid #ece8f0;font-size:10pt;}
    tr:nth-child(even) td{background:#fdf4ff;}
    .footer{margin-top:30px;border-top:1px solid #eee;padding-top:12px;text-align:center;font-size:8.5pt;color:#bbb;}
    </style></head><body>
    <div class="page">
      <div class="logo-row">
        <img src="https://storage.readdy-site.link/project_files/8353c6c3-4df0-48e3-b13e-2f6c24e6f89d/cdcdd814-b3fe-46c1-9b8f-9725d6eb6c56_coat-of-arms.png?v=ae75c071780b2ebbd4c43c378032ba85" class="logo-img" alt="Coat of Arms" />
        <img src="https://storage.readdy-site.link/project_files/8353c6c3-4df0-48e3-b13e-2f6c24e6f89d/6d094512-dcbf-4464-ad6a-2cd0e9a78386_uwezo-fund-logo.png?v=b8c8d3a851b1cad388b3877b7e83a7db" class="logo-img" alt="Uwezo Fund Logo" />
      </div>
      <div class="doc-title">UWEZO FUND OVERSIGHT BOARD</div>
      <hr class="divider">
      <div class="doc-subtitle">${title} — Generated ${today}</div>
      <p style="color:#666;font-size:10pt;">This report is generated from the Uwezo Fund HRMS leave management module.</p>
    </div></body></html>`;
    try {
      const { printHtmlInIframe } = await import('../../../lib/autoDownloadPdf');
      await printHtmlInIframe(html, 30000);
    } catch {
      // fallback: silently ignore
    }
  };

  const handleDownloadExcel = (reportId: string, title: string) => {
    const today = new Date().toISOString().split('T')[0];
    const rows = [['UWEZO FUND OVERSIGHT BOARD — ' + title, 'Generated: ' + today], []];
    if (reportId === 'liability') {
      rows.push(['Employee', 'Department', 'Unused Days', 'Daily Rate (KES)', 'Liability (KES)']);
      liabilityData.forEach(r => rows.push([r.name, r.dept, String(r.unused), String(r.rate), String(r.unused * r.rate)]));
      rows.push([], ['Total Leave Liability', '', '', '', String(liabilityData.reduce((a, r) => a + r.unused * r.rate, 0))]);
    } else if (reportId === 'absenteeism') {
      rows.push(['Employee', 'Sick Leave Occurrences']);
      sickFreq.forEach(r => rows.push([r.name, String(r.count)]));
    } else if (reportId === 'balance_summary') {
      rows.push(['Department', 'Approved', 'Pending', 'Rejected']);
      byDept.forEach(r => rows.push([r.dept, String(r.approved), String(r.pending), String(r.rejected)]));
    } else if (reportId === 'pending') {
      const pendingReqs = requests.filter(r => r.status === 'Pending');
      rows.push(['ID', 'Employee', 'Department', 'Type', 'Start Date', 'End Date', 'Days']);
      pendingReqs.forEach(r => rows.push([r.id, r.employee, r.dept, r.type, r.startDate, r.endDate, String(r.days)]));
    }
    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-${today}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-4 gap-3">
        {[
          { label: 'Approved Requests', value: totalApproved, icon: 'ri-checkbox-circle-line', color: '#16a34a', bg: '#dcfce7' },
          { label: 'Total Days Taken', value: totalDays, icon: 'ri-calendar-check-line', color: '#b828a0', bg: '#fdf4ff' },
          { label: 'Pending Approval', value: pendingCount, icon: 'ri-time-line', color: '#d97706', bg: '#fef3c7' },
          { label: 'Employees on Leave', value: requests.filter(r => r.status === 'Approved' && r.startDate <= '2026-04-16' && r.endDate >= '2026-04-16').length, icon: 'ri-user-follow-line', color: '#3b82f6', bg: '#eff6ff' },
        ].map(s => (
          <div key={s.label} className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: s.bg }}>
              <i className={`${s.icon} text-lg`} style={{ color: s.color }}></i>
            </div>
            <div>
              <p className="text-xl font-bold text-gray-800">{s.value}</p>
              <p className="text-xs text-gray-500">{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
          <h4 className="font-semibold text-gray-700">Pre-built Reports</h4>
          <span className="text-xs text-gray-400">{reports.length} reports available</span>
        </div>
        <div className="divide-y divide-gray-50">
          {reports.map(r => (
            <div key={r.id} className="flex items-center gap-4 px-5 py-4 hover:bg-gray-50/50">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: r.color + '15' }}>
                <i className={`${r.icon} text-lg`} style={{ color: r.color }}></i>
              </div>
              <div className="flex-1">
                <p className="font-semibold text-gray-700 text-sm">{r.name}</p>
                <p className="text-xs text-gray-400">{r.desc}</p>
              </div>
              <div className="flex items-center gap-2">
                <button onClick={() => setActiveReport(activeReport === r.id ? null : r.id)}
                  className="flex items-center gap-1.5 px-3 py-1.5 border border-gray-200 rounded-lg text-xs text-gray-600 cursor-pointer hover:bg-gray-100 whitespace-nowrap">
                  <i className="ri-eye-line"></i> View
                </button>
                <button onClick={() => handleDownloadPdf(r.id, r.name)}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
                  <i className="ri-download-line"></i> PDF
                </button>
                <button onClick={() => handleDownloadExcel(r.id, r.name)}
                  className="flex items-center gap-1.5 px-3 py-1.5 border border-gray-200 rounded-lg text-xs text-gray-600 cursor-pointer hover:bg-gray-100 whitespace-nowrap">
                  <i className="ri-file-excel-line"></i> Excel
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {activeReport === 'liability' && (
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
            <h4 className="font-semibold text-gray-700">Leave Liability Report</h4>
            <button onClick={() => handleDownloadPdf('liability', 'Leave Liability Report')}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
              <i className="ri-download-line"></i> Export PDF
            </button>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-100">
                  <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Employee</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Department</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Unused Days</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Daily Rate (KES)</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Liability (KES)</th>
                </tr>
              </thead>
              <tbody>
                {liabilityData.map(row => (
                  <tr key={row.name} className="border-b border-gray-50 hover:bg-gray-50/50">
                    <td className="px-5 py-3 font-medium text-gray-700">{row.name}</td>
                    <td className="px-4 py-3 text-gray-500">{row.dept}</td>
                    <td className="px-4 py-3 text-right font-semibold text-gray-700">{row.unused}</td>
                    <td className="px-4 py-3 text-right text-gray-500">{row.rate.toLocaleString()}</td>
                    <td className="px-4 py-3 text-right font-bold text-gray-800">{(row.unused * row.rate).toLocaleString()}</td>
                  </tr>
                ))}
                <tr className="bg-purple-50 font-bold">
                  <td colSpan={4} className="px-5 py-3 text-right text-gray-700">Total Leave Liability</td>
                  <td className="px-4 py-3 text-right" style={{ color: '#b828a0' }}>
                    KES {liabilityData.reduce((a, r) => a + r.unused * r.rate, 0).toLocaleString()}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeReport === 'absenteeism' && (
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-5">
          <h4 className="font-semibold text-gray-700 mb-4">Absenteeism Report — Sick Leave Frequency</h4>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={sickFreq} layout="vertical" barSize={16}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11 }} />
              <YAxis type="category" dataKey="name" tick={{ fontSize: 11 }} width={80} />
              <Tooltip formatter={v => [`${v} occurrences`]} />
              <Bar dataKey="count" fill="#ef4444" radius={[0, 4, 4, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}

      {activeReport === 'balance_summary' && (
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-5">
          <h4 className="font-semibold text-gray-700 mb-4">Leave Balance Summary by Department</h4>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={byDept} barSize={16}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
              <XAxis dataKey="dept" tick={{ fontSize: 11 }} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip />
              <Legend iconSize={8} wrapperStyle={{ fontSize: '11px' }} />
              <Bar dataKey="approved" fill="#16a34a" radius={[3, 3, 0, 0]} name="Approved" />
              <Bar dataKey="pending" fill="#f59e0b" radius={[3, 3, 0, 0]} name="Pending" />
              <Bar dataKey="rejected" fill="#ef4444" radius={[3, 3, 0, 0]} name="Rejected" />
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}

      <div className="grid grid-cols-2 gap-4">
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-5">
          <h4 className="font-semibold text-gray-700 mb-1 text-sm">Leave by Type</h4>
          <p className="text-xs text-gray-400 mb-4">Distribution of approved leave requests</p>
          <ResponsiveContainer width="100%" height={200}>
            <PieChart>
              <Pie data={byType} dataKey="count" nameKey="name" cx="50%" cy="50%" outerRadius={75} paddingAngle={3}>
                {byType.map((entry, i) => <Cell key={i} fill={entry.fill} />)}
              </Pie>
              <Tooltip formatter={v => [`${v} requests`]} />
              <Legend iconSize={8} wrapperStyle={{ fontSize: '11px' }} />
            </PieChart>
          </ResponsiveContainer>
        </div>

        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-5">
          <h4 className="font-semibold text-gray-700 mb-1 text-sm">Monthly Leave Trend</h4>
          <p className="text-xs text-gray-400 mb-4">Leave taken over the past 6 months</p>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={monthlyTrend}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
              <XAxis dataKey="month" tick={{ fontSize: 11 }} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip />
              <Legend iconSize={8} wrapperStyle={{ fontSize: '11px' }} />
              <Line type="monotone" dataKey="total" stroke="#b828a0" strokeWidth={2} dot={false} name="Total" />
              <Line type="monotone" dataKey="sick" stroke="#ef4444" strokeWidth={2} dot={false} name="Sick" />
              <Line type="monotone" dataKey="annual" stroke="#8b5cf6" strokeWidth={2} dot={false} name="Annual" />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>
    </div>
  );
}
