'use client';
import { useState } from 'react';
import FinanceLayout from '../../../components/FinanceLayout';
import { useTrainingStore } from '../../../lib/trainingStore';

const BUDGET_PROPOSALS = [
  { id: 'FR001', dept: 'ICT', category: 'Software Licenses', amount: 450000, status: 'Pending', date: '2026-04-10', submittedBy: 'Gedion Njoroge' },
  { id: 'FR002', dept: 'Monitoring & Evaluation', category: 'Field Equipment', amount: 280000, status: 'Approved', date: '2026-04-08', submittedBy: 'Evans Oyaro' },
  { id: 'FR003', dept: 'Procurement', category: 'Office Supplies', amount: 95000, status: 'Approved', date: '2026-04-05', submittedBy: 'Laban Mwangi' },
  { id: 'FR004', dept: 'Transport', category: 'Vehicle Maintenance', amount: 115000, status: 'Pending', date: '2026-04-12', submittedBy: 'Margaret Murithi' },
  { id: 'FR005', dept: 'ICT', category: 'Infrastructure Upgrade', amount: 750000, status: 'Approved', date: '2026-03-28', submittedBy: 'Gedion Njoroge' },
  { id: 'FR006', dept: 'Corporate Communication', category: 'Media Production', amount: 180000, status: 'Rejected', date: '2026-04-01', submittedBy: 'Benadette Owade' },
  { id: 'FR007', dept: 'Monitoring & Evaluation', category: 'Data Collection Tools', amount: 320000, status: 'Approved', date: '2026-03-15', submittedBy: 'Evans Oyaro' },
  { id: 'FR008', dept: 'Procurement', category: 'Audit Services', amount: 200000, status: 'Rejected', date: '2026-04-01', submittedBy: 'Laban Mwangi' },
];

const DEPT_BUDGETS = [
  { dept: 'ICT', allocated: 2500000, used: 1876000 },
  { dept: 'Monitoring & Evaluation', allocated: 1800000, used: 1420000 },
  { dept: 'Procurement', allocated: 1200000, used: 890000 },
  { dept: 'Transport', allocated: 900000, used: 620000 },
  { dept: 'Corporate Communication', allocated: 750000, used: 480000 },
];

export default function FinanceReportsPage() {
  const { trainingReqs } = useTrainingStore();
  const [statusFilter, setStatusFilter] = useState('All');

  const filtered = statusFilter === 'All' ? BUDGET_PROPOSALS : BUDGET_PROPOSALS.filter(r => r.status === statusFilter);

  const totalApproved = BUDGET_PROPOSALS.filter(r => r.status === 'Approved').reduce((s, r) => s + r.amount, 0);
  const totalPending = BUDGET_PROPOSALS.filter(r => r.status === 'Pending').reduce((s, r) => s + r.amount, 0);
  const totalRejected = BUDGET_PROPOSALS.filter(r => r.status === 'Rejected').reduce((s, r) => s + r.amount, 0);

  const approvedTraining = trainingReqs.filter(r => r.currentStage === 'Complete');
  const totalTrainingApproved = approvedTraining.reduce((s, r) => s + r.estimatedCost, 0);
  const rejectedTraining = trainingReqs.filter(r => r.currentStage === 'Rejected');

  const maxBudget = Math.max(...DEPT_BUDGETS.map(d => d.allocated));

  const exportReport = () => {
    const content = `UWEZO FUND — FINANCIAL REPORTS
Date: ${new Date().toISOString().split('T')[0]}

BUDGET PROPOSALS SUMMARY
Total Approved: KES ${totalApproved.toLocaleString()}
Total Pending: KES ${totalPending.toLocaleString()}
Total Rejected: KES ${totalRejected.toLocaleString()}

TRAINING BUDGETS SUMMARY
Total Approved Training Budgets: ${approvedTraining.length} (KES ${totalTrainingApproved.toLocaleString()})
Total Rejected Training Requests: ${rejectedTraining.length}

DEPARTMENT BUDGET UTILIZATION
${DEPT_BUDGETS.map(d => `${d.dept}: KES ${d.used.toLocaleString()} / KES ${d.allocated.toLocaleString()} (${Math.round((d.used / d.allocated) * 100)}%)`).join('\n')}

BUDGET PROPOSALS DETAIL
${BUDGET_PROPOSALS.map(r => `${r.id},${r.dept},${r.category},${r.amount},${r.status},${r.date},${r.submittedBy}`).join('\n')}

APPROVED TRAINING BUDGETS
${approvedTraining.map(r => `${r.id},${r.employeeName},${r.dept},${r.courseRequested},${r.estimatedCost},${r.financeApprovedOn || ''}`).join('\n')}
`.trim();

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `Financial-Reports-${new Date().toISOString().split('T')[0]}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <FinanceLayout title="Financial Reports">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-gray-800">Financial Reports</h2>
            <p className="text-sm text-gray-500">Budget proposals, training expenditures, and department utilization</p>
          </div>
          <button onClick={exportReport}
            className="flex items-center gap-2 text-white px-4 py-2.5 rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: '#b828a0' }}>
            <i className="ri-download-line"></i> Export Report
          </button>
        </div>

        <div className="grid grid-cols-4 gap-4">
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400 mb-1">Budget Proposals Approved</p>
            <p className="text-2xl font-bold text-green-700">KES {(totalApproved / 1000000).toFixed(2)}M</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400 mb-1">Budget Proposals Pending</p>
            <p className="text-2xl font-bold text-amber-600">KES {(totalPending / 1000000).toFixed(2)}M</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400 mb-1">Training Budgets Approved</p>
            <p className="text-2xl font-bold" style={{ color: '#b828a0' }}>KES {(totalTrainingApproved / 1000).toFixed(0)}K</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400 mb-1">Proposals Rejected</p>
            <p className="text-2xl font-bold text-red-600">KES {(totalRejected / 1000000).toFixed(2)}M</p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <h3 className="font-bold text-gray-800 mb-4">Department Budget Utilization</h3>
            <div className="space-y-4">
              {DEPT_BUDGETS.map(d => {
                const pct = Math.round((d.used / d.allocated) * 100);
                const isHigh = pct > 85;
                return (
                  <div key={d.dept}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-gray-700">{d.dept}</span>
                      <span className={`text-xs font-bold ${isHigh ? 'text-red-600' : 'text-gray-600'}`}>{pct}%</span>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-3">
                      <div className="h-3 rounded-full transition-all" style={{ width: `${pct}%`, background: isHigh ? '#dc2626' : '#b828a0' }}></div>
                    </div>
                    <div className="flex justify-between mt-0.5">
                      <span className="text-xs text-gray-400">KES {(d.used / 1000000).toFixed(1)}M used</span>
                      <span className="text-xs text-gray-400">KES {(d.allocated / 1000000).toFixed(1)}M allocated</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <h3 className="font-bold text-gray-800 mb-4">Approved Training Budgets</h3>
            {approvedTraining.length === 0 ? (
              <p className="text-sm text-gray-400 text-center py-8">No approved training budgets yet</p>
            ) : (
              <div className="space-y-3">
                {approvedTraining.map(r => (
                  <div key={r.id} className="flex items-center justify-between p-3 bg-green-50 rounded-xl border border-green-100">
                    <div>
                      <p className="text-sm font-medium text-gray-800">{r.courseRequested}</p>
                      <p className="text-xs text-gray-500">{r.employeeName} · {r.dept}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-bold text-green-700">KES {r.estimatedCost.toLocaleString()}</p>
                      <p className="text-xs text-gray-400">{r.financeApprovedOn}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
            <h3 className="font-bold text-gray-800">Budget Proposals — Full Report</h3>
            <div className="flex gap-2">
              {['All', 'Approved', 'Pending', 'Rejected'].map(s => (
                <button key={s} onClick={() => setStatusFilter(s)}
                  className="px-3 py-1.5 rounded-full text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
                  style={statusFilter === s ? { background: '#b828a0', color: '#fff' } : { background: '#f3f4f6', color: '#4b5563' }}>
                  {s}
                </button>
              ))}
            </div>
          </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">ID</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Department</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Category</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Amount (KES)</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Submitted By</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Date</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(r => (
                  <tr key={r.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                    <td className="px-5 py-3 font-mono text-xs text-gray-500">{r.id}</td>
                    <td className="px-4 py-3 font-medium text-gray-700">{r.dept}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{r.category}</td>
                    <td className="px-4 py-3 text-right font-bold text-gray-800">{r.amount.toLocaleString()}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{r.submittedBy}</td>
                    <td className="px-4 py-3 text-xs text-gray-400">{r.date}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap ${r.status === 'Approved' ? 'bg-green-100 text-green-700' : r.status === 'Rejected' ? 'bg-red-100 text-red-700' : 'bg-amber-100 text-amber-700'}`}>
                        {r.status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="px-5 py-2 border-t border-gray-50 bg-gray-50/30">
            <p className="text-xs text-gray-400">Showing {filtered.length} of {BUDGET_PROPOSALS.length} records</p>
          </div>
        </div>
      </div>
    </FinanceLayout>
  );
}
