'use client';
import { useState } from 'react';
import HODLayout from '../../../components/HODLayout';
import { useAuth } from '../../../lib/authContext';
import { useLeaveStore } from '../../../lib/leaveStore';
import { useTrainingStore } from '../../../lib/trainingStore';
import { LEAVE_POLICIES } from '../../hr/leave/leaveData';

type HistoryTab = 'leave' | 'training';

const STATUS_CONFIG: Record<string, { color: string; bg: string }> = {
  Pending: { color: '#d97706', bg: '#fef3c7' },
  'HOD Approved': { color: '#2563eb', bg: '#dbeafe' },
  'HOS Approved': { color: '#059669', bg: '#d1fae5' },
  Approved: { color: '#16a34a', bg: '#dcfce7' },
  Rejected: { color: '#dc2626', bg: '#fee2e2' },
};

const BRAND = '#B22698';

const TRAINING_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 HODHistoryPage() {
  const { user } = useAuth();

  if (!user) return null;

  const { requests } = useLeaveStore();
  const { trainingReqs } = useTrainingStore();
  const [filter, setFilter] = useState('All');
  const [historyTab, setHistoryTab] = useState<HistoryTab>('leave');
  const [search, setSearch] = useState('');

  const deptRequests = requests.filter(r => r.dept === user.dept && r.status !== 'Pending');
  const filtered = (filter === 'All' ? deptRequests : deptRequests.filter(r => r.status === filter))
    .filter(r => !search || r.employee.toLowerCase().includes(search.toLowerCase()));

  const deptTraining = trainingReqs.filter(r => r.dept === user.dept);
  const filteredTraining = deptTraining.filter(r => !search || r.employeeName.toLowerCase().includes(search.toLowerCase()) || r.courseRequested.toLowerCase().includes(search.toLowerCase()));

  const leaveStats = {
    total: deptRequests.length,
    approved: deptRequests.filter(r => r.status === 'Approved').length,
    rejected: deptRequests.filter(r => r.status === 'Rejected').length,
    pending: deptRequests.filter(r => r.status === 'HOD Approved' || r.status === 'HOS Approved').length,
  };

  const trainingStats = {
    total: deptTraining.length,
    approved: deptTraining.filter(r => r.currentStage === 'Complete').length,
    rejected: deptTraining.filter(r => r.currentStage === 'Rejected').length,
    pending: deptTraining.filter(r => !['Complete', 'Rejected'].includes(r.currentStage)).length,
  };

  return (
    <HODLayout title="Approval History">
      <div className="space-y-5">
        <div>
          <h2 className="text-lg font-bold text-gray-800">Approval History — {user.dept}</h2>
          <p className="text-sm text-gray-500">Complete record of all processed requests with timestamps and approver details</p>
        </div>

        <div className="grid grid-cols-4 gap-4">
          {[
            { label: 'Total Processed', value: historyTab === 'leave' ? leaveStats.total : trainingStats.total, color: '#B22698', icon: 'ri-file-list-3-line' },
            { label: 'Approved', value: historyTab === 'leave' ? leaveStats.approved : trainingStats.approved, color: '#16a34a', icon: 'ri-checkbox-circle-line' },
            { label: 'Rejected', value: historyTab === 'leave' ? leaveStats.rejected : trainingStats.rejected, color: '#dc2626', icon: 'ri-close-circle-line' },
            { label: 'In Progress', value: historyTab === 'leave' ? leaveStats.pending : trainingStats.pending, color: '#d97706', icon: 'ri-time-line' },
          ].map(s => (
            <div key={s.label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
              <div className="w-9 h-9 rounded-xl flex items-center justify-center mb-2" style={{ background: s.color + '15' }}>
                <i className={`${s.icon} text-base`} style={{ color: s.color }}></i>
              </div>
              <p className="text-2xl font-bold text-gray-800">{s.value}</p>
              <p className="text-xs text-gray-500 mt-0.5">{s.label}</p>
            </div>
          ))}
        </div>

        <div className="flex items-center justify-between flex-wrap gap-3">
          <div className="flex gap-1 bg-white rounded-xl border border-gray-100 shadow-sm p-1">
            {[{ id: 'leave', label: 'Leave History', icon: 'ri-calendar-check-line' }, { id: 'training', label: 'Training History', icon: 'ri-graduation-cap-line' }].map(t => (
              <button key={t.id} onClick={() => { setHistoryTab(t.id as HistoryTab); setFilter('All'); setSearch(''); }}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap transition-all ${historyTab === t.id ? 'text-white' : 'text-gray-500 hover:bg-gray-50'}`}
                style={historyTab === t.id ? { background: BRAND } : {}}>
                <i className={t.icon}></i> {t.label}
              </button>
            ))}
          </div>
          <div className="relative">
            <i className="ri-search-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search..."
              className="pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm outline-none w-48" />
          </div>
        </div>

        {historyTab === 'leave' && (
          <>
            <div className="flex gap-2 flex-wrap">
              {['All', 'HOD Approved', 'HOS Approved', 'Approved', 'Rejected'].map(s => (
                <button key={s} onClick={() => setFilter(s)}
                  className="px-3 py-1.5 rounded-full text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
                  style={filter === s ? { background: BRAND, color: '#fff' } : { background: '#f3f4f6', color: '#4b5563' }}>
                  {s}
                </button>
              ))}
            </div>

            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
              {filtered.length === 0 ? (
                <div className="py-16 text-center text-gray-400">
                  <i className="ri-history-line text-5xl block mb-3 text-gray-200"></i>
                  <p className="text-sm">No leave history found</p>
                </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">Leave Type</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Period</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">HOD Action</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">HOS Action</th>
                        <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">HR Final</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filtered.map(req => {
                        const st = STATUS_CONFIG[req.status] || STATUS_CONFIG['Pending'];
                        const policy = LEAVE_POLICIES.find(p => p.type === req.type);
                        return (
                          <tr key={req.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                            <td className="px-5 py-3">
                              <div className="flex items-center gap-2">
                                <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: BRAND }}>
                                  {req.employee.split(' ').map((n: string) => n[0]).join('').slice(0, 2)}
                                </div>
                                <div>
                                  <p className="font-medium text-gray-800">{req.employee}</p>
                                  <p className="text-xs text-gray-400 font-mono">{req.id}</p>
                                </div>
                              </div>
                            </td>
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-1.5">
                                <div className="w-2 h-2 rounded-full" style={{ background: policy?.color }}></div>
                                <span className="text-gray-700 text-sm">{policy?.label}</span>
                              </div>
                            </td>
                            <td className="px-4 py-3 text-xs text-gray-600">
                              <p>{req.startDate} → {req.endDate}</p>
                              <p className="text-gray-400">{req.days} day(s)</p>
                            </td>
                            <td className="px-4 py-3">
                              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-semibold whitespace-nowrap"
                                style={{ color: st.color, background: st.bg }}>{req.status}</span>
                            </td>
                            <td className="px-4 py-3 text-xs">
                              {req.hodApprovedBy ? (
                                <div className="text-green-700">
                                  <i className="ri-check-line mr-1"></i>
                                  <span>{req.hodApprovedOn}</span>
                                  <p className="text-gray-400">{req.hodApprovedBy?.split('(')[0]?.trim()}</p>
                                </div>
                              ) : req.rejectedStage === 'HOD' ? (
                                <span className="text-red-600"><i className="ri-close-line mr-1"></i>Rejected</span>
                              ) : <span className="text-gray-300">—</span>}
                            </td>
                            <td className="px-4 py-3 text-xs">
                              {req.hosApprovedBy ? (
                                <div className="text-green-700">
                                  <i className="ri-check-line mr-1"></i>{req.hosApprovedOn}
                                </div>
                              ) : req.rejectedStage === 'HOS' ? (
                                <span className="text-red-600"><i className="ri-close-line mr-1"></i>Rejected</span>
                              ) : <span className="text-gray-300">—</span>}
                            </td>
                            <td className="px-4 py-3 text-xs">
                              {req.approvedBy ? (
                                <div className="text-green-700">
                                  <i className="ri-checkbox-circle-line mr-1"></i>{req.approvedOn}
                                </div>
                              ) : req.rejectedStage === 'HR' ? (
                                <span className="text-red-600"><i className="ri-close-line mr-1"></i>Rejected</span>
                              ) : <span className="text-gray-300">Pending</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 {deptRequests.length} leave records</p>
              </div>
            </div>
          </>
        )}

        {historyTab === 'training' && (
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            {filteredTraining.length === 0 ? (
              <div className="py-16 text-center text-gray-400">
                <i className="ri-graduation-cap-line text-5xl block mb-3 text-gray-200"></i>
                <p className="text-sm">No training history found</p>
              </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">Course</th>
                      <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Dates</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">Stage</th>
                      <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Approval Trail</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredTraining.map(r => {
                      const sc = TRAINING_STAGE_CONFIG[r.currentStage] || TRAINING_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">
                            <div className="flex items-center gap-2">
                              <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: BRAND }}>
                                {r.employeeName.split(' ').map((n: string) => n[0]).join('').slice(0, 2)}
                              </div>
                              <div>
                                <p className="font-medium text-gray-800">{r.employeeName}</p>
                                <p className="text-xs text-gray-400 font-mono">{r.id}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <p className="text-sm font-medium text-gray-800 max-w-[180px] truncate">{r.courseRequested}</p>
                            <p className="text-xs text-gray-400">Submitted {r.dateSubmitted}</p>
                          </td>
                          <td className="px-4 py-3 text-xs text-gray-600">
                            <p>{r.preferredStartDate}</p>
                            <p className="text-gray-400">→ {r.preferredEndDate}</p>
                          </td>
                          <td className="px-4 py-3 text-right font-semibold text-gray-800">{r.estimatedCost.toLocaleString()}</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">
                            <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-pink-100 text-pink-700' : 'bg-gray-100 text-gray-400'}`}>HOS {r.hosApprovedBy ? '✓' : '–'}</span>
                              <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${r.financeApprovedBy ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}`}>Finance {r.financeApprovedBy ? '✓' : '–'}</span>
                            </div>
                          </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 {filteredTraining.length} of {deptTraining.length} training records</p>
            </div>
          </div>
        )}
      </div>
    </HODLayout>
  );
}
