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

interface CommitteeMember {
  name: string;
  role: 'Chair' | 'Secretary' | 'Member';
  dept: string;
}

interface Committee {
  id: number;
  name: string;
  type: string;
  purpose: string;
  members: CommitteeMember[];
  nextMeeting: string;
  status: 'Active' | 'Inactive';
}

const initialCommittees: Committee[] = [
  {
    id: 1, name: 'Disciplinary Committee', type: 'Disciplinary', status: 'Active',
    purpose: 'Review and adjudicate disciplinary cases, ensure fair process and natural justice',
    nextMeeting: '2026-04-22',
    members: [
      { name: 'Susan Kamau', role: 'Chair', dept: 'Human Resources' },
      { name: 'Peter Kariuki', role: 'Secretary', dept: 'Legal & Compliance' },
      { name: 'John Mwangi', role: 'Member', dept: 'Finance & Accounts' },
      { name: 'Grace Muthoni', role: 'Member', dept: 'Program Management' },
    ],
  },
  {
    id: 2, name: 'Grievance Handling Committee', type: 'Grievance', status: 'Active',
    purpose: 'Handle employee grievances, mediate disputes, and recommend resolutions',
    nextMeeting: '2026-04-28',
    members: [
      { name: 'Jane Wambua', role: 'Chair', dept: 'Human Resources' },
      { name: 'David Otieno', role: 'Secretary', dept: 'ICT & Systems' },
      { name: 'Faith Njoroge', role: 'Member', dept: 'Communications' },
    ],
  },
  {
    id: 3, name: 'Promotions Committee', type: 'Promotions', status: 'Active',
    purpose: 'Review promotion applications, evaluate eligibility criteria, approve grade changes',
    nextMeeting: '2026-05-10',
    members: [
      { name: 'James Onyango', role: 'Chair', dept: 'Executive Office' },
      { name: 'Susan Kamau', role: 'Secretary', dept: 'Human Resources' },
      { name: 'Peter Kariuki', role: 'Member', dept: 'Legal & Compliance' },
      { name: 'John Mwangi', role: 'Member', dept: 'Finance & Accounts' },
      { name: 'Grace Muthoni', role: 'Member', dept: 'Program Management' },
    ],
  },
];

const ROLE_COLORS = { Chair: 'bg-purple-100 text-purple-700', Secretary: 'bg-blue-100 text-blue-600', Member: 'bg-gray-100 text-gray-600' };

function MeetingModal({ committee, onClose, onSave }: { committee: Committee; onClose: () => void; onSave: (date: string, agenda: string) => void }) {
  const [date, setDate] = useState('');
  const [agenda, setAgenda] = useState('');
  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-sm p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-bold text-gray-800">Schedule Meeting</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"></i></button>
        </div>
        <p className="text-xs text-gray-500 mb-4">{committee.name}</p>
        <div className="space-y-3">
          <div><label className="text-xs font-semibold text-gray-600 block mb-1">Meeting Date & Time</label>
            <input type="datetime-local" value={date} onChange={e => setDate(e.target.value)} 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">Agenda</label>
            <textarea value={agenda} onChange={e => setAgenda(e.target.value)} rows={3} placeholder="Meeting agenda..." className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none resize-none" maxLength={500}></textarea></div>
        </div>
        <div className="flex gap-3 mt-4">
          <button onClick={onClose} className="flex-1 px-4 py-2.5 rounded-xl border border-gray-200 text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
          <button onClick={() => { onSave(date, agenda); onClose(); }} className="flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Schedule</button>
        </div>
      </div>
    </div>
  );
}

export default function CommitteesSection() {
  const [committees, setCommittees] = useState<Committee[]>(initialCommittees);
  const [expanded, setExpanded] = useState<number | null>(1);
  const [meetingModal, setMeetingModal] = useState<Committee | null>(null);
  const [delTarget, setDelTarget] = useState<Committee | null>(null);
  const [toast, setToast] = useState('');

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      {meetingModal && <MeetingModal committee={meetingModal} onClose={() => setMeetingModal(null)}
        onSave={(date) => { setCommittees(cs => cs.map(c => c.id === meetingModal.id ? { ...c, nextMeeting: date.split('T')[0] } : c)); setToast('Meeting scheduled & invites sent'); }} />}
      {delTarget && <ConfirmDialog title="Dissolve Committee" message={`Dissolve "${delTarget.name}"? All meeting records will be archived.`}
        confirmLabel="Dissolve" onConfirm={() => { setCommittees(cs => cs.filter(c => c.id !== delTarget.id)); setDelTarget(null); setToast('Committee dissolved'); }}
        onCancel={() => setDelTarget(null)} />}

      <SectionHeader icon="ri-group-3-line" title="Committee Setup" desc="Create and manage organizational committees and their members"
        action={<button onClick={() => setToast('Create committee form coming soon')} 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> New Committee
        </button>} />

      <div className="space-y-4">
        {committees.map(c => (
          <div key={c.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden hover:-translate-y-0.5 transition-transform">
            <div className="flex items-center justify-between p-4 cursor-pointer" onClick={() => setExpanded(expanded === c.id ? null : c.id)}>
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-xl flex items-center justify-center text-white font-bold text-sm flex-shrink-0" style={{ background: '#b828a0' }}>
                  {c.members.length}
                </div>
                <div>
                  <p className="text-sm font-bold text-gray-800">{c.name}</p>
                  <p className="text-xs text-gray-500 mt-0.5">{c.purpose.substring(0, 60)}...</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${c.status === 'Active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>{c.status}</span>
                <button onClick={(e) => { e.stopPropagation(); setMeetingModal(c); }} className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-pink-50 text-xs font-medium cursor-pointer whitespace-nowrap" style={{ color: '#b828a0' }}>
                  <i className="ri-calendar-event-line text-xs"></i> Schedule
                </button>
                <button onClick={(e) => { e.stopPropagation(); setDelTarget(c); }} 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>
                <div className="w-5 h-5 flex items-center justify-center">
                  <i className={`${expanded === c.id ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} text-gray-400 text-lg`}></i>
                </div>
              </div>
            </div>

            {expanded === c.id && (
              <div className="border-t border-gray-100 p-4">
                <div className="flex items-center gap-4 mb-4">
                  <div className="flex items-center gap-1.5 text-xs text-gray-500">
                    <div className="w-3 h-3 flex items-center justify-center"><i className="ri-calendar-line text-xs"></i></div>
                    Next meeting: <span className="font-semibold text-gray-700">{c.nextMeeting}</span>
                  </div>
                  <div className="flex items-center gap-1.5 text-xs text-gray-500">
                    <div className="w-3 h-3 flex items-center justify-center"><i className="ri-group-line text-xs"></i></div>
                    {c.members.length} members
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-2">
                  {c.members.map((m, i) => (
                    <div key={i} className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                      <div className="flex items-center gap-2">
                        <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: '#b828a0' }}>
                          {m.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                        </div>
                        <div>
                          <p className="text-xs font-semibold text-gray-800">{m.name}</p>
                          <p className="text-xs text-gray-400">{m.dept}</p>
                        </div>
                      </div>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium whitespace-nowrap ${ROLE_COLORS[m.role]}`}>{m.role}</span>
                    </div>
                  ))}
                </div>
                <button onClick={() => setToast('Member added to committee')} className="mt-3 flex items-center gap-1.5 text-xs font-medium cursor-pointer" style={{ color: '#b828a0' }}>
                  <div className="w-4 h-4 flex items-center justify-center"><i className="ri-user-add-line text-sm"></i></div>
                  Add Member
                </button>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
