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

const BRAND = '#B22698';

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

export default function HODOwnLeavePage() {
  const { user } = useAuth();
  const { requests, updateRequests } = useLeaveStore();
  
  const [showForm, setShowForm] = useState(false);
  const [toast, setToast] = useState('');
  const [form, setForm] = useState({ type: 'Annual', startDate: '', endDate: '', reason: '', dutyDelegate: '', dutyDelegateOther: '' });
  const [errors, setErrors] = useState<Record<string, string>>();
  const [docFile, setDocFile] = useState('');
  const [viewAppForm, setViewAppForm] = useState<LeaveRequest | null>(null);

  if (!user) return null;

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

  const hodId = `HOD-${user.id}`;
  const myRequests = requests.filter(r => r.employeeId === hodId);
  const gender = (user.gender || 'Male') as 'Male' | 'Female';
  const availableTypes = getAvailableLeaveTypes(gender);
  const minStart = getMinStartDate(form.type as any);

  const days = calculateDays(form.startDate, form.endDate);
  const balance = computeEmployeeBalance(hodId, 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 deptEmployees = EMPLOYEES.filter(e => e.dept === user.dept && e.employeeType === 'Employee');

  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 = 'Start date 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 (!form.dutyDelegate) newErrors.dutyDelegate = 'Please select an employee to delegate your duties to during your absence.';
    if (form.dutyDelegate === 'other' && !form.dutyDelegateOther.trim()) newErrors.dutyDelegateOther = 'Please specify who will perform your duties during your absence.';
    if (Object.keys(newErrors).length > 0) { setErrors(newErrors); return; }

    const delegateName = form.dutyDelegate === 'other' ? form.dutyDelegateOther : form.dutyDelegate;

    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: hodId,
      employee: user.name,
      dept: user.dept || 'Management',
      position: user.position || 'Head of Department',
      employeeType: 'Employee',
      gender,
      type: form.type as any,
      startDate: form.startDate,
      endDate: form.endDate,
      days,
      reason: form.reason,
      status: 'Pending HOS Approval',
      submittedOn: new Date().toISOString().split('T')[0],
      hodApprovedBy: `${user.name} (Self — HOD)`,
      hodApprovedOn: new Date().toISOString().split('T')[0],
      dutyDelegate: delegateName,
    };
    updateRequests(prev => [newReq, ...prev]);
    setShowForm(false);
    setForm({ type: 'Annual', startDate: '', endDate: '', reason: '', dutyDelegate: '', dutyDelegateOther: '' });
    setErrors({});
    setDocFile('');
    showToast('Leave request submitted. Forwarded to HOS for approval.');
  };

  return (
    <HODLayout 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">As HOD, your requests go directly to HOS for approval</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 Leave Request
          </button>
        </div>

        <div className="rounded-xl px-4 py-3 flex items-start gap-2 border" style={{ background: '#fce7f3', borderColor: BRAND }}>
          <i className="ri-information-line mt-0.5" style={{ color: BRAND }}></i>
          <p className="text-xs" style={{ color: BRAND }}>As HOD, your own leave requests are automatically forwarded to <strong>HOS</strong> for approval.</p>
        </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} 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 font-medium">{days} day(s) selected</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 for leave..."
                    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 className="md:col-span-2">
                <label className="block text-xs font-semibold text-gray-600 mb-1.5">Duty Delegation During Absence *</label>
                <p className="text-xs text-gray-500 mb-2">Select an employee from your department to be responsible for your duties during your absence</p>
                <div className="space-y-2">
                  {deptEmployees.map(c => (
                    <button
                      key={c.id}
                      onClick={() => setForm(f => ({ ...f, dutyDelegate: c.name, dutyDelegateOther: '' }))}
                      className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border text-sm cursor-pointer transition-all"
                      style={form.dutyDelegate === c.name ? { background: '#fdf4ff', borderColor: '#b828a0', color: '#b828a0' } : { background: '#fff', borderColor: '#e5e7eb', color: '#4b5563' }}
                    >
                      <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: '#b828a0' }}>
                        {c.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                      </div>
                      <div className="text-left">
                        <p className="font-medium">{c.name}</p>
                        <p className="text-xs text-gray-400">{c.position}</p>
                      </div>
                      {form.dutyDelegate === c.name && <i className="ri-check-line ml-auto"></i>}
                    </button>
                  ))}
                  <button
                    onClick={() => setForm(f => ({ ...f, dutyDelegate: 'other' }))}
                    className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border text-sm cursor-pointer transition-all"
                    style={form.dutyDelegate === 'other' ? { background: '#fdf4ff', borderColor: '#b828a0', color: '#b828a0' } : { background: '#fff', borderColor: '#e5e7eb', color: '#4b5563' }}
                  >
                    <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold bg-gray-400">
                      <i className="ri-add-line"></i>
                    </div>
                    <span className="font-medium">Other (specify)</span>
                    {form.dutyDelegate === 'other' && <i className="ri-check-line ml-auto"></i>}
                  </button>
                </div>
                {form.dutyDelegate === 'other' && (
                  <div className="mt-2">
                    <input
                      type="text"
                      value={form.dutyDelegateOther}
                      onChange={e => setForm(f => ({ ...f, dutyDelegateOther: e.target.value }))}
                      placeholder="Enter name of person who will perform your duties..."
                      className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none"
                    />
                  </div>
                )}
                {errors?.dutyDelegate && <p className="text-xs text-red-500 mt-1">{errors.dutyDelegate}</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 HOS</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 submitted 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>
                    <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {myRequests.map(r => {
                    const st = STATUS_CONFIG[r.status] || STATUS_CONFIG['Pending'];
                    const policy = LEAVE_POLICIES.find(p => p.type === r.type);
                    const showActions = (r.status === 'Approved' || r.status === 'HOS Approved');
                    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: policy?.color }}></div>
                            <span className="font-medium text-gray-700">{policy?.label}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-600">
                          <p>{r.startDate}</p>
                          <p className="text-gray-400">to {r.endDate}</p>
                        </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 items-center 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>
                        <td className="px-4 py-3 text-right">
                          {showActions ? (
                            <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>
                              <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>
                          ) : (
                            <span className="text-xs text-gray-400 italic">Awaiting Approval</span>
                          )}
                        </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={user.name}
          hosName={viewAppForm.hosApprovedBy?.split('(')[0]?.trim()}
          onClose={() => setViewAppForm(null)}
        />
      )}
    </HODLayout>
  );
}