'use client';
import { useState } from 'react';
import HODLayout from '../../../components/HODLayout';
import { useAuth } from '../../../lib/authContext';
import { useTrainingStore } from '../../../lib/trainingStore';
import { initialPrograms, TrainingProgram } from '../../hr/training/trainingData';
import { TrainingRequest } from '../../hr/training/trainingModuleData';
import ProgramViewModal from '../../../components/ProgramViewModal';

const BRAND = '#B22698';

const STAGE_CONFIG: Record<string, { color: string; bg: string; label: string }> = {
  HR: { color: '#d97706', bg: '#fef3c7', label: 'Pending HR' },
  HOS: { color: BRAND, bg: '#fce7f3', label: 'Pending HOS' },
  Finance: { color: '#2563eb', bg: '#dbeafe', label: 'Pending Finance' },
  Complete: { color: '#16a34a', bg: '#dcfce7', label: 'Fully Approved' },
  Rejected: { color: '#dc2626', bg: '#fee2e2', label: 'Rejected' },
};

function TrainingRequestModal({ onClose, onSubmit, dept }: { onClose: () => void; onSubmit: (form: any) => void; dept: string }) {
  const { user } = useAuth();
  const [form, setForm] = useState({
    courseName: '',
    provider: '',
    mode: 'Physical' as 'Physical' | 'Virtual' | 'Hybrid',
    regNo: '',
    cost: '',
    proformaFile: '',
    admissionFile: '',
    startDate: '',
    endDate: '',
    justification: '',
    outcomes: '',
    previousTraining: false,
    email: '',
  });

  const set = (k: string, v: any) => setForm(p => ({ ...p, [k]: v }));
  const [errors, setErrors] = useState<string[]>([]);

  const validateAllFields = () => {
    const errs: string[] = [];
    if (!form.courseName.trim()) errs.push('Course Name is required');
    if (!form.provider.trim()) errs.push('Training Provider is required');
    if (!form.mode) errs.push('Training Mode is required');
    if (!form.regNo.trim()) errs.push('Registration Number is required');
    if (!form.email.trim() || !/^\S+@\S+\.\S+$/.test(form.email)) errs.push('A valid email address is required for updates');
    if (!form.cost.trim() || Number(form.cost) <= 0) errs.push('Estimated Cost (KES) is required and must be greater than 0');
    if (!form.proformaFile) errs.push('Proforma Invoice (PDF) is required');
    if (!form.admissionFile) errs.push('Admission Letter (PDF) is required');
    if (!form.startDate) errs.push('Start Date is required');
    else if (form.startDate < new Date().toISOString().split('T')[0]) errs.push('Start Date cannot be in the past');
    if (!form.endDate) errs.push('End Date is required');
    else if (form.endDate <= form.startDate) errs.push('End Date must be after Start Date');
    if (!form.justification.trim()) errs.push('Justification is required');
    if (!form.outcomes.trim()) errs.push('Expected Outcomes are required');
    return errs;
  };

  const handleSubmit = () => {
    const errs = validateAllFields();
    setErrors(errs);
    if (errs.length > 0) return;
    onSubmit(form);
    setErrors([]);
  };

  return (
    <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-xl max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: BRAND }}>
          <h2 className="text-white font-bold text-lg">Training Request</h2>
          <button onClick={onClose} 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">
          {errors.length > 0 && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-3 space-y-1">
              {errors.map((e, i) => (
                <div key={i} className="flex items-start gap-2">
                  <i className="ri-error-warning-line text-red-500 mt-0.5 flex-shrink-0"></i>
                  <p className="text-xs text-red-700">{e}</p>
                </div>
              ))}
            </div>
          )}
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Course Name <span className="text-red-500">*</span></label>
              <input value={form.courseName} onChange={e => set('courseName', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. Advanced Data Analytics" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Training Provider <span className="text-red-500">*</span></label>
              <input value={form.provider} onChange={e => set('provider', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Provider name" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Training Mode <span className="text-red-500">*</span></label>
              <div className="flex gap-1">
                {(['Physical', 'Virtual', 'Hybrid'] as const).map(m => (
                  <button key={m} onClick={() => set('mode', m)}
                    className={`flex-1 py-1.5 rounded-lg text-xs font-medium cursor-pointer border transition-all ${form.mode === m ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                    style={form.mode === m ? { background: BRAND } : {}}>
                    {m}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Registration Number <span className="text-red-500">*</span></label>
              <input value={form.regNo} onChange={e => set('regNo', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. REG2024A001" />
              <p className="text-xs text-gray-400 mt-1">Must contain both letters and numbers</p>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Email Address <span className="text-red-500">*</span></label>
              <input type="email" value={form.email} onChange={e => set('email', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="your.email@uwezo.go.ke" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Estimated Cost (KES) <span className="text-red-500">*</span></label>
              <input type="number" value={form.cost} onChange={e => set('cost', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="0" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Proforma Invoice (PDF) <span className="text-red-500">*</span></label>
              <label className={`border-2 border-dashed rounded-lg p-2 text-center hover:border-pink-300 transition-colors cursor-pointer block ${!form.proformaFile ? 'border-red-200' : 'border-gray-200'}`}>
                <i className="ri-upload-cloud-line text-gray-400 text-lg"></i>
                <p className="text-xs text-gray-500">{form.proformaFile || 'Upload PDF (Required)'}</p>
                <input type="file" accept=".pdf" className="hidden" onChange={e => set('proformaFile', e.target.files?.[0]?.name || '')} />
              </label>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Admission Letter (PDF) <span className="text-red-500">*</span></label>
              <label className={`border-2 border-dashed rounded-lg p-2 text-center hover:border-pink-300 transition-colors cursor-pointer block ${!form.admissionFile ? 'border-red-200' : 'border-gray-200'}`}>
                <i className="ri-upload-cloud-line text-gray-400 text-lg"></i>
                <p className="text-xs text-gray-500">{form.admissionFile || 'Upload PDF (Required)'}</p>
                <input type="file" accept=".pdf" className="hidden" onChange={e => set('admissionFile', e.target.files?.[0]?.name || '')} />
              </label>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Start Date <span className="text-red-500">*</span></label>
              <input type="date" value={form.startDate} onChange={e => set('startDate', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">End Date <span className="text-red-500">*</span></label>
              <input type="date" value={form.endDate} onChange={e => set('endDate', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Justification <span className="text-red-500">*</span></label>
              <textarea value={form.justification} onChange={e => set('justification', e.target.value)} rows={2} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Why this training is needed..." />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Expected Outcomes <span className="text-red-500">*</span></label>
              <textarea value={form.outcomes} onChange={e => set('outcomes', e.target.value)} rows={2} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="What you expect to achieve..." />
            </div>
            <div className="col-span-2 flex items-center gap-2">
              <input type="checkbox" id="prevTraining" checked={form.previousTraining} onChange={e => set('previousTraining', e.target.checked)} className="w-4 h-4 rounded cursor-pointer" />
              <label htmlFor="prevTraining" className="text-sm text-gray-700 cursor-pointer">I have undergone previous related training</label>
            </div>
          </div>
          <button onClick={handleSubmit}
            className="w-full py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap hover:opacity-90"
            style={{ background: BRAND }}>
            Submit Training Request
          </button>
        </div>
      </div>
    </div>
  );
}

export default function HODTrainingPage() {
  const { user } = useAuth();

  // #region agent log
  fetch('http://127.0.0.1:7275/ingest/995cfed7-44e5-437f-b48b-30a221f911ed',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'8673df'},body:JSON.stringify({sessionId:'8673df',runId:'pre-fix',hypothesisId:'H1',location:'app/hod/training/page.tsx:HODTrainingPage',message:'module-resolution-and-entry',data:{hasUser:!!user,programCount:initialPrograms.length},timestamp:Date.now()})}).catch(()=>{});
  // #endregion

  if (!user) return null;

  const { trainingReqs, updateTrainingReqs } = useTrainingStore();
  const [showForm, setShowForm] = useState(false);
  const [toast, setToast] = useState('');
  const [viewProgram, setViewProgram] = useState<TrainingProgram | null>(null);
  const [form, setForm] = useState({ courseRequested: '', justification: '', preferredStartDate: '', preferredEndDate: '', estimatedCost: '' });

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

  const deptId = `HOD-${user.id}`;
  const myReqs = trainingReqs.filter(r => r.employeeId === deptId || r.dept === user.dept);
  const deptPrograms = initialPrograms.filter(p => p.dept === user.dept || p.dept === 'All Departments');

  // #region agent log
  fetch('http://127.0.0.1:7275/ingest/995cfed7-44e5-437f-b48b-30a221f911ed',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'8673df'},body:JSON.stringify({sessionId:'8673df',runId:'pre-fix',hypothesisId:'H3',location:'app/hod/training/page.tsx:HODTrainingPage',message:'derived-training-state',data:{dept:user.dept,myReqs:myReqs.length,deptPrograms:deptPrograms.length},timestamp:Date.now()})}).catch(()=>{});
  // #endregion

  const completedPrograms = deptPrograms
    .filter(p => p.status === 'Completed')
    .sort((a, b) => new Date(b.end).getTime() - new Date(a.end).getTime());

  const handleSubmit = (form: any) => {
    const newReq: TrainingRequest = {
      id: `REQ-HOD-${Date.now()}`,
      employeeId: deptId,
      employeeName: user.name,
      dept: user.dept || 'Management',
      courseRequested: form.courseName,
      justification: form.justification,
      trainingProvider: form.provider,
      trainingMode: form.mode,
      regNo: form.regNo,
      estimatedCost: Number(form.cost) || 0,
      preferredStartDate: form.startDate,
      preferredEndDate: form.endDate,
      expectedOutcomes: form.outcomes,
      previousTraining: form.previousTraining,
      dateSubmitted: new Date().toISOString().split('T')[0],
      status: 'Submitted',
      currentStage: 'HR',
    };
    updateTrainingReqs(prev => [newReq, ...prev]);
    setShowForm(false);
    showToast('Training request submitted. Workflow: HR → HOS → Finance.');
  };

  return (
    <HODLayout title="Training & Development">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2" style={{ background: BRAND }}>
          <i className="ri-checkbox-circle-line"></i><span className="text-sm font-medium">{toast}</span>
        </div>
      )}
      <div className="space-y-5">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-gray-800">Training & Development</h2>
            <p className="text-sm text-gray-500">Request training for yourself or view department programs</p>
          </div>
          <button onClick={() => setShowForm(true)}
            className="flex items-center gap-2 text-white px-4 py-2.5 rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: BRAND }}>
            <i className="ri-add-line"></i> Request Training
          </button>
        </div>

        <div className="rounded-xl px-4 py-3 flex items-start gap-2 border" style={{ background: '#fce7f3', borderColor: BRAND }}>
          <i className="ri-information-line mt-0.5" style={{ color: BRAND }}></i>
          <p className="text-xs" style={{ color: BRAND }}>Training requests follow this approval chain: <strong>HR → HOS → Finance Officer</strong>. Finance must approve before training can commence.</p>
        </div>

        {showForm && (
          <TrainingRequestModal
            onClose={() => setShowForm(false)}
            onSubmit={handleSubmit}
            dept={user.dept || 'Management'}
          />
        )}

        <div className="grid grid-cols-2 gap-4 mb-2">
          {completedPrograms.slice(0, 4).map(p => (
            <div key={p.id} className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 cursor-pointer hover:shadow-md transition-shadow"
              onClick={() => setViewProgram(p)}>
              <div className="flex items-start justify-between mb-2">
                <h4 className="font-semibold text-gray-800 text-sm leading-tight flex-1 pr-2">{p.title}</h4>
                <span className={`text-xs px-2 py-0.5 rounded-full font-bold flex-shrink-0 ${p.status === 'Completed' ? 'bg-green-100 text-green-700' : p.status === 'Ongoing' ? 'bg-blue-100 text-blue-700' : 'bg-amber-100 text-amber-700'}`}>
                  {p.status}
                </span>
              </div>
              <p className="text-xs text-gray-500 mb-2">{p.trainer} · {p.mode}</p>
              <p className="text-xs text-gray-400">{p.start} → {p.end}</p>
              <p className="text-xs text-gray-400 mt-1">{p.enrolled}/{p.capacity} enrolled</p>
              <p className="text-xs mt-2 font-medium" style={{ color: BRAND }}>Click to view objectives →</p>
            </div>
          ))}
        </div>

        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100">
            <h3 className="font-semibold text-gray-700">My Training Requests</h3>
          </div>
          {myReqs.length === 0 ? (
            <div className="py-12 text-center text-gray-400 text-sm">No training requests yet</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">Course</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Submitted</th>
                    <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Cost (KES)</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Stage</th>
                  </tr>
                </thead>
                <tbody>
                  {myReqs.map(r => {
                    const sc = STAGE_CONFIG[r.currentStage] || STAGE_CONFIG['HR'];
                    return (
                      <tr key={r.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3">
                          <p className="font-medium text-gray-800">{r.courseRequested}</p>
                          <p className="text-xs text-gray-400">{r.justification.slice(0, 60)}...</p>
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-500">{r.dateSubmitted}</td>
                        <td className="px-4 py-3 text-right font-semibold text-gray-700">{r.estimatedCost.toLocaleString()}</td>
                        <td className="px-4 py-3">
                          <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap"
                            style={{ color: sc.color, background: sc.bg }}>{sc.label}</span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
      {viewProgram && (
        <ProgramViewModal program={viewProgram} onClose={() => setViewProgram(null)} />
      )}
    </HODLayout>
  );
}
