'use client';
import { useState } from 'react';
import HOSLayout from '../../../components/HOSLayout';
import { useAuth } from '../../../lib/authContext';
import { useLeaveStore } from '../../../lib/leaveStore';
import {
  LEAVE_POLICIES, LeaveRequest,
  getMinStartDate, calculateDays, getAvailableLeaveTypes, computeEmployeeBalance
} from '../../hr/leave/leaveData';
import LeaveApplicationViewModal from '../../hr/leave/LeaveApplicationViewModal';
import { downloadLeaveComputationForm } from '../../../lib/leaveComputationForm';

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' },
};

const BRAND = '#B22698';

export default function HOSOwnLeavePage() {
  // ========== ALL HOOKS FIRST (before any conditional returns) ==========
  const { user } = useAuth();
  const leaveStore = useLeaveStore();  // ← MOVED HERE - before conditional return
  const requests = leaveStore?.requests || [];
  const updateRequests = leaveStore?.updateRequests;

  // All useState hooks
  const [showForm, setShowForm] = useState(false);
  const [toast, setToast] = useState('');
  const [form, setForm] = useState({ type: 'Annual', startDate: '', endDate: '', reason: '' });
  const [errors, setErrors] = useState<Record<string, string>>();
  const [docFile, setDocFile] = useState('');
  const [viewAppForm, setViewAppForm] = useState<LeaveRequest | null>(null);

  // ========== CONDITIONAL RETURN AFTER ALL HOOKS ==========
  if (!user) return null;

  // ========== DERIVED VALUES (after conditional return) ==========
  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3500); };
  const hosId = `HOS-${user.id}`;
  const myRequests = Array.isArray(requests) ? requests.filter(r => r && r.employeeId === hosId) : [];
  const gender = (user as any).gender || 'Male';
  const availableTypes = getAvailableLeaveTypes(gender);
  const minStart = getMinStartDate(form.type as any);
  const days = calculateDays(form?.startDate || '', form?.endDate || '');
  const balance = computeEmployeeBalance(hosId, form.type as any, false, requests);
  const policy = LEAVE_POLICIES.find(p => p.type === form.type);
  const isDocMandatory = form.type === 'Sick' || form.type === 'Maternity';
  const showDocumentSection = form.type === 'Sick' || form.type === 'Maternity';
  const showReasonField = form.type !== 'Annual';
  const maxDaysAllowed = Math.min(balance.remaining || 0, policy?.entitlement || 0);

  const handleSubmit = () => {
    const newErrors: Record<string, string> = {};
    if (!form?.startDate) newErrors.startDate = 'Start date required';
    else if (form.type !== 'Sick' && form.type !== 'Bereavement' && form.startDate < minStart) newErrors.startDate = 'Must be at least 14 days from today';
    if (!form?.endDate) newErrors.endDate = 'End date required';
    else if (form.endDate < form.startDate) newErrors.endDate = 'End date must be after start date';
    else if (days > maxDaysAllowed) newErrors.endDate = `Days requested (${days}) exceed remaining balance (${balance.remaining} days) or entitlement (${policy?.entitlement} days). Max allowed: ${maxDaysAllowed} days.`;
    if (showReasonField && !form?.reason?.trim()) newErrors.reason = 'Reason required';
    if (isDocMandatory && !docFile) newErrors.document = 'Supporting document is mandatory for Sick/Maternity leave';
    if (Object.keys(newErrors).length > 0) { setErrors(newErrors); return; }

    const newReq: LeaveRequest = {
      id: (() => {
        const maxNum = requests.reduce((max, r) => {
          const match = r.id.match(/^LV(?:-HOS-)?(\d+)$/);
          return match ? Math.max(max, parseInt(match[1], 10)) : max;
        }, 0);
        return `LV${String(maxNum + 1).padStart(3, '0')}`;
      })(),
      employeeId: hosId,
      employee: user.name || 'HOS User',
      dept: 'Secretariat',
      position: user.position || 'Head of Secretariat',
      employeeType: 'Employee',
      gender: gender as 'Male' | 'Female',
      type: form.type as any,
      startDate: form?.startDate || '',
      endDate: form?.endDate || '',
      days,
      reason: form?.reason || '',
      status: 'HOS Approved',
      submittedOn: new Date().toISOString().split('T')[0],
      hosApprovedBy: `${user.name || 'HOS User'} (Self — HOS)`,
      hosApprovedOn: new Date().toISOString().split('T')[0],
    };
    if (leaveStore && updateRequests) {
      updateRequests(prev => [newReq, ...prev]);
    }
    setShowForm(false);
    setForm({ type: 'Annual', startDate: '', endDate: '', reason: '' });
    setDocFile('');
    setErrors({});
    showToast('Request submitted. Forwarded to HR for final approval.');
  };

  return (
    <HOSLayout title="My Leave">
      {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">My Leave Requests</h2>
            <p className="text-sm text-gray-500">Your own requests go directly to HR (bypassing HOD and HOS steps)</p>
          </div>
          <button onClick={() => setShowForm(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: BRAND }}>
            <i className="ri-add-line"></i> New Request
          </button>
        </div>

        {showForm && (
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6">
            <h3 className="font-bold text-gray-800 mb-4">New Leave Request</h3>
            <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={form?.type || 'Annual'} onChange={e => setForm(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={form?.startDate || ''} onChange={e => setForm(f => ({ ...f, startDate: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" />
                {errors?.startDate && <p className="text-xs text-red-500 mt-1">{errors.startDate}</p>}
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1.5">End Date</label>
                <input type="date"
                  value={form?.endDate || ''} onChange={e => setForm(f => ({ ...f, endDate: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" />
                {errors?.endDate && <p className="text-xs text-red-500 mt-1">{errors.endDate}</p>}
                {days > 0 && <p className="text-xs text-green-600 mt-1">{days} day(s)</p>}
                {days > maxDaysAllowed && <p className="text-xs text-red-500 mt-1">Maximum allowed: {maxDaysAllowed} days (remaining: {balance?.remaining}, entitlement: {policy?.entitlement})</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={form?.reason || ''} onChange={e => setForm(f => ({ ...f, reason: e.target.value }))} rows={3}
                    placeholder="State your reason..." className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" />
                  {errors?.reason && <p className="text-xs text-red-500 mt-1">{errors.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>}
                  {errors?.document && <p className="text-xs text-red-500 mt-1">{errors.document}</p>}
                  {isDocMandatory && !docFile && <p className="text-xs text-red-500 mt-1">Sick and Maternity leave require supporting documents</p>}
                </div>
              )}
            </div>
            <div className="flex gap-3 mt-4">
              <button onClick={() => setShowForm(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={handleSubmit}
                className="px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: BRAND }}>Submit to HR</button>
            </div>
          </div>
        )}

        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100"><h3 className="font-semibold text-gray-700">My Leave History</h3></div>
          {myRequests.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">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-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {myRequests.filter(Boolean).map(r => {
                    const st = STATUS_CONFIG[r?.status] || STATUS_CONFIG['Pending'];
                    const policy = LEAVE_POLICIES.find(p => p.type === r?.type);
                    return (
                      <tr key={r?.id || Math.random()} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3 font-medium text-gray-700">{policy?.label}</td>
                        <td className="px-4 py-3 text-xs text-gray-600">{r?.startDate || ''} to {r?.endDate || ''}</td>
                        <td className="px-4 py-3 text-center font-bold text-gray-800">{r?.days || 0}</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-right">
                          <div className="flex items-center justify-end gap-1">
                            <button onClick={() => setViewAppForm(r)} title="View Application Form"
                              className="w-7 h-7 flex items-center justify-center rounded-lg bg-blue-50 text-blue-500 hover:bg-blue-100 cursor-pointer">
                              <i className="ri-eye-line text-sm"></i>
                            </button>
                            {(r.status === 'Approved' || r.status === 'HOS Approved') && (
                              <button onClick={() => downloadLeaveComputationForm(r)} title="Download Computation Form"
                                className="flex items-center gap-1 px-2 py-1 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 cursor-pointer text-xs font-medium whitespace-nowrap">
                                <i className="ri-file-text-line"></i> Computation
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {viewAppForm && (
        <LeaveApplicationViewModal
          request={viewAppForm}
          allRequests={requests}
          stage={viewAppForm.status === 'Approved' ? 'full' : viewAppForm.status === 'HOS Approved' ? 'part2' : 'part1'}
          hodName={viewAppForm.hodApprovedBy?.split('(')[0]?.trim()}
          hosName={user.name || 'HOS User'}
          onClose={() => setViewAppForm(null)}
        />
      )}
    </HOSLayout>
  );
}