'use client';
import { useState } from 'react';
import HRLayout from '../../../components/HRLayout';
import { useAuth } from '../../../lib/authContext';
import { useLeaveStore } from '../../../lib/leaveStore';
import { LeaveRequest, LEAVE_POLICIES, getAvailableLeaveTypes, computeEmployeeBalance, getMinStartDate, calculateDays } from './leaveData';
import LeaveStatsBar from './LeaveStatsBar';
import LeaveRequestsTab from './LeaveRequestsTab';
import LeaveBalanceTab from './LeaveBalanceTab';
import LeaveCalendarTab from './LeaveCalendarTab';
import LeavePolicyTab from './LeavePolicyTab';
import LeaveReportsTab from './LeaveReportsTab';
import HRStampSection from './HRStampSection';

type TabKey = 'requests' | 'balances' | 'calendar' | 'policy' | 'reports' | 'my-leave' | 'stamp';

const TABS: { key: TabKey; label: string; icon: string }[] = [
  { key: 'requests', label: 'Leave Requests', icon: 'ri-file-list-3-line' },
  { key: 'my-leave', label: 'My Leave', icon: 'ri-user-heart-line' },
  { key: 'balances', label: 'Leave Balances', icon: 'ri-wallet-3-line' },
  { key: 'calendar', label: 'Calendar', icon: 'ri-calendar-2-line' },
  { key: 'policy', label: 'Leave Policy', icon: 'ri-settings-3-line' },
  { key: 'reports', label: 'Reports', icon: 'ri-bar-chart-2-line' },
  { key: 'stamp', label: 'Stamp & Signature', icon: 'ri-mark-pen-line' },
];

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

export default function LeaveContent() {
  const { user } = useAuth();
  const { requests, setRequests, updateRequests } = useLeaveStore();
  const [activeTab, setActiveTab] = useState<TabKey>('requests');
  const [toast, setToast] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);
  const [showNewLeave, setShowNewLeave] = useState(false);
  const [leaveForm, setLeaveForm] = useState({ type: 'Annual', startDate: '', endDate: '', reason: '' });
  const [leaveErrors, setLeaveErrors] = useState<Record<string, string>>({});
  const [docFile, setDocFile] = useState('');

  const isAdmin = user?.role === 'admin';
  const canEditPolicy = user?.role === 'admin' || user?.role === 'hr';

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 3000);
  };

  const pendingCount = requests.filter(r => r.status === 'Pending' || r.status === 'HOS Approved').length;

  const hrId = `HR-${user?.id || 'hr001'}`;
  const hrGender: 'Male' | 'Female' = (user?.gender as 'Male' | 'Female') || 'Female';
  const availableTypes = getAvailableLeaveTypes(hrGender);
  const minStart = getMinStartDate(leaveForm.type as any);
  const days = calculateDays(leaveForm.startDate, leaveForm.endDate);
  const balance = computeEmployeeBalance(hrId, leaveForm.type as any, false, requests);
  const policy = LEAVE_POLICIES.find(p => p.type === leaveForm.type);
  const isDocMandatory = leaveForm.type === 'Sick' || leaveForm.type === 'Maternity';
  const showDocumentSection = leaveForm.type === 'Sick' || leaveForm.type === 'Maternity';
  const showReasonField = leaveForm.type !== 'Annual';
  const maxDaysAllowed = Math.min(balance.remaining || 0, policy?.entitlement || 0);

  const myLeaveRequests = requests.filter(r => r.employeeId === hrId);

  const handleSubmitLeave = () => {
    const errs: Record<string, string> = {};
    if (!leaveForm.startDate) errs.startDate = 'Start date required';
    else if (leaveForm.type !== 'Sick' && leaveForm.type !== 'Bereavement' && leaveForm.startDate < minStart) errs.startDate = 'Must be at least 14 days from today';
    if (!leaveForm.endDate) errs.endDate = 'End date required';
    else if (leaveForm.endDate < leaveForm.startDate) errs.endDate = 'End date must be after start date';
    else if (days > maxDaysAllowed) errs.endDate = `Days (${days}) exceed max allowed (${maxDaysAllowed})`;
    if (showReasonField && !leaveForm.reason.trim()) errs.reason = 'Reason required';
    if (isDocMandatory && !docFile) errs.document = 'Supporting document required';
    if (Object.keys(errs).length > 0) { setLeaveErrors(errs); return; }

    const newReq: LeaveRequest = {
      id: (() => {
        const maxNum = requests.reduce((max, r) => {
          const match = r.id.match(/^LV(\d+)$/);
          return match ? Math.max(max, parseInt(match[1], 10)) : max;
        }, 0);
        return `LV${String(maxNum + 1).padStart(3, '0')}`;
      })(),
      employeeId: hrId,
      employee: user?.name || 'HR Manager',
      dept: 'HR',
      position: 'HR Manager',
      employeeType: 'Employee',
      gender: hrGender,
      type: leaveForm.type as any,
      startDate: leaveForm.startDate,
      endDate: leaveForm.endDate,
      days,
      reason: leaveForm.reason,
      status: 'Pending',
      submittedOn: new Date().toISOString().split('T')[0],
    };
    updateRequests(prev => [newReq, ...prev]);
    setShowNewLeave(false);
    setLeaveForm({ type: 'Annual', startDate: '', endDate: '', reason: '' });
    setLeaveErrors({});
    setDocFile('');
    showToast('Leave request submitted. Forwarded to HOS for approval.');
  };

  return (
    <HRLayout title="Leave Management" breadcrumb="HR">
      {toast && (
        <div className={`fixed top-5 right-5 z-[100] px-5 py-3 rounded-xl shadow-lg text-white text-sm font-medium flex items-center gap-2 transition-all
          ${toast.type === 'success' ? 'bg-green-600' : 'bg-red-600'}`}>
          <i className={toast.type === 'success' ? 'ri-checkbox-circle-line' : 'ri-close-circle-line'}></i>
          {toast.msg}
        </div>
      )}

      <LeaveStatsBar requests={requests} />

      <div className="flex items-center gap-1 flex-wrap mb-5 bg-white border border-gray-100 rounded-2xl px-2 py-2 shadow-sm">
        {TABS.map(tab => (
          <button key={tab.key} onClick={() => setActiveTab(tab.key)}
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium cursor-pointer whitespace-nowrap transition-all relative"
            style={activeTab === tab.key ? { background: '#b828a0', color: '#fff' } : { color: '#6b7280' }}>
            <i className={tab.icon}></i>
            {tab.label}
            {tab.key === 'requests' && pendingCount > 0 && (
              <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-amber-400 text-white text-xs flex items-center justify-center font-bold leading-none">
                {pendingCount}
              </span>
            )}
          </button>
        ))}
      </div>

      {activeTab === 'requests' && (
        <LeaveRequestsTab requests={requests} onUpdate={setRequests} showToast={showToast} isAdmin={isAdmin} />
      )}

      {activeTab === 'my-leave' && (
        <div className="space-y-5">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-bold text-gray-800">My Leave Requests</h3>
              <p className="text-sm text-gray-500">HR leave requests are approved by HOS/CEO</p>
            </div>
            <button onClick={() => setShowNewLeave(true)}
              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-add-line"></i> New Request
            </button>
          </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 HR Manager, your leave requests are forwarded directly to the <strong>Head of Secretariat (HOS/CEO)</strong> for approval. You cannot approve your own requests.</p>
          </div>

          {showNewLeave && (
            <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6">
              <h4 className="font-bold text-gray-800 mb-4">New Leave Request</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1.5">Leave Type</label>
                  <select value={leaveForm.type} onChange={e => setLeaveForm(f => ({ ...f, type: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                    {availableTypes.map(t => {
                      const p = LEAVE_POLICIES.find(pp => pp.type === t);
                      return <option key={t} value={t}>{p?.label || t}</option>;
                    })}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1.5">Start Date (min: {minStart})</label>
                  <input type="date" min={minStart} value={leaveForm.startDate} onChange={e => setLeaveForm(f => ({ ...f, startDate: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" />
                  {leaveErrors.startDate && <p className="text-xs text-red-500 mt-1">{leaveErrors.startDate}</p>}
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1.5">End Date</label>
                  <input type="date" value={leaveForm.endDate} onChange={e => setLeaveForm(f => ({ ...f, endDate: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" />
                  {leaveErrors.endDate && <p className="text-xs text-red-500 mt-1">{leaveErrors.endDate}</p>}
                  {days > 0 && <p className="text-xs text-green-600 mt-1">{days} day(s) selected</p>}
                </div>
                {showReasonField && (
                  <div className="md:col-span-2">
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5">Reason</label>
                    <textarea value={leaveForm.reason} onChange={e => setLeaveForm(f => ({ ...f, reason: e.target.value }))} rows={3}
                      placeholder="State your reason for leave..."
                      className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" />
                    {leaveErrors.reason && <p className="text-xs text-red-500 mt-1">{leaveErrors.reason}</p>}
                  </div>
                )}
                {showDocumentSection && (
                  <div className="md:col-span-2">
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5">Supporting Document <span className="text-red-500">*</span></label>
                    <label className={`border-2 border-dashed rounded-xl p-4 text-center hover:border-purple-300 transition-colors cursor-pointer block ${isDocMandatory && !docFile ? 'border-red-200 bg-red-50' : 'border-gray-200'}`}>
                      <div className="w-8 h-8 flex items-center justify-center mx-auto mb-1">
                        <i className="ri-upload-cloud-2-line text-2xl text-gray-400"></i>
                      </div>
                      <p className="text-xs text-gray-500">PDF, JPG, PNG up to 10MB</p>
                      <input type="file" accept=".pdf,.jpg,.png" className="hidden" onChange={e => setDocFile(e.target.files?.[0]?.name || '')} />
                    </label>
                    {docFile && <p className="text-xs text-green-600 mt-1"><i className="ri-check-line mr-1"></i>{docFile}</p>}
                    {leaveErrors.document && <p className="text-xs text-red-500 mt-1">{leaveErrors.document}</p>}
                  </div>
                )}
              </div>
              <div className="flex gap-3 mt-4">
                <button onClick={() => setShowNewLeave(false)}
                  className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                <button onClick={handleSubmitLeave}
                  className="px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
                  style={{ background: '#b828a0' }}>
                  Submit to HOS
                </button>
              </div>
            </div>
          )}

          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div className="px-5 py-3 border-b border-gray-100">
              <h4 className="font-semibold text-gray-700">My Leave History</h4>
            </div>
            {myLeaveRequests.length === 0 ? (
              <div className="py-12 text-center text-gray-400">
                <i className="ri-calendar-line text-4xl block mb-2"></i>
                <p className="text-sm">No leave requests yet</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">Leave Type</th>
                      <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Period</th>
                      <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Days</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">Submitted</th>
                    </tr>
                  </thead>
                  <tbody>
                    {myLeaveRequests.map(r => {
                      const st = STATUS_CONFIG[r.status] || STATUS_CONFIG['Pending'];
                      const pol = LEAVE_POLICIES.find(p => p.type === r.type);
                      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-2 h-2 rounded-full" style={{ background: pol?.color }}></div>
                              <span className="font-medium text-gray-700">{pol?.label}</span>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-xs text-gray-600">{r.startDate} → {r.endDate}</td>
                          <td className="px-4 py-3 text-center font-bold text-gray-800">{r.days}</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 }}>{r.status}</span>
                          </td>
                          <td className="px-4 py-3 text-xs text-gray-400">{r.submittedOn}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {activeTab === 'balances' && <LeaveBalanceTab />}
      {activeTab === 'calendar' && <LeaveCalendarTab requests={requests} />}
      {activeTab === 'policy' && <LeavePolicyTab canEdit={canEditPolicy} />}
      {activeTab === 'reports' && <LeaveReportsTab requests={requests} />}
      {activeTab === 'stamp' && <HRStampSection />}
    </HRLayout>
  );
}