'use client';
import { useState } from 'react';
import { Category, initialCategories } from './gradingData';

function CategoryModal({ cat, onClose, onSave }: { cat?: Category | null; onClose: () => void; onSave: (c: Category) => void }) {
  const [form, setForm] = useState<Category>(cat || {
    id: `cat_${Date.now()}`, name: '', leaveDays: 10, benefitsEligible: false, probationMonths: 0,
    noticeDays: 14, contractRenewalDays: 30, benefits: [], color: '#b828a0', isCustom: true,
  });
  const [newBenefit, setNewBenefit] = useState('');
  const set = (k: keyof Category, v: any) => setForm(p => ({ ...p, [k]: v }));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg p-6 max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-base font-bold text-gray-800">{cat ? 'Edit Category' : 'Add Custom Category'}</h3>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer">
            <i className="ri-close-line text-gray-500"></i>
          </button>
        </div>
        <div className="space-y-4">
          <div>
            <label className="text-xs font-semibold text-gray-600 block mb-1">Category Name</label>
            <input value={form.name} onChange={e => set('name', e.target.value)} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" placeholder="e.g. Fixed Term" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-1">Leave Days / Year</label>
              <input type="number" value={form.leaveDays} onChange={e => set('leaveDays', +e.target.value)} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
            </div>
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-1">Probation Period (months)</label>
              <input type="number" value={form.probationMonths} onChange={e => set('probationMonths', +e.target.value)} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
            </div>
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-1">Notice Period (days)</label>
              <input type="number" value={form.noticeDays} onChange={e => set('noticeDays', +e.target.value)} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
            </div>
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-1">Renewal Reminder (days before)</label>
              <input type="number" value={form.contractRenewalDays} onChange={e => set('contractRenewalDays', +e.target.value)} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button onClick={() => set('benefitsEligible', !form.benefitsEligible)}
              className={`w-10 h-6 rounded-full transition-all cursor-pointer ${form.benefitsEligible ? '' : 'bg-gray-200'}`}
              style={form.benefitsEligible ? { background: '#b828a0' } : {}}>
              <div className={`w-4 h-4 bg-white rounded-full shadow transition-transform mx-1 ${form.benefitsEligible ? 'translate-x-4' : 'translate-x-0'}`}></div>
            </button>
            <label className="text-sm text-gray-700 font-medium">Benefits Eligible</label>
          </div>
          <div>
            <label className="text-xs font-semibold text-gray-600 block mb-2">Benefits Packages</label>
            <div className="flex flex-wrap gap-1.5 mb-2">
              {form.benefits.map((b, i) => (
                <span key={i} className="flex items-center gap-1 text-xs px-2.5 py-1 rounded-full bg-green-100 text-green-700">
                  {b}
                  <button onClick={() => set('benefits', form.benefits.filter((_, j) => j !== i))} className="cursor-pointer hover:text-red-500"><i className="ri-close-line text-xs"></i></button>
                </span>
              ))}
            </div>
            <div className="flex gap-2">
              <input value={newBenefit} onChange={e => setNewBenefit(e.target.value)} placeholder="Add benefit..." className="flex-1 border border-gray-200 rounded-xl px-3 py-2 text-sm outline-none focus:border-pink-400" onKeyDown={e => { if (e.key === 'Enter' && newBenefit.trim()) { set('benefits', [...form.benefits, newBenefit.trim()]); setNewBenefit(''); }}} />
              <button onClick={() => { if (newBenefit.trim()) { set('benefits', [...form.benefits, newBenefit.trim()]); setNewBenefit(''); }}} className="px-3 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Add</button>
            </div>
          </div>
        </div>
        <div className="flex gap-3 mt-6">
          <button onClick={onClose} className="flex-1 px-4 py-2.5 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">Cancel</button>
          <button onClick={() => { onSave(form); onClose(); }} className="flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
            {cat ? 'Save Changes' : 'Create Category'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default function CategoryMasterTab() {
  const [categories, setCategories] = useState<Category[]>(initialCategories);
  const [modal, setModal] = useState(false);
  const [editing, setEditing] = useState<Category | null>(null);
  const [expanded, setExpanded] = useState<string | null>('perm');

  const handleSave = (c: Category) => {
    if (editing) setCategories(cs => cs.map(x => x.id === c.id ? c : x));
    else setCategories(cs => [...cs, c]);
    setEditing(null);
  };

  return (
    <div>
      {modal && <CategoryModal cat={editing} onClose={() => { setModal(false); setEditing(null); }} onSave={handleSave} />}
      <div className="flex items-center justify-between mb-4">
        <div>
          <h3 className="text-sm font-bold text-gray-800">Employee Category Master List</h3>
          <p className="text-xs text-gray-500 mt-0.5">Define employment categories with default entitlements</p>
        </div>
        <button onClick={() => { setEditing(null); setModal(true); }} className="flex items-center gap-2 px-4 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line"></i></div>
          Add Custom Category
        </button>
      </div>
      <div className="space-y-3">
        {categories.map(cat => (
          <div key={cat.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm hover:-translate-y-0.5 transition-transform overflow-hidden">
            <div className="flex items-center justify-between px-5 py-4 cursor-pointer" onClick={() => setExpanded(expanded === cat.id ? null : cat.id)}>
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center text-white text-sm font-bold" style={{ background: cat.color }}>
                  {cat.name[0]}
                </div>
                <div>
                  <p className="text-sm font-bold text-gray-800">{cat.name}</p>
                  <p className="text-xs text-gray-500">{cat.leaveDays} leave days/yr · {cat.probationMonths ? `${cat.probationMonths}mo probation` : 'No probation'} · {cat.noticeDays}d notice</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                {cat.benefitsEligible && <span className="text-xs px-2.5 py-1 rounded-full bg-green-100 text-green-700 font-medium">Benefits Eligible</span>}
                {cat.isCustom && <span className="text-xs px-2.5 py-1 rounded-full bg-purple-100 text-purple-700 font-medium">Custom</span>}
                <button onClick={e => { e.stopPropagation(); setEditing(cat); setModal(true); }} className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer">
                  <i className="ri-edit-2-line text-blue-500 text-xs"></i>
                </button>
                <div className="w-5 h-5 flex items-center justify-center">
                  <i className={expanded === cat.id ? 'ri-arrow-up-s-line text-gray-400' : 'ri-arrow-down-s-line text-gray-400'}></i>
                </div>
              </div>
            </div>
            {expanded === cat.id && (
              <div className="px-5 pb-5 border-t border-gray-50">
                <div className="grid grid-cols-4 gap-3 mt-4 mb-4">
                  {[
                    { label: 'Leave Days/Year', value: `${cat.leaveDays} days`, icon: 'ri-calendar-line' },
                    { label: 'Probation Period', value: cat.probationMonths ? `${cat.probationMonths} months` : 'None', icon: 'ri-time-line' },
                    { label: 'Notice Period', value: `${cat.noticeDays} days`, icon: 'ri-file-warning-line' },
                    { label: 'Renewal Reminder', value: cat.contractRenewalDays ? `${cat.contractRenewalDays}d before` : 'N/A', icon: 'ri-notification-badge-line' },
                  ].map(item => (
                    <div key={item.label} className="bg-gray-50 rounded-xl p-3 text-center">
                      <div className="w-6 h-6 flex items-center justify-center mx-auto mb-1.5" style={{ color: cat.color }}>
                        <i className={`${item.icon} text-base`}></i>
                      </div>
                      <p className="text-sm font-bold text-gray-800">{item.value}</p>
                      <p className="text-xs text-gray-500 mt-0.5">{item.label}</p>
                    </div>
                  ))}
                </div>
                <div>
                  <p className="text-xs font-semibold text-gray-600 mb-2">Benefits & Entitlements</p>
                  <div className="flex flex-wrap gap-2">
                    {cat.benefits.map(b => (
                      <span key={b} className="text-xs px-3 py-1.5 rounded-full bg-green-100 text-green-700 font-medium">{b}</span>
                    ))}
                    {cat.benefits.length === 0 && <span className="text-xs text-gray-400">No benefits defined</span>}
                  </div>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
