'use client';
import { useState } from 'react';
import HOSLayout from '../../../components/HOSLayout';
import { useLeaveStore } from '../../../lib/leaveStore';
import { LEAVE_POLICIES } from '../../hr/leave/leaveData';

const BRAND = '#B22698';

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

export default function HOSAuditPage() {
  const { requests } = useLeaveStore();
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('All');

  const allProcessed = requests.filter(r => r.status !== 'Pending');
  const filtered = allProcessed.filter(r => {
    const fs = statusFilter === 'All' || r.status === statusFilter;
    const fq = !search || r.employee.toLowerCase().includes(search.toLowerCase()) || r.id.toLowerCase().includes(search.toLowerCase());
    return fs && fq;
  });

  const stats = [
    { label: 'Total Processed', value: allProcessed.length, color: '#6b7280', bg: '#f3f4f6' },
    { label: 'HOD Approved', value: allProcessed.filter(r => r.status === 'HOD Approved').length, color: '#2563eb', bg: '#dbeafe' },
    { label: 'HOS Approved', value: allProcessed.filter(r => r.status === 'HOS Approved').length, color: BRAND, bg: '#fce7f3' },
    { label: 'Fully Approved', value: allProcessed.filter(r => r.status === 'Approved').length, color: '#16a34a', bg: '#dcfce7' },
    { label: 'Rejected', value: allProcessed.filter(r => r.status === 'Rejected').length, color: '#dc2626', bg: '#fee2e2' },
  ];

  return (
    <HOSLayout title="Audit Trail">
      <div className="space-y-5">
        <div>
          <h2 className="text-lg font-bold text-gray-800">Full Audit Trail</h2>
          <p className="text-sm text-gray-500">Complete history of all leave requests and approver actions with timestamps</p>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
          {stats.map(s => (
            <div key={s.label} className="bg-white rounded-xl border border-gray-100 p-3 text-center shadow-sm">
              <p className="text-xl font-bold" style={{ color: s.color }}>{s.value}</p>
              <p className="text-xs text-gray-500 mt-0.5">{s.label}</p>
            </div>
          ))}
        </div>

        <div className="flex flex-wrap gap-3 items-center">
          <div className="relative flex-1 min-w-[200px]">
            <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 employee or ID..."
              className="pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm w-full outline-none" />
          </div>
          <div className="flex gap-2 flex-wrap">
            {['All', 'HOD Approved', 'HOS Approved', '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}
              </button>
            ))}
          </div>
        </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">Request ID</th>
                  <th className="text-left px-4 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">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>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 && (
                  <tr><td colSpan={8} className="text-center py-12 text-gray-400">No records found</td></tr>
                )}
                {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 font-mono text-xs text-gray-500">{req.id}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 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 text-xs">{req.employee}</p>
                            <p className="text-xs text-gray-400">{req.dept}</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-xs">{policy?.label}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-600">
                        {req.startDate} → {req.endDate}<br />
                        <span className="text-gray-400">{req.days} day(s)</span>
                      </td>
                      <td className="px-4 py-3 text-xs">
                        {req.hodApprovedBy ? (
                          <div style={{ color: BRAND }}>
                            <i className="ri-check-line mr-0.5"></i>{req.hodApprovedOn}
                            <p className="text-gray-400 text-xs">{req.hodApprovedBy?.split('(')[0]?.trim()}</p>
                          </div>
                        ) : req.rejectedStage === 'HOD' ? (
                          <span className="text-red-600 text-xs"><i className="ri-close-line mr-0.5"></i>Rejected</span>
                        ) : <span className="text-gray-300">—</span>}
                      </td>
                      <td className="px-4 py-3 text-xs">
                        {req.hosApprovedBy ? (
                          <div style={{ color: BRAND }}>
                            <i className="ri-check-double-line mr-0.5"></i>{req.hosApprovedOn}
                            <p className="text-gray-400 text-xs">{req.hosApprovedBy?.split('(')[0]?.trim()}</p>
                            {(req as any).hosComment && (
                              <p className="text-gray-400 italic text-xs">"{(req as any).hosComment}"</p>
                            )}
                          </div>
                        ) : req.rejectedStage === 'HOS' ? (
                          <span className="text-red-600 text-xs"><i className="ri-close-line mr-0.5"></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-0.5"></i>{req.approvedOn}
                          </div>
                        ) : req.rejectedStage === 'HR' ? (
                          <span className="text-red-600 text-xs"><i className="ri-close-line mr-0.5"></i>Rejected</span>
                        ) : <span className="text-gray-300">Pending HR</span>}
                      </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: st.color, background: st.bg }}>{req.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 {allProcessed.length} records</p>
          </div>
        </div>
      </div>
    </HOSLayout>
  );
}