'use client';
import { useState } from 'react';
import { TrainingProgram, EnrolledStaff, initialPrograms } from './trainingData';
import ScheduleTrainingModal from './ScheduleTrainingModal';
import EnrollStaffModal from './EnrollStaffModal';

const STATUS_ORDER: Record<string, number> = { Upcoming: 0, Ongoing: 1, Completed: 2 };

const STATUS_COLORS: Record<string, string> = {
  Upcoming: 'bg-yellow-100 text-yellow-700',
  Ongoing: 'bg-blue-100 text-blue-700',
  Completed: 'bg-green-100 text-green-700',
};

const MODE_ICONS: Record<string, string> = {
  'In-Person': 'ri-map-pin-line',
  'Online': 'ri-wifi-line',
  'Hybrid': 'ri-git-merge-line',
};

type ModalMode = 'view' | 'edit' | null;

export default function TrainingProgramsTab() {
  const [programs, setPrograms] = useState<TrainingProgram[]>(() =>
    [...initialPrograms].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status])
  );
  const [filter, setFilter] = useState('All');
  const [search, setSearch] = useState('');
  const [modal, setModal] = useState<ModalMode>(null);
  const [selected, setSelected] = useState<TrainingProgram | null>(null);
  const [enrollProgram, setEnrollProgram] = useState<TrainingProgram | null>(null);
  const [showSchedule, setShowSchedule] = useState(false);
  const [toast, setToast] = useState('');
  const [editForm, setEditForm] = useState<Partial<TrainingProgram>>({});

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

  const sorted = [...programs].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status]);

  const filtered = sorted.filter(p =>
    (filter === 'All' || p.status === filter) &&
    (p.title.toLowerCase().includes(search.toLowerCase()) ||
      p.dept.toLowerCase().includes(search.toLowerCase()) ||
      p.trainer.toLowerCase().includes(search.toLowerCase()))
  );

  const handleEnroll = (staffList: { staffId: string; name: string; dept: string }[]) => {
    if (!enrollProgram) return;
    const today = new Date().toISOString().split('T')[0];
    const newEntries: EnrolledStaff[] = staffList.map(s => ({
      staffId: s.staffId, name: s.name, dept: s.dept,
      enrolledDate: today, completionStatus: 'Enrolled' as const,
    }));
    setPrograms(prev => prev.map(p => {
      if (p.id !== enrollProgram.id) return p;
      return { ...p, enrolled: p.enrolled + staffList.length, enrolledStaff: [...p.enrolledStaff, ...newEntries] };
    }));
    setEnrollProgram(null);
    showToast(`${staffList.length === 1 ? staffList[0].name : `${staffList.length} staff`} enrolled successfully!`);
  };

  const handleSchedule = (program: TrainingProgram) => {
    setPrograms(prev => [...prev, program].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status]));
    setShowSchedule(false);
    showToast(`Training "${program.title}" scheduled!`);
  };

  const handleEditSave = () => {
    if (!selected) return;
    setPrograms(prev => prev.map(p => p.id === selected.id ? { ...p, ...editForm } : p));
    showToast('Program updated successfully!');
    setModal(null);
    setSelected(null);
  };

  return (
    <div className="space-y-5">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium">{toast}</div>
      )}

      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Total Programs', value: programs.length, icon: 'ri-book-open-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Upcoming', value: programs.filter(p => p.status === 'Upcoming').length, icon: 'ri-calendar-event-line', color: 'text-yellow-600 bg-yellow-50' },
          { label: 'Ongoing', value: programs.filter(p => p.status === 'Ongoing').length, icon: 'ri-loader-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Completed', value: programs.filter(p => p.status === 'Completed').length, icon: 'ri-checkbox-circle-line', color: 'text-green-600 bg-green-50' },
        ].map(({ label, value, icon, color }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-xl ${color} flex items-center justify-center mb-3`}>
              <i className={`${icon} text-lg`}></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{value}</p>
            <p className="text-sm text-gray-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100">
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-2 flex-wrap">
            {['All', 'Upcoming', 'Ongoing', 'Completed'].map(f => (
              <button key={f} onClick={() => setFilter(f)}
                className="px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap transition-all"
                style={filter === f ? { background: '#b22698', color: 'white' } : { background: '#f3f4f6', color: '#6b7280' }}>
                {f}
              </button>
            ))}
            <div className="relative">
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search programs..."
                className="bg-gray-50 border border-gray-200 rounded-lg px-4 py-1.5 text-sm w-44 outline-none" />
              <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2">
                <i className="ri-search-line text-gray-400 text-sm"></i>
              </div>
            </div>
          </div>
          <button onClick={() => setShowSchedule(true)}
            className="flex items-center gap-2 text-white px-4 py-2 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap hover:opacity-90"
            style={{ background: '#b22698' }}>
            <i className="ri-add-line"></i> Create New Program
          </button>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                {['Program Name', 'Department', 'Start Date', 'End Date', 'Enrolled', 'Status', 'Actions'].map(h => (
                  <th key={h} className="text-left text-xs font-semibold text-gray-500 px-4 py-3 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(p => (
                <tr key={p.id} className={`border-b border-gray-50 hover:bg-gray-50 transition-colors ${p.status === 'Completed' ? 'opacity-75' : ''}`}>
                  <td className="px-4 py-3">
                    <p className="text-sm font-semibold text-gray-800">{p.title}</p>
                    <p className="text-xs text-gray-400">{p.id} · {p.trainer}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">{p.dept}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{p.start}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{p.end}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5">
                      <span className="text-sm font-semibold text-gray-800">{p.enrolled}</span>
                      <span className="text-xs text-gray-400">/ {p.capacity}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2.5 py-1 rounded-full text-xs font-semibold ${STATUS_COLORS[p.status]}`}>{p.status}</span>
                    {p.status === 'Completed' && (
                      <p className="text-xs text-orange-500 mt-0.5 font-medium">Certificate upload required</p>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5">
                      <button onClick={() => { setSelected(p); setModal('view'); }}
                        className="text-xs px-2.5 py-1.5 rounded-lg cursor-pointer font-medium text-white whitespace-nowrap hover:opacity-80"
                        style={{ background: '#b22698' }}>
                        View
                      </button>
                      <button onClick={() => { setSelected(p); setEditForm({ title: p.title, dept: p.dept, start: p.start, end: p.end }); setModal('edit'); }}
                        className="text-xs px-2.5 py-1.5 rounded-lg cursor-pointer font-medium whitespace-nowrap hover:bg-gray-100 border border-gray-200 text-gray-600">
                        Edit
                      </button>
                      {p.status !== 'Completed' && (
                        <button onClick={() => setEnrollProgram(p)}
                          className="text-xs px-2.5 py-1.5 rounded-lg cursor-pointer font-medium whitespace-nowrap hover:bg-gray-100 border border-gray-200 text-gray-600">
                          Enroll
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div className="text-center py-12 text-gray-400 text-sm">No programs found</div>
          )}
        </div>
        <div className="px-5 py-3 border-t border-gray-100 bg-gray-50 rounded-b-xl">
          <p className="text-xs text-gray-400">Sort order: Upcoming → Ongoing → Completed. Completed programs trigger certificate upload requests to participants.</p>
        </div>
      </div>

      {modal === 'view' && selected && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b22698' }}>
              <div>
                <h2 className="text-white font-bold text-lg">{selected.title}</h2>
                <p className="text-pink-200 text-sm">{selected.id} · {selected.dept}</p>
              </div>
              <button onClick={() => { setModal(null); setSelected(null); }} className="w-8 h-8 flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-white text-xl"></i>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                {[
                  ['Trainer', selected.trainer],
                  ['Mode', selected.mode],
                  ['Venue', selected.venue],
                  ['Dates', `${selected.start} → ${selected.end}`],
                  ['Enrolled', `${selected.enrolled} / ${selected.capacity}`],
                  ['Cost', `KES ${selected.cost.toLocaleString()}`],
                ].map(([k, v]) => (
                  <div key={k}>
                    <p className="text-xs text-gray-400 mb-1">{k}</p>
                    <p className="text-sm font-semibold text-gray-800">{v}</p>
                  </div>
                ))}
              </div>
              <div>
                <p className="text-xs text-gray-400 mb-1">Description</p>
                <p className="text-sm text-gray-700 bg-gray-50 rounded-lg p-3">{selected.description}</p>
              </div>
              {selected.status === 'Completed' && (
                <div className="bg-orange-50 border border-orange-200 rounded-xl p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <div className="w-4 h-4 flex items-center justify-center">
                      <i className="ri-alarm-warning-line text-orange-600 text-sm"></i>
                    </div>
                    <p className="text-sm font-semibold text-orange-700">Certificate Upload Required</p>
                  </div>
                  <p className="text-xs text-orange-600">All {selected.enrolled} participants must upload their certificates. Reminders are sent 7 days after completion if missing.</p>
                </div>
              )}
              {selected.enrolledStaff.length > 0 && (
                <div>
                  <p className="text-xs text-gray-400 mb-2">Enrolled Staff ({selected.enrolledStaff.length})</p>
                  <div className="space-y-1.5">
                    {selected.enrolledStaff.map(s => (
                      <div key={s.staffId} className="flex items-center justify-between py-1.5 px-3 bg-gray-50 rounded-lg">
                        <div>
                          <span className="text-sm font-medium text-gray-800">{s.name}</span>
                          <span className="text-xs text-gray-400 ml-2">{s.dept}</span>
                        </div>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${s.completionStatus === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`}>
                          {s.completionStatus}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {modal === 'edit' && selected && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b22698' }}>
              <h2 className="text-white font-bold text-lg">Edit Program</h2>
              <button onClick={() => { setModal(null); setSelected(null); }} className="w-8 h-8 flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-white text-xl"></i>
              </button>
            </div>
            <div className="p-6 space-y-4">
              {[
                { label: 'Program Name', key: 'title', type: 'text' },
                { label: 'Department', key: 'dept', type: 'text' },
                { label: 'Start Date', key: 'start', type: 'date' },
                { label: 'End Date', key: 'end', type: 'date' },
              ].map(({ label, key, type }) => (
                <div key={key}>
                  <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
                  <input type={type} value={(editForm as any)[key] || ''} onChange={e => setEditForm(p => ({ ...p, [key]: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-pink-400" />
                </div>
              ))}
              <div className="flex gap-3 pt-2">
                <button onClick={handleEditSave}
                  className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer hover:opacity-90"
                  style={{ background: '#b22698' }}>
                  Save Changes
                </button>
                <button onClick={() => { setModal(null); setSelected(null); }}
                  className="flex-1 py-2.5 rounded-xl border border-gray-200 text-gray-600 text-sm font-semibold cursor-pointer hover:bg-gray-50">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {enrollProgram && (
        <EnrollStaffModal program={enrollProgram} onClose={() => setEnrollProgram(null)} onEnroll={handleEnroll} />
      )}
      {showSchedule && (
        <ScheduleTrainingModal onClose={() => setShowSchedule(false)} onSave={handleSchedule} existingCount={programs.length} />
      )}
    </div>
  );
}
