'use client';
import { useState } from 'react';
import SectionHeader from './SectionHeader';
import ToastNotif from './ToastNotif';
import ConfirmDialog from './ConfirmDialog';

interface Holiday {
  id: number;
  name: string;
  date: string;
  type: 'Public' | 'Company';
  recurring: boolean;
}

interface Shift {
  id: number;
  name: string;
  start: string;
  end: string;
  breakMins: number;
  days: string[];
}

interface BlackoutPeriod {
  id: number;
  name: string;
  from: string;
  to: string;
  reason: string;
}

const initialHolidays: Holiday[] = [
  { id: 1, name: "New Year's Day", date: '2026-01-01', type: 'Public', recurring: true },
  { id: 2, name: 'Good Friday', date: '2026-04-03', type: 'Public', recurring: false },
  { id: 3, name: 'Labour Day', date: '2026-05-01', type: 'Public', recurring: true },
  { id: 4, name: "Madaraka Day", date: '2026-06-01', type: 'Public', recurring: true },
  { id: 5, name: 'Huduma Day', date: '2026-10-10', type: 'Public', recurring: true },
  { id: 6, name: "Jamhuri Day", date: '2026-12-12', type: 'Public', recurring: true },
  { id: 7, name: "Christmas Day", date: '2026-12-25', type: 'Public', recurring: true },
  { id: 8, name: "Uwezo Fund Founding Day", date: '2026-03-15', type: 'Company', recurring: true },
];

const initialShifts: Shift[] = [
  { id: 1, name: 'Morning Shift', start: '07:00', end: '15:00', breakMins: 30, days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
  { id: 2, name: 'Afternoon Shift', start: '14:00', end: '22:00', breakMins: 30, days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
  { id: 3, name: 'Standard Day', start: '08:00', end: '17:00', breakMins: 60, days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
];

const initialBlackouts: BlackoutPeriod[] = [
  { id: 1, name: 'Year-End Shutdown', from: '2026-12-24', to: '2026-12-31', reason: 'Annual organization shutdown period' },
  { id: 2, name: 'Audit Period', from: '2026-06-15', to: '2026-06-30', reason: 'Staff required during annual audit — no leave permitted' },
];

const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

export default function CalendarSection() {
  const [holidays, setHolidays] = useState<Holiday[]>(initialHolidays);
  const [shifts, setShifts] = useState<Shift[]>(initialShifts);
  const [blackouts, setBlackouts] = useState<BlackoutPeriod[]>(initialBlackouts);
  const [activeTab, setActiveTab] = useState<'holidays' | 'shifts' | 'blackouts' | 'config'>('holidays');
  const [toast, setToast] = useState('');
  const [delHoliday, setDelHoliday] = useState<Holiday | null>(null);
  const [delBlackout, setDelBlackout] = useState<BlackoutPeriod | null>(null);
  const [addHoliday, setAddHoliday] = useState(false);
  const [addShift, setAddShift] = useState(false);
  const [addBlackout, setAddBlackout] = useState(false);
  const [hForm, setHForm] = useState({ name: '', date: '', type: 'Public' as 'Public' | 'Company', recurring: false });
  const [sForm, setSForm] = useState({ name: '', start: '08:00', end: '17:00', breakMins: 60, days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] as string[] });
  const [bForm, setBForm] = useState({ name: '', from: '', to: '', reason: '' });
  const [workDays, setWorkDays] = useState(['Mon', 'Tue', 'Wed', 'Thu', 'Fri']);
  const [postingCycle, setPostingCycle] = useState('Monthly');

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      {delHoliday && <ConfirmDialog title="Delete Holiday" message={`Remove "${delHoliday.name}" from the holiday calendar?`}
        onConfirm={() => { setHolidays(hs => hs.filter(h => h.id !== delHoliday.id)); setDelHoliday(null); setToast('Holiday removed'); }}
        onCancel={() => setDelHoliday(null)} />}
      {delBlackout && <ConfirmDialog title="Remove Blackout Period" message={`Remove "${delBlackout.name}" blackout period?`}
        onConfirm={() => { setBlackouts(bs => bs.filter(b => b.id !== delBlackout.id)); setDelBlackout(null); setToast('Blackout period removed'); }}
        onCancel={() => setDelBlackout(null)} />}

      <SectionHeader icon="ri-calendar-2-line" title="Calendar Configuration" desc="Manage working days, public holidays, shifts, and blackout periods" />

      <div className="flex gap-2 mb-4 flex-wrap">
        {[{ k: 'holidays' as const, l: 'Public Holidays' }, { k: 'shifts' as const, l: 'Shift Definitions' }, { k: 'blackouts' as const, l: 'Blackout Periods' }, { k: 'config' as const, l: 'Calendar Config' }].map(t => (
          <button key={t.k} onClick={() => setActiveTab(t.k)}
            className={`px-4 py-2 rounded-xl text-xs font-semibold cursor-pointer whitespace-nowrap border transition-all ${activeTab === t.k ? 'text-white border-transparent' : 'bg-white text-gray-600 border-gray-200'}`}
            style={activeTab === t.k ? { background: '#b828a0' } : {}}>
            {t.l}
          </button>
        ))}
      </div>

      {activeTab === 'holidays' && (
        <div>
          {addHoliday && (
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-4">
              <p className="text-sm font-semibold text-gray-800 mb-3">Add Holiday</p>
              <div className="grid grid-cols-2 gap-3">
                <div><label className="text-xs font-semibold text-gray-600 block mb-1">Name</label>
                  <input value={hForm.name} onChange={e => setHForm(f => ({ ...f, name: e.target.value }))} placeholder="Holiday name" className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
                <div><label className="text-xs font-semibold text-gray-600 block mb-1">Date</label>
                  <input type="date" value={hForm.date} onChange={e => setHForm(f => ({ ...f, date: e.target.value }))} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
                <div className="flex gap-3 items-center col-span-2">
                  {['Public', 'Company'].map(t => (
                    <button key={t} onClick={() => setHForm(f => ({ ...f, type: t as 'Public' | 'Company' }))}
                      className={`px-4 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border ${hForm.type === t ? 'text-white border-transparent' : 'border-gray-200 text-gray-600'}`}
                      style={hForm.type === t ? { background: '#b828a0' } : {}}>{t}</button>
                  ))}
                  <label className="flex items-center gap-2 text-xs text-gray-600 cursor-pointer ml-2">
                    <input type="checkbox" checked={hForm.recurring} onChange={e => setHForm(f => ({ ...f, recurring: e.target.checked }))} className="rounded" />
                    Recurring annually
                  </label>
                </div>
              </div>
              <div className="flex gap-2 mt-3">
                <button onClick={() => setAddHoliday(false)} className="px-4 py-2 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                <button onClick={() => { if (hForm.name && hForm.date) { setHolidays(hs => [...hs, { ...hForm, id: Date.now() }]); setAddHoliday(false); setHForm({ name: '', date: '', type: 'Public', recurring: false }); setToast('Holiday added'); } }}
                  className="px-4 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Add Holiday</button>
              </div>
            </div>
          )}
          <div className="flex justify-end mb-3">
            <button onClick={() => setAddHoliday(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 text-sm"></i></div> Add Holiday
            </button>
          </div>
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <table className="w-full">
              <thead><tr className="border-b border-gray-100" style={{ background: '#fdf0fb' }}>
                {['Holiday', 'Date', 'Type', 'Recurring', ''].map(h => <th key={h} className="text-left text-xs font-semibold text-gray-600 px-4 py-3">{h}</th>)}
              </tr></thead>
              <tbody>
                {holidays.map(h => (
                  <tr key={h.id} className="border-b border-gray-50 hover:bg-pink-50/30 transition-colors">
                    <td className="px-4 py-3 text-sm font-semibold text-gray-800">{h.name}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{h.date}</td>
                    <td className="px-4 py-3"><span className={`text-xs px-2.5 py-1 rounded-full font-medium ${h.type === 'Public' ? 'bg-blue-100 text-blue-700' : 'bg-pink-100'}`} style={h.type === 'Company' ? { color: '#b828a0' } : {}}>{h.type}</span></td>
                    <td className="px-4 py-3"><span className={`text-xs px-2.5 py-1 rounded-full ${h.recurring ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>{h.recurring ? 'Yes' : 'No'}</span></td>
                    <td className="px-4 py-3"><button onClick={() => setDelHoliday(h)} className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-red-50 cursor-pointer"><i className="ri-delete-bin-line text-red-400 text-xs"></i></button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeTab === 'shifts' && (
        <div>
          {addShift && (
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-4">
              <p className="text-sm font-semibold text-gray-800 mb-3">Add Shift</p>
              <div className="grid grid-cols-2 gap-3">
                <div className="col-span-2"><label className="text-xs font-semibold text-gray-600 block mb-1">Shift Name</label>
                  <input value={sForm.name} onChange={e => setSForm(f => ({ ...f, name: e.target.value }))} placeholder="e.g. Night Shift" className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
                {[{ l: 'Start Time', k: 'start' }, { l: 'End Time', k: 'end' }].map(f => (
                  <div key={f.k}><label className="text-xs font-semibold text-gray-600 block mb-1">{f.l}</label>
                    <input type="time" value={(sForm as any)[f.k]} onChange={e => setSForm(p => ({ ...p, [f.k]: e.target.value }))} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
                ))}
                <div className="col-span-2"><label className="text-xs font-semibold text-gray-600 block mb-2">Working Days</label>
                  <div className="flex gap-2">
                    {WEEKDAYS.map(d => (
                      <button key={d} onClick={() => setSForm(f => ({ ...f, days: f.days.includes(d) ? f.days.filter(x => x !== d) : [...f.days, d] }))}
                        className={`w-10 h-10 rounded-xl text-xs font-bold cursor-pointer border transition-all ${sForm.days.includes(d) ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                        style={sForm.days.includes(d) ? { background: '#b828a0' } : {}}>{d}</button>
                    ))}
                  </div>
                </div>
              </div>
              <div className="flex gap-2 mt-3">
                <button onClick={() => setAddShift(false)} className="px-4 py-2 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                <button onClick={() => { if (sForm.name) { setShifts(ss => [...ss, { ...sForm, id: Date.now() }]); setAddShift(false); setToast('Shift added'); } }}
                  className="px-4 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Add Shift</button>
              </div>
            </div>
          )}
          <div className="flex justify-end mb-3">
            <button onClick={() => setAddShift(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 text-sm"></i></div> Add Shift
            </button>
          </div>
          <div className="grid grid-cols-1 gap-3">
            {shifts.map(s => (
              <div key={s.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center justify-between hover:-translate-y-0.5 transition-transform">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center bg-pink-50 flex-shrink-0"><i className="ri-time-line text-xl" style={{ color: '#b828a0' }}></i></div>
                  <div>
                    <p className="text-sm font-bold text-gray-800">{s.name}</p>
                    <p className="text-xs text-gray-500">{s.start} – {s.end} · {s.breakMins} min break</p>
                    <div className="flex gap-1 mt-1.5">{s.days.map(d => <span key={d} className="text-xs px-2 py-0.5 rounded-full bg-pink-100 font-medium" style={{ color: '#b828a0' }}>{d}</span>)}</div>
                  </div>
                </div>
                <div className="flex gap-1">
                  <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer"><i className="ri-edit-2-line text-blue-400 text-sm"></i></button>
                  <button onClick={() => { setShifts(ss => ss.filter(x => x.id !== s.id)); setToast('Shift removed'); }} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 cursor-pointer"><i className="ri-delete-bin-line text-red-400 text-sm"></i></button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {activeTab === 'blackouts' && (
        <div>
          {addBlackout && (
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-4">
              <p className="text-sm font-semibold text-gray-800 mb-3">Add Blackout Period</p>
              <div className="grid grid-cols-2 gap-3">
                <div className="col-span-2"><label className="text-xs font-semibold text-gray-600 block mb-1">Period Name</label>
                  <input value={bForm.name} onChange={e => setBForm(f => ({ ...f, name: e.target.value }))} placeholder="e.g. Year-End Shutdown" className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
                {[{ l: 'From Date', k: 'from' }, { l: 'To Date', k: 'to' }].map(f => (
                  <div key={f.k}><label className="text-xs font-semibold text-gray-600 block mb-1">{f.l}</label>
                    <input type="date" value={(bForm as any)[f.k]} onChange={e => setBForm(p => ({ ...p, [f.k]: e.target.value }))} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
                ))}
                <div className="col-span-2"><label className="text-xs font-semibold text-gray-600 block mb-1">Reason</label>
                  <input value={bForm.reason} onChange={e => setBForm(f => ({ ...f, reason: e.target.value }))} placeholder="Reason for blackout" className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
              </div>
              <div className="flex gap-2 mt-3">
                <button onClick={() => setAddBlackout(false)} className="px-4 py-2 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                <button onClick={() => { if (bForm.name) { setBlackouts(bs => [...bs, { ...bForm, id: Date.now() }]); setAddBlackout(false); setBForm({ name: '', from: '', to: '', reason: '' }); setToast('Blackout period added'); } }}
                  className="px-4 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Add Period</button>
              </div>
            </div>
          )}
          <div className="flex justify-end mb-3">
            <button onClick={() => setAddBlackout(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 text-sm"></i></div> Add Period
            </button>
          </div>
          <div className="space-y-3">
            {blackouts.map(b => (
              <div key={b.id} className="bg-white rounded-2xl border border-red-100 shadow-sm p-4 hover:-translate-y-0.5 transition-transform">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl bg-red-50 flex items-center justify-center flex-shrink-0"><i className="ri-calendar-close-line text-xl text-red-500"></i></div>
                    <div>
                      <p className="text-sm font-bold text-gray-800">{b.name}</p>
                      <p className="text-xs text-gray-500 mt-0.5">{b.from} → {b.to} · {b.reason}</p>
                    </div>
                  </div>
                  <button onClick={() => setDelBlackout(b)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 cursor-pointer"><i className="ri-delete-bin-line text-red-400 text-sm"></i></button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {activeTab === 'config' && (
        <div className="space-y-4">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <p className="text-sm font-bold text-gray-800 mb-4">Base Calendar Settings</p>
            <div className="mb-4">
              <label className="text-xs font-semibold text-gray-600 block mb-2">Working Days</label>
              <div className="flex gap-2">
                {WEEKDAYS.map(d => (
                  <button key={d} onClick={() => setWorkDays(wd => wd.includes(d) ? wd.filter(x => x !== d) : [...wd, d])}
                    className={`w-11 h-11 rounded-xl text-xs font-bold cursor-pointer border transition-all ${workDays.includes(d) ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                    style={workDays.includes(d) ? { background: '#b828a0' } : {}}>{d}</button>
                ))}
              </div>
            </div>
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-2">Leave Posting Cycle</label>
              <div className="flex gap-2">
                {['Monthly', 'Quarterly', 'Bi-Annually', 'Annually'].map(c => (
                  <button key={c} onClick={() => setPostingCycle(c)}
                    className={`px-4 py-2 rounded-xl text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${postingCycle === c ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                    style={postingCycle === c ? { background: '#b828a0' } : {}}>{c}</button>
                ))}
              </div>
            </div>
            <button onClick={() => setToast('Calendar configuration saved')} className="mt-5 px-6 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Save Configuration</button>
          </div>
        </div>
      )}
    </div>
  );
}
