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

const BRAND = '#B22698';

interface BudgetProposal {
  id: string;
  dept: string;
  category: string;
  amount: number;
  requestedBy: string;
  submittedOn: string;
  purpose: string;
  status: 'Pending' | 'Approved' | 'Rejected';
  approvedOn?: string;
  remarks?: string;
}

const INITIAL_BUDGETS: BudgetProposal[] = [
  { id: 'BG001', dept: 'ICT', category: 'Software Licenses', amount: 450000, requestedBy: 'David Njoroge', submittedOn: '2026-04-10', purpose: 'Annual renewal of enterprise software licenses for development tools.', status: 'Pending' },
  { id: 'BG002', dept: 'Finance', category: 'Staff Training', amount: 180000, requestedBy: 'James Omondi', submittedOn: '2026-04-12', purpose: 'CPA training for 3 finance staff members.', status: 'Pending' },
  { id: 'BG003', dept: 'HR', category: 'Recruitment', amount: 95000, requestedBy: 'Susan Kariuki', submittedOn: '2026-04-08', purpose: 'Recruitment campaign for 2 vacant positions.', status: 'Approved', approvedOn: '2026-04-14', remarks: 'Approved as per HR plan 2026.' },
  { id: 'BG004', dept: 'Operations', category: 'Equipment', amount: 320000, requestedBy: 'Mary Ndungu', submittedOn: '2026-04-15', purpose: 'Replacement of 4 desktop computers and 2 printers.', status: 'Pending' },
  { id: 'BG005', dept: 'ICT', category: 'Infrastructure', amount: 750000, requestedBy: 'David Njoroge', submittedOn: '2026-03-28', purpose: 'Network upgrade and new server procurement.', status: 'Approved', approvedOn: '2026-04-05', remarks: 'Approved. Procurement to follow procurement guidelines.' },
  { id: 'BG006', dept: 'Finance', category: 'Audit Services', amount: 200000, requestedBy: 'James Omondi', submittedOn: '2026-04-01', purpose: 'External audit for Q1 2026 financial review.', status: 'Rejected', approvedOn: '2026-04-10', remarks: 'Covered under existing annual audit contract.' },
  { id: 'BG007', dept: 'Operations', category: 'Vehicle Maintenance', amount: 115000, requestedBy: 'Mary Ndungu', submittedOn: '2026-04-18', purpose: 'Scheduled service for 3 department vehicles.', status: 'Pending' },
];

export default function FinanceBudgetsPage() {
  const [budgets, setBudgets] = useState<BudgetProposal[]>(INITIAL_BUDGETS);
  const [toast, setToast] = useState('');
  const [approveModal, setApproveModal] = useState<string | null>(null);
  const [rejectModal, setRejectModal] = useState<string | null>(null);
  const [remarks, setRemarks] = useState('');
  const [previewLetter, setPreviewLetter] = useState<BudgetProposal | null>(null);
  const [statusFilter, setStatusFilter] = useState('Pending');

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

  const handleApprove = () => {
    if (!approveModal) return;
    setBudgets(prev => prev.map(b => b.id === approveModal ? { ...b, status: 'Approved' as const, approvedOn: new Date().toISOString().split('T')[0], remarks } : b));
    setApproveModal(null);
    setRemarks('');
    showToast('Budget proposal approved. Approval letter can now be generated.');
  };

  const handleReject = () => {
    if (!rejectModal || !remarks) return;
    setBudgets(prev => prev.map(b => b.id === rejectModal ? { ...b, status: 'Rejected' as const, approvedOn: new Date().toISOString().split('T')[0], remarks } : b));
    setRejectModal(null);
    setRemarks('');
    showToast('Budget proposal rejected.');
  };

  const downloadLetter = (b: BudgetProposal) => {
    const letterHtml = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Budget Approval Letter - ${b.id}</title>
<style>
  body { font-family: 'Times New Roman', serif; margin: 0; padding: 40px; color: #1a1a1a; }
  .header { text-align: center; border-bottom: 3px solid #B22698; padding-bottom: 20px; margin-bottom: 30px; }
  .logo-area { display: flex; align-items: center; justify-content: center; gap: 16px; margin-bottom: 8px; }
  .org-name { font-size: 24px; font-weight: bold; color: #B22698; }
  .org-sub { font-size: 13px; color: #666; }
  .ref-date { display: flex; justify-content: space-between; margin-bottom: 24px; font-size: 13px; }
  .subject { background: #fce7f3; border-left: 4px solid #B22698; padding: 12px 16px; margin: 20px 0; font-weight: bold; font-size: 14px; }
  .body-text { font-size: 13px; line-height: 1.8; margin-bottom: 16px; }
  .details-table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }
  .details-table td { padding: 8px 12px; border: 1px solid #e5e7eb; }
  .details-table td:first-child { font-weight: bold; background: #f9fafb; width: 35%; }
  .amount-highlight { font-size: 18px; font-weight: bold; color: #B22698; }
  .signature-area { margin-top: 40px; }
  .sig-line { border-top: 1px solid #333; width: 200px; margin-top: 40px; padding-top: 8px; font-size: 12px; }
  .footer { margin-top: 40px; padding-top: 16px; border-top: 1px solid #e5e7eb; text-align: center; font-size: 11px; color: #999; }
  .stamp { display: inline-block; border: 3px solid #16a34a; color: #16a34a; padding: 8px 20px; font-weight: bold; font-size: 16px; transform: rotate(-5deg); margin: 20px 0; }
  @media print { body { padding: 20px; } }
</style>
</head>
<body>
<div class="header">
  <div class="logo-area">
    <div>
      <div class="org-name">UWEZO FUND</div>
      <div class="org-sub">Empowering Communities Through Financial Inclusion</div>
      <div class="org-sub">P.O. Box 12345-00100, Nairobi, Kenya | finance@uwezo.go.ke | +254 700 000 000</div>
    </div>
  </div>
</div>

<div class="ref-date">
  <div><strong>Ref:</strong> UF/FIN/BUDGET/${b.id}/${new Date().getFullYear()}</div>
  <div><strong>Date:</strong> ${b.approvedOn || new Date().toISOString().split('T')[0]}</div>
</div>

<div>
  <strong>To:</strong> ${b.requestedBy}<br>
  <strong>Department:</strong> ${b.dept}<br>
  <strong>Uwezo Fund</strong>
</div>

<div class="subject">
  RE: BUDGET APPROVAL LETTER — ${b.category.toUpperCase()} (${b.id})
</div>

<p class="body-text">Dear ${b.requestedBy.split(' ')[0]},</p>

<p class="body-text">
  I write to inform you that your budget proposal referenced <strong>${b.id}</strong> for the <strong>${b.dept} Department</strong> 
  has been reviewed by the Finance Office and has been <strong>APPROVED</strong> as detailed below.
</p>

<table class="details-table">
  <tr><td>Proposal Reference</td><td>${b.id}</td></tr>
  <tr><td>Department</td><td>${b.dept}</td></tr>
  <tr><td>Budget Category</td><td>${b.category}</td></tr>
  <tr><td>Approved Amount</td><td><span class="amount-highlight">KES ${b.amount.toLocaleString()}</span></td></tr>
  <tr><td>Purpose</td><td>${b.purpose}</td></tr>
  <tr><td>Date Submitted</td><td>${b.submittedOn}</td></tr>
  <tr><td>Date Approved</td><td>${b.approvedOn}</td></tr>
  <tr><td>Finance Remarks</td><td>${b.remarks || 'Approved as submitted.'}</td></tr>
</table>

<div style="text-align:center; margin: 20px 0;">
  <div class="stamp">✓ APPROVED</div>
</div>

<p class="body-text">
  You are hereby authorized to proceed with the expenditure of <strong>KES ${b.amount.toLocaleString()}</strong> 
  for the stated purpose. Please ensure all expenditures are supported by appropriate documentation and 
  comply with Uwezo Fund's Financial Regulations and Procurement Guidelines.
</p>

<p class="body-text">
  Kindly note that this approval is subject to the following conditions:
</p>
<ol style="font-size:13px; line-height:1.8;">
  <li>All procurement must follow the Public Procurement and Asset Disposal Act, 2015.</li>
  <li>Expenditure must be within the approved amount. Any variation requires fresh approval.</li>
  <li>Supporting documents (LPOs, invoices, receipts) must be submitted to Finance within 30 days.</li>
  <li>This approval is valid for the current financial year only.</li>
</ol>

<p class="body-text">For any clarifications, please contact the Finance Office.</p>

<p class="body-text">Yours faithfully,</p>

<div class="signature-area">
  <div class="sig-line">
    <strong>Catherine Waweru</strong><br>
    Finance Officer<br>
    Uwezo Fund<br>
    finance@uwezo.go.ke
  </div>
</div>

<div class="footer">
  This is an official document generated by Uwezo Fund HRMS v2.0 · ${new Date().toLocaleString()} · Ref: ${b.id}
</div>
</body>
</html>`;

    const blob = new Blob([letterHtml], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `Budget-Approval-Letter-${b.id}-${b.dept}.html`;
    a.click();
    URL.revokeObjectURL(url);
    showToast(`Approval letter for ${b.id} downloaded successfully.`);
  };

  const filtered = statusFilter === 'All' ? budgets : budgets.filter(b => b.status === statusFilter);
  const pendingCount = budgets.filter(b => b.status === 'Pending').length;
  const approvedCount = budgets.filter(b => b.status === 'Approved').length;
  const totalApprovedAmount = budgets.filter(b => b.status === 'Approved').reduce((s, b) => s + b.amount, 0);

  return (
    <FinanceLayout title="Budget Approvals">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2" style={{ background: BRAND }}>
          <i className="ri-checkbox-circle-line"></i><span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="space-y-5">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-gray-800">Department Budget Proposals</h2>
            <p className="text-sm text-gray-500">Review, approve/reject proposals and generate official approval letters</p>
          </div>
          {pendingCount > 0 && (
            <div className="flex items-center gap-2 bg-pink-50 border rounded-xl px-4 py-2" style={{ borderColor: BRAND }}>
              <i className="ri-alarm-warning-line" style={{ color: BRAND }}></i>
              <span className="text-sm font-semibold" style={{ color: BRAND }}>{pendingCount} proposals awaiting decision</span>
            </div>
          )}
        </div>

        <div className="grid grid-cols-3 gap-4">
          <div className="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
            <p className="text-2xl font-bold text-amber-600">{pendingCount}</p>
            <p className="text-xs text-gray-500 mt-0.5">Pending Review</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
            <p className="text-2xl font-bold text-green-600">{approvedCount}</p>
            <p className="text-xs text-gray-500 mt-0.5">Approved</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
            <p className="text-xl font-bold" style={{ color: BRAND }}>KES {totalApprovedAmount.toLocaleString()}</p>
            <p className="text-xs text-gray-500 mt-0.5">Total Approved Amount</p>
          </div>
        </div>

        <div className="flex gap-2">
          {['Pending', 'All', 'Approved', '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: BRAND, color: '#fff' } : { background: '#f3f4f6', color: '#4b5563' }}>
              {s}{s === 'Pending' && pendingCount > 0 ? ` (${pendingCount})` : ''}
            </button>
          ))}
        </div>

        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <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">Proposal</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Dept</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">Purpose</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(b => (
                  <tr key={b.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                    <td className="px-5 py-3">
                      <p className="font-mono text-xs font-bold" style={{ color: BRAND }}>{b.id}</p>
                      <p className="text-xs text-gray-400">{b.submittedOn} · {b.requestedBy}</p>
                    </td>
                    <td className="px-4 py-3 font-medium text-gray-700">{b.dept}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{b.category}</td>
                    <td className="px-4 py-3 text-right font-bold text-gray-800">
                      {b.amount.toLocaleString()}
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-500 max-w-[180px] truncate">{b.purpose}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap
                        ${b.status === 'Approved' ? 'bg-green-100 text-green-700' : b.status === 'Rejected' ? 'bg-red-100 text-red-700' : 'bg-amber-100 text-amber-700'}`}>
                        {b.status}
                      </span>
                      {b.approvedOn && <p className="text-xs text-gray-400 mt-0.5">{b.approvedOn}</p>}
                    </td>
                    <td className="px-4 py-3 text-right">
                      {b.status === 'Pending' ? (
                        <div className="flex items-center justify-end gap-1">
                          <button onClick={() => { setApproveModal(b.id); setRemarks(''); }}
                            className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-white hover:opacity-90 cursor-pointer text-xs font-semibold whitespace-nowrap"
                            style={{ background: BRAND }}>
                            <i className="ri-check-line"></i> Approve
                          </button>
                          <button onClick={() => { setRejectModal(b.id); setRemarks(''); }}
                            className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-red-50 text-red-600 hover:bg-red-100 cursor-pointer text-xs font-semibold whitespace-nowrap">
                            <i className="ri-close-line"></i> Reject
                          </button>
                        </div>
                      ) : b.status === 'Approved' ? (
                        <div className="flex items-center justify-end gap-1">
                          <button onClick={() => setPreviewLetter(b)}
                            className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-pink-50 text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ color: BRAND }}>
                            <i className="ri-eye-line"></i> Preview
                          </button>
                          <button onClick={() => downloadLetter(b)}
                            className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-white cursor-pointer text-xs font-semibold whitespace-nowrap"
                            style={{ background: BRAND }}>
                            <i className="ri-download-line"></i> Download
                          </button>
                        </div>
                      ) : (
                        <span className="text-xs text-gray-400 italic">{b.remarks}</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {approveModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: '#fce7f3' }}>
                <i className="ri-check-line text-lg" style={{ color: BRAND }}></i>
              </div>
              <div>
                <h3 className="font-bold text-gray-800">Approve Budget Proposal</h3>
                <p className="text-xs text-gray-500">An approval letter will be generated after approval</p>
              </div>
            </div>
            <textarea value={remarks} onChange={e => setRemarks(e.target.value)} rows={3}
              placeholder="Approval remarks (optional)..."
              className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none mb-4" />
            <div className="flex gap-3">
              <button onClick={() => setApproveModal(null)}
                className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={handleApprove}
                className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: BRAND }}>
                Confirm Approval
              </button>
            </div>
          </div>
        </div>
      )}

      {rejectModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <h3 className="font-bold text-gray-800 mb-1">Reject Budget Proposal</h3>
            <p className="text-sm text-gray-500 mb-4">Provide reason for rejection (required).</p>
            <textarea value={remarks} onChange={e => setRemarks(e.target.value)} rows={3}
              placeholder="Reason for rejection..."
              className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none mb-4" />
            <div className="flex gap-3">
              <button onClick={() => setRejectModal(null)}
                className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={handleReject} disabled={!remarks}
                className="flex-1 py-2.5 bg-red-600 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap">
                Confirm Rejection
              </button>
            </div>
          </div>
        </div>
      )}

      {previewLetter && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#fce7f3' }}>
                  <i className="ri-file-text-line" style={{ color: BRAND }}></i>
                </div>
                <div>
                  <h3 className="font-bold text-gray-800">Budget Approval Letter Preview</h3>
                  <p className="text-xs text-gray-400">{previewLetter.id} · {previewLetter.dept}</p>
                </div>
              </div>
              <button onClick={() => setPreviewLetter(null)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer">
                <i className="ri-close-line text-gray-500"></i>
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6">
              <div className="border-2 rounded-xl p-6 space-y-4" style={{ borderColor: BRAND }}>
                <div className="text-center border-b pb-4" style={{ borderColor: BRAND }}>
                  <p className="text-xl font-bold" style={{ color: BRAND }}>UWEZO FUND</p>
                  <p className="text-xs text-gray-500">Empowering Communities Through Financial Inclusion</p>
                  <p className="text-xs text-gray-400">P.O. Box 12345-00100, Nairobi | finance@uwezo.go.ke</p>
                </div>
                <div className="flex justify-between text-xs text-gray-600">
                  <span><strong>Ref:</strong> UF/FIN/BUDGET/{previewLetter.id}/{new Date().getFullYear()}</span>
                  <span><strong>Date:</strong> {previewLetter.approvedOn}</span>
                </div>
                <div className="text-sm">
                  <p><strong>To:</strong> {previewLetter.requestedBy}</p>
                  <p><strong>Department:</strong> {previewLetter.dept}</p>
                </div>
                <div className="rounded-lg px-4 py-2 text-sm font-bold" style={{ background: '#fce7f3', color: BRAND }}>
                  RE: BUDGET APPROVAL — {previewLetter.category.toUpperCase()} ({previewLetter.id})
                </div>
                <p className="text-sm text-gray-700">Dear {previewLetter.requestedBy.split(' ')[0]},</p>
                <p className="text-sm text-gray-700">Your budget proposal <strong>{previewLetter.id}</strong> for the <strong>{previewLetter.dept} Department</strong> has been reviewed and <strong>APPROVED</strong>.</p>
                <div className="border border-gray-200 rounded-lg overflow-hidden text-xs">
                  {[
                    ['Proposal ID', previewLetter.id],
                    ['Department', previewLetter.dept],
                    ['Category', previewLetter.category],
                    ['Approved Amount', `KES ${previewLetter.amount.toLocaleString()}`],
                    ['Purpose', previewLetter.purpose],
                    ['Date Approved', previewLetter.approvedOn || ''],
                    ['Remarks', previewLetter.remarks || 'Approved as submitted.'],
                  ].map(([k, v]) => (
                    <div key={k} className="flex border-b border-gray-100 last:border-0">
                      <div className="w-36 px-3 py-2 font-semibold bg-gray-50 flex-shrink-0">{k}</div>
                      <div className="px-3 py-2 text-gray-700 flex-1">{v}</div>
                    </div>
                  ))}
                </div>
                <div className="text-center">
                  <span className="inline-block border-2 border-green-600 text-green-700 px-6 py-2 font-bold text-sm rounded-lg">✓ APPROVED</span>
                </div>
                <div className="mt-4 pt-4 border-t border-gray-100">
                  <p className="text-xs text-gray-500 font-semibold">Catherine Waweru</p>
                  <p className="text-xs text-gray-400">Finance Officer · Uwezo Fund</p>
                </div>
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-100 flex gap-3">
              <button onClick={() => setPreviewLetter(null)}
                className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Close</button>
              <button onClick={() => { downloadLetter(previewLetter); setPreviewLetter(null); }}
                className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap flex items-center justify-center gap-2"
                style={{ background: BRAND }}>
                <i className="ri-download-line"></i> Download Letter
              </button>
            </div>
          </div>
        </div>
      )}
    </FinanceLayout>
  );
}
