'use client';
import { useState } from 'react';
import { LEAVE_POLICIES, LeavePolicy, PUBLIC_HOLIDAYS } from './leaveData';

interface Props {
  canEdit?: boolean;
}

export default function LeavePolicyTab({ canEdit = false }: Props) {
  const [policies, setPolicies] = useState<LeavePolicy[]>(LEAVE_POLICIES);
  const [editing, setEditing] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<Partial<LeavePolicy>>({});
  const [activeSection, setActiveSection] = useState<'policies' | 'holidays'>('policies');

  const startEdit = (p: LeavePolicy) => {
    setEditing(p.type);
    setEditForm({ ...p });
  };

  const saveEdit = () => {
    if (!editing) return;
    setPolicies(prev => prev.map(p => p.type === editing ? { ...p, ...editForm } as LeavePolicy : p));
    setEditing(null);
  };

  return (
    <div className="space-y-4">
      <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-3">
        <i className="ri-government-line text-blue-600 mt-0.5 text-lg"></i>
        <div className="text-xs text-blue-800">
          <strong>Uwezo Fund Leave Policy</strong> — Leave entitlements are aligned with Kenya Employment Act provisions. All leave must be applied for at least 14 days in advance (except sick/emergency leave) and approved by HR.
          {canEdit && <span className="ml-1 font-semibold text-blue-700">HR and Admin can edit policies below.</span>}
          {!canEdit && <span className="ml-1 text-blue-600">Policies are managed by HR and Admin only.</span>}
        </div>
      </div>

      <div className="flex items-center gap-1 bg-white border border-gray-200 rounded-xl px-1 py-1 w-fit">
        {(['policies', 'holidays'] as const).map(t => (
          <button key={t} onClick={() => setActiveSection(t)}
            className="px-4 py-1.5 rounded-lg text-sm font-medium cursor-pointer capitalize transition-all"
            style={activeSection === t ? { background: '#b828a0', color: '#fff' } : { color: '#6b7280' }}>
            {t === 'policies' ? 'Leave Policies' : 'Public Holidays'}
          </button>
        ))}
      </div>

      {activeSection === 'policies' && (
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
            <h4 className="font-semibold text-gray-700">Leave Types & Entitlements</h4>
            <span className="text-xs text-gray-400">{policies.length} leave types configured</span>
          </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-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Employee Entitlement</th>
                  <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Intern Entitlement</th>
                  <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Max Carryover</th>
                  <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Unpaid Allowed</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Notes</th>
                  {canEdit && <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>}
                </tr>
              </thead>
              <tbody>
                {policies.map(policy => (
                  <tr key={policy.type} className="border-b border-gray-50 hover:bg-gray-50/50">
                    {editing === policy.type && canEdit ? (
                      <td colSpan={canEdit ? 7 : 6} className="px-5 py-4">
                        <div className="grid grid-cols-4 gap-4 mb-3">
                          <div>
                            <label className="text-xs font-semibold text-gray-500 block mb-1">Entitlement (days)</label>
                            <input type="number" value={editForm.entitlement ?? ''} onChange={e => setEditForm(f => ({ ...f, entitlement: +e.target.value }))}
                              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                          </div>
                          <div>
                            <label className="text-xs font-semibold text-gray-500 block mb-1">Intern Entitlement (days)</label>
                            <input type="number" value={editForm.internEntitlement ?? ''} onChange={e => setEditForm(f => ({ ...f, internEntitlement: +e.target.value }))}
                              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                          </div>
                          <div>
                            <label className="text-xs font-semibold text-gray-500 block mb-1">Max Carryover (days)</label>
                            <input type="number" value={editForm.maxCarryover ?? ''} onChange={e => setEditForm(f => ({ ...f, maxCarryover: +e.target.value }))}
                              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                          </div>
                          <div>
                            <label className="text-xs font-semibold text-gray-500 block mb-1">Unpaid Allowed</label>
                            <select value={editForm.unpaidAllowed ? 'yes' : 'no'} onChange={e => setEditForm(f => ({ ...f, unpaidAllowed: e.target.value === 'yes' }))}
                              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none cursor-pointer pr-8">
                              <option value="no">No</option>
                              <option value="yes">Yes</option>
                            </select>
                          </div>
                          <div>
                            <label className="text-xs font-semibold text-gray-500 block mb-1">Notes</label>
                            <input type="text" value={editForm.notes ?? ''} onChange={e => setEditForm(f => ({ ...f, notes: e.target.value }))}
                              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                          </div>
                        </div>
                        <div className="flex gap-2">
                          <button onClick={saveEdit} className="px-4 py-1.5 rounded-lg text-sm font-semibold text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Save</button>
                          <button onClick={() => setEditing(null)} className="px-4 py-1.5 rounded-lg text-sm border border-gray-200 text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                        </div>
                      </td>
                    ) : (
                      <>
                        <td className="px-5 py-3">
                          <div className="flex items-center gap-2.5">
                            <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background: policy.color + '20' }}>
                              <i className={`${policy.icon} text-sm`} style={{ color: policy.color }}></i>
                            </div>
                            <span className="font-semibold text-gray-800">{policy.label}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <span className="inline-flex items-center justify-center w-12 h-7 rounded-full text-sm font-bold" style={{ background: policy.color + '15', color: policy.color }}>
                            {policy.entitlement === 0 ? '∞' : policy.entitlement}
                          </span>
                          {policy.entitlement > 0 && <span className="text-xs text-gray-400 ml-1">days</span>}
                        </td>
                        <td className="px-4 py-3 text-center">
                          {policy.internEntitlement !== undefined && (
                            <span className="inline-flex items-center justify-center w-12 h-7 rounded-full text-sm font-bold" style={{ background: '#f3e8ff', color: '#9333ea' }}>
                              {policy.internEntitlement === 0 ? '∞' : policy.internEntitlement}
                            </span>
                          )}
                          {policy.internEntitlement > 0 && <span className="text-xs text-gray-400 ml-1">days</span>}
                        </td>
                        <td className="px-4 py-3 text-center">
                          {policy.maxCarryover > 0 ? (
                            <span className="text-sm font-semibold text-gray-700">{policy.maxCarryover} days</span>
                          ) : (
                            <span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">None</span>
                          )}
                        </td>
                        <td className="px-4 py-3 text-center">
                          {policy.unpaidAllowed ? (
                            <span className="inline-flex items-center gap-1 text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full font-semibold">
                              <i className="ri-check-line"></i> Yes
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full">
                              <i className="ri-close-line"></i> No
                            </span>
                          )}
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-500 max-w-xs">{policy.notes}</td>
                        {canEdit && (
                          <td className="px-4 py-3 text-right">
                            <button onClick={() => startEdit(policy)}
                              className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 text-gray-400 cursor-pointer ml-auto">
                              <i className="ri-edit-line text-sm"></i>
                            </button>
                          </td>
                        )}
                      </>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeSection === 'holidays' && (
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
            <h4 className="font-semibold text-gray-700">Public Holidays 2026 — Kenya</h4>
          </div>
          <div className="divide-y divide-gray-50">
            {PUBLIC_HOLIDAYS.map(h => (
              <div key={h.date} className="flex items-center gap-4 px-5 py-3 hover:bg-gray-50/50">
                <div className="w-9 h-9 rounded-xl bg-red-50 flex items-center justify-center flex-shrink-0">
                  <i className="ri-calendar-event-line text-red-500"></i>
                </div>
                <div className="flex-1">
                  <p className="text-sm font-semibold text-gray-700">{h.name}</p>
                  <p className="text-xs text-gray-400">Kenya National Holiday</p>
                </div>
                <p className="text-sm font-mono text-gray-600">{h.date}</p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
