'use client';
import { useState } from 'react';
import FinanceLayout from '../../../components/FinanceLayout';
import { useAuth } from '../../../lib/authContext';
import { useTrainingStore } from '../../../lib/trainingStore';
import { TrainingRequest } from '../../hr/training/trainingModuleData';
import { initialPrograms, TrainingProgram } from '../../hr/training/trainingData';
import ProgramViewModal from '../../../components/ProgramViewModal';

const BRAND = '#B22698';

const STAGE_CONFIG: Record<string, { color: string; bg: string; label: string }> = {
  HR: { color: '#d97706', bg: '#fef3c7', label: 'Pending HR' },
  HOS: { color: BRAND, bg: '#fce7f3', label: 'Pending HOS' },
  Finance: { color: '#2563eb', bg: '#dbeafe', label: 'Pending Finance' },
  Complete: { color: '#16a34a', bg: '#dcfce7', label: 'Fully Approved' },
  Rejected: { color: '#dc2626', bg: '#fee2e2', label: 'Rejected' },
};

export default function FinanceTrainingPage() {
  const { user } = useAuth();

  if (!user) return null;

  const { trainingReqs, updateTrainingReqs } = useTrainingStore();
  const [toast, setToast] = useState('');
  const [rejectModal, setRejectModal] = useState<string | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [filter, setFilter] = useState('Finance');
  const [viewProgram, setViewProgram] = useState<TrainingProgram | null>(null);

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

  const pendingFinance = trainingReqs.filter(r => r.currentStage === 'Finance');
  const displayReqs = filter === 'Finance' ? pendingFinance : filter === 'Complete' ? trainingReqs.filter(r => r.currentStage === 'Complete') : trainingReqs;

  const handleApprove = (id: string) => {
    updateTrainingReqs(prev => prev.map(r =>
      r.id === id && r.currentStage === 'Finance'
        ? { ...r, status: 'Finance Approved' as const, currentStage: 'Complete' as const, financeApprovedBy: user.name, financeApprovedOn: new Date().toISOString().split('T')[0] }
        : r
    ));
    showToast('Training budget approved! The training can now commence.');
  };

  const handleReject = () => {
    if (!rejectModal || !rejectReason) return;
    updateTrainingReqs(prev => prev.map(r =>
      r.id === rejectModal
        ? { ...r, status: 'Rejected' as const, currentStage: 'Rejected' as const, rejectReason, rejectedBy: user.name, rejectedStage: 'Finance' }
        : r
    ));
    setRejectModal(null);
    setRejectReason('');
    showToast('Training request rejected due to budget constraints.');
  };

  const downloadApprovalLetter = (r: TrainingRequest) => {
    const content = `UWEZO FUND
TRAINING BUDGET APPROVAL LETTER

Date: ${r.financeApprovedOn || new Date().toISOString().split('T')[0]}
Reference: ${r.id}

To: ${r.employeeName}
Department: ${r.dept}

Dear ${r.employeeName.split(' ')[0]},

RE: APPROVAL OF TRAINING BUDGET — ${r.courseRequested.toUpperCase()}

This letter confirms that the budget for the above training has been reviewed and APPROVED by the Finance Officer.

TRAINING DETAILS:
- Course: ${r.courseRequested}
- Department: ${r.dept}
- Estimated Cost: KES ${r.estimatedCost.toLocaleString()}
- Preferred Dates: ${r.preferredStartDate} to ${r.preferredEndDate}
- Justification: ${r.justification}

APPROVAL TRAIL:
- HR Approved: ${r.hrApprovedBy || 'N/A'} on ${r.hrApprovedOn || 'N/A'}
- HOS Approved: ${r.hosApprovedBy || 'N/A'} on ${r.hosApprovedOn || 'N/A'}
- Finance Approved: ${r.financeApprovedBy || user.name} on ${r.financeApprovedOn || new Date().toISOString().split('T')[0]}

You may now proceed with the training enrollment.

_______________________________
FINANCE OFFICER
UWEZO FUND

Uwezo Fund HRMS Version 2.0.1 © 2026`.trim();

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `Training-Budget-Approval-${r.id}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const totalPendingCost = pendingFinance.reduce((s, r) => s + r.estimatedCost, 0);
  const totalApprovedCost = trainingReqs.filter(r => r.currentStage === 'Complete').reduce((s, r) => s + r.estimatedCost, 0);

  return (
    <FinanceLayout title="Training Budget Approvals">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2">
          <i className="ri-checkbox-circle-line"></i><span className="text-sm font-medium">{toast}</span>
        </div>
      )}
      <div className="space-y-5">
        <div>
          <h2 className="text-lg font-bold text-gray-800">Training Budget Approvals</h2>
          <p className="text-sm text-gray-500">Final approval for training budgets. Approved trainings can commence immediately.</p>
        </div>

        <div className="grid grid-cols-3 gap-4">
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400">Pending Your Approval</p>
            <p className="text-2xl font-bold text-amber-600 mt-1">{pendingFinance.length}</p>
            <p className="text-xs text-gray-400 mt-1">KES {totalPendingCost.toLocaleString()} total</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400">Approved This Year</p>
            <p className="text-2xl font-bold text-green-600 mt-1">{trainingReqs.filter(r => r.currentStage === 'Complete').length}</p>
            <p className="text-xs text-gray-400 mt-1">KES {totalApprovedCost.toLocaleString()} total</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4">
            <p className="text-xs text-gray-400">Rejected</p>
            <p className="text-2xl font-bold text-red-600 mt-1">{trainingReqs.filter(r => r.currentStage === 'Rejected').length}</p>
          </div>
        </div>

        <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-2">
          <i className="ri-information-line text-blue-600 mt-0.5"></i>
          <p className="text-xs text-blue-800">As Finance Officer, you are the <strong>final approver</strong> for all training budgets. Once you approve, the training is fully authorized and can commence. Rejected requests are returned to the employee.</p>
        </div>

        <div className="flex gap-2">
          {[{ k: 'Finance', l: `Pending Approval (${pendingFinance.length})` }, { k: 'Complete', l: 'Approved' }, { k: 'all', l: 'All Requests' }].map(t => (
            <button key={t.k} onClick={() => setFilter(t.k)}
              className="px-3 py-1.5 rounded-full text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
              style={filter === t.k ? { background: BRAND, color: '#fff' } : { background: '#f3f4f6', color: '#4b5563' }}>
              {t.l}
            </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">Employee</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Course</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Dept</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Cost (KES)</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Approval Trail</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Stage</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody>
                {displayReqs.length === 0 && (
                  <tr><td colSpan={7} className="text-center py-10 text-gray-400 text-sm">No requests found</td></tr>
                )}
                {displayReqs.map(r => {
                  const sc = STAGE_CONFIG[r.currentStage] || STAGE_CONFIG['HR'];
                  return (
                    <tr key={r.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                      <td className="px-5 py-3">
                        <p className="font-medium text-gray-800">{r.employeeName}</p>
                        <p className="text-xs text-gray-400">{r.dateSubmitted}</p>
                      </td>
                      <td className="px-4 py-3">
                        <p className="text-sm text-gray-700 font-medium">{r.courseRequested}</p>
                        <p className="text-xs text-gray-400 truncate max-w-[180px]">{r.justification.slice(0, 50)}...</p>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">{r.dept}</td>
                      <td className="px-4 py-3 text-right font-bold text-gray-800">{r.estimatedCost.toLocaleString()}</td>
                      <td className="px-4 py-3 text-xs">
                        <div className="flex items-center gap-1 flex-wrap">
                          <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${r.hrApprovedBy ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}`}>HR {r.hrApprovedBy ? '✓' : '–'}</span>
                          <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${r.hosApprovedBy ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}`}>HOS {r.hosApprovedBy ? '✓' : '–'}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap"
                          style={{ color: sc.color, background: sc.bg }}>{sc.label}</span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        {r.currentStage === 'Finance' ? (
                          <div className="flex items-center justify-end gap-1">
                            <button onClick={() => handleApprove(r.id)}
                              className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-green-50 text-green-700 hover:bg-green-100 cursor-pointer text-xs font-semibold whitespace-nowrap">
                              <i className="ri-check-line"></i> Approve Budget
                            </button>
                            <button onClick={() => { setRejectModal(r.id); setRejectReason(''); }}
                              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>
                        ) : r.currentStage === 'Complete' ? (
                          <button onClick={() => downloadApprovalLetter(r)}
                            className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-semibold text-white cursor-pointer whitespace-nowrap"
                            style={{ background: BRAND }}>
                            <i className="ri-download-line"></i> Letter
                          </button>
                        ) : <span className="text-xs text-gray-400 italic">{sc.label}</span>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {viewProgram && (
        <ProgramViewModal program={viewProgram} onClose={() => setViewProgram(null)} />
      )}

      {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 Training Budget</h3>
            <p className="text-sm text-gray-500 mb-4">Provide reason for rejection (required).</p>
            <textarea value={rejectReason} onChange={e => setRejectReason(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={!rejectReason}
                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>
      )}
    </FinanceLayout>
  );
}
