"use client";

import { useState } from 'react';
import HOSLayout from '../../../components/HOSLayout';
import { useAuth } from '../../../lib/authContext';
import { useTrainingStore } from '../../../lib/trainingStore';
import { initialPrograms, TrainingProgram } from '../../hr/training/trainingData';
import { trainingRequests as INITIAL_REQUESTS, trainingEvaluations, TrainingEvaluation, TrainingRequest } from '../../hr/training/trainingModuleData';
import ProgramViewModal from '../../../components/ProgramViewModal';
import { BookOpen, GraduationCap, Award, Search, Plus, Calendar, Clock, Users, FileText, CheckCircle, AlertCircle } from 'lucide-react';

export default function HOSTrainingPage() {
  const { user } = useAuth();
  const { trainingReqs, updateTrainingReqs } = useTrainingStore();
  const [activeTab, setActiveTab] = useState('overview');
  const [searchQuery, setSearchQuery] = useState('');
  const [showRequestModal, setShowRequestModal] = useState(false);
  const [showReactionModal, setShowReactionModal] = useState(false);
  const [selectedProgram, setSelectedProgram] = useState<any>(null);
  const [selectedCompleted, setSelectedCompleted] = useState<any>(null);
  const [showCertificateUpload, setShowCertificateUpload] = useState(false);
  const [certificateFile, setCertificateFile] = useState<File | null>(null);
  const [formErrors, setFormErrors] = useState<string[]>([]);

  // Local state for requests since HOS submits their own
  const [localRequests, setLocalRequests] = useState<TrainingRequest[]>(INITIAL_REQUESTS);
  const [localEvals, setLocalEvals] = useState<TrainingEvaluation[]>(trainingEvaluations);

  const [trainingForm, setTrainingForm] = useState({
    courseName: '',
    provider: '',
    mode: '',
    regNumber: '',
    cost: '',
    startDate: '',
    endDate: '',
    justification: '',
    expectedOutcomes: '',
    previousTraining: false,
    proformaInvoice: null as File | null,
    admissionLetter: null as File | null,
    email: '',
  });

  const [reactionForm, setReactionForm] = useState({
    contentRelevance: 0,
    facilitatorKnowledge: 0,
    materialsQuality: 0,
    overallSatisfaction: 0,
    wouldRecommend: false,
    feedback: '',
  });

  if (!user) return null;

  const hosRequests = [...trainingReqs, ...localRequests].filter(
    (r: any) => r.employeeId === user?.employeeId || r.employeeId === `HOD-${user?.id}` || r.employeeId === user?.id
  );

  const pendingRequestsCount = hosRequests.filter((r: any) => r.status === 'Pending' || r.status === 'Submitted').length;

  // Build completed programs from evaluations where HOS is the employee
  const hosEmployeeId = user?.employeeId || user?.id || 'hos-001';
  const hosCompleted = localEvals
    .filter((e: any) => e.employeeId === hosEmployeeId || e.employeeName === user?.name)
    .map((e: any) => ({
      id: e.id,
      userId: user?.id,
      programTitle: e.programTitle || 'Training Program',
      completedDate: e.completedDate || e.evalDate,
      score: e.l2PostScore || 85,
      remarks: e.l2Status === 'Pass' ? 'Demonstrated competency in all assessed areas' : 'Needs additional support',
    }))
    .sort((a: any, b: any) => new Date(b.completedDate).getTime() - new Date(a.completedDate).getTime());

  const filteredPrograms = initialPrograms.filter((p: any) =>
    p.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    p.provider.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const validateTrainingForm = () => {
    const errors: string[] = [];
    if (!trainingForm.courseName.trim()) errors.push('Course Name is required');
    if (!trainingForm.provider.trim()) errors.push('Training Provider is required');
    if (!trainingForm.mode) errors.push('Training Mode is required');
    if (!trainingForm.regNumber.trim()) errors.push('Registration Number is required');
    if (trainingForm.regNumber.trim() && (!/[a-zA-Z]/.test(trainingForm.regNumber) || !/[0-9]/.test(trainingForm.regNumber))) errors.push('Registration Number must contain both letters and numbers');
    if (!trainingForm.email.trim() || !/^\S+@\S+\.\S+$/.test(trainingForm.email)) errors.push('A valid email address is required for updates');
    if (!trainingForm.cost.trim()) errors.push('Estimated Cost is required');
    if (!trainingForm.startDate) errors.push('Start Date is required');
    else if (trainingForm.startDate < new Date().toISOString().split('T')[0]) errors.push('Start Date cannot be in the past');
    if (!trainingForm.endDate) errors.push('End Date is required');
    else if (trainingForm.endDate <= trainingForm.startDate) {
      errors.push('End Date must be after Start Date');
    }
    if (!trainingForm.justification.trim()) errors.push('Justification is required');
    if (!trainingForm.expectedOutcomes.trim()) errors.push('Expected Outcomes are required');
    if (!trainingForm.proformaInvoice) errors.push('Proforma Invoice is required');
    if (!trainingForm.admissionLetter) errors.push('Admission Letter is required');
    setFormErrors(errors);
    return errors.length === 0;
  };

  const handleRequestSubmit = () => {
    if (!validateTrainingForm()) return;

    // Create a request that matches the TrainingRequest interface
    const newReq: TrainingRequest = {
      id: `REQ-HOS-${Date.now()}`,
      employeeId: user?.employeeId || `HOS-${user?.id}`,
      employeeName: user?.name || 'HOS User',
      dept: user?.dept || 'Executive',
      courseRequested: trainingForm.courseName,
      justification: trainingForm.justification,
      trainingProvider: trainingForm.provider,
      trainingMode: trainingForm.mode,
      regNo: trainingForm.regNumber,
      estimatedCost: parseFloat(trainingForm.cost) || 0,
      preferredStartDate: trainingForm.startDate,
      preferredEndDate: trainingForm.endDate,
      expectedOutcomes: trainingForm.expectedOutcomes,
      previousTraining: trainingForm.previousTraining,
      dateSubmitted: new Date().toISOString().split('T')[0],
      status: 'Submitted',
      currentStage: 'HR',
    };

    updateTrainingReqs(prev => [newReq, ...prev]);

    setTrainingForm({
      courseName: '',
      provider: '',
      mode: '',
      regNumber: '',
      cost: '',
      startDate: '',
      endDate: '',
      justification: '',
      expectedOutcomes: '',
      previousTraining: false,
      proformaInvoice: null,
      admissionLetter: null,
      email: '',
    });
    setFormErrors([]);
    setShowRequestModal(false);
  };

  const handleReactionSubmit = () => {
    if (selectedCompleted) {
      // Reaction saved
    }
    setShowReactionModal(false);
    setSelectedCompleted(null);
  };

  const handleCertificateUpload = () => {
    if (certificateFile && selectedCompleted) {
      // Certificate uploaded
    }
    setShowCertificateUpload(false);
    setCertificateFile(null);
    setSelectedCompleted(null);
  };

  return (
    <HOSLayout title="Training & Development">
      <div className="p-6 max-w-7xl mx-auto">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Training & Development</h1>
            <p className="text-gray-500 mt-1">Manage your professional growth</p>
          </div>
          <button
            onClick={() => setShowRequestModal(true)}
            className="mt-4 md:mt-0 flex items-center gap-2 bg-[#b22698] text-white px-4 py-2 rounded-lg hover:bg-[#9a1f84] transition-colors"
          >
            <Plus className="w-4 h-4" />
            Request Training
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-white rounded-xl shadow-sm p-4 border border-gray-100">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-[#b22698]/10 rounded-lg flex items-center justify-center">
                <BookOpen className="w-5 h-5 text-[#b22698]" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Available Programs</p>
                <p className="text-xl font-bold text-gray-900">{initialPrograms.length}</p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-xl shadow-sm p-4 border border-gray-100">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center">
                <GraduationCap className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">My Enrolled</p>
                <p className="text-xl font-bold text-gray-900">
                  {initialPrograms.filter((p: any) => p.enrolledStaff?.some((s: any) => s.staffId === user?.employeeId)).length}
                </p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-xl shadow-sm p-4 border border-gray-100">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-50 rounded-lg flex items-center justify-center">
                <Award className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Completed</p>
                <p className="text-xl font-bold text-gray-900">{hosCompleted.length}</p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-xl shadow-sm p-4 border border-gray-100">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-yellow-50 rounded-lg flex items-center justify-center">
                <Clock className="w-5 h-5 text-yellow-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Pending Requests</p>
                <p className="text-xl font-bold text-gray-900">{pendingRequestsCount}</p>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 mb-6">
          <div className="flex border-b border-gray-100">
            {[
              { id: 'overview', label: 'Overview', icon: BookOpen },
              { id: 'completed', label: 'Completed Programs', icon: Award },
              { id: 'requests', label: 'My Requests', icon: FileText },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-5 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                  activeTab === tab.id
                    ? 'border-[#b22698] text-[#b22698]'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
              </button>
            ))}
          </div>

          <div className="p-6">
            {activeTab === 'overview' && (
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold text-gray-900">Available Training Programs</h3>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="text"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      placeholder="Search programs..."
                      className="pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                    />
                  </div>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {filteredPrograms.map((program: any) => (
                    <div
                      key={program.id}
                      onClick={() => setSelectedProgram(program)}
                      className="bg-gray-50 rounded-lg p-4 cursor-pointer hover:bg-gray-100 transition-colors border border-gray-100"
                    >
                      <h4 className="font-semibold text-gray-900">{program.title}</h4>
                      <p className="text-sm text-gray-500 mt-1">{program.provider}</p>
                      <div className="flex items-center gap-4 mt-3 text-xs text-gray-500">
                        <span className="flex items-center gap-1">
                          <Calendar className="w-3 h-3" />
                          {program.duration}
                        </span>
                        <span className="flex items-center gap-1">
                          <Users className="w-3 h-3" />
                          {program.enrolled}/{program.capacity}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {activeTab === 'completed' && (
              <div className="space-y-4">
                <h3 className="text-lg font-semibold text-gray-900">Completed Programs</h3>
                {hosCompleted.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">No completed programs yet</div>
                ) : (
                  <div className="space-y-3">
                    {hosCompleted.map((item: any) => (
                      <div
                        key={item.id}
                        className="bg-gray-50 rounded-lg p-4 border border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4"
                      >
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <CheckCircle className="w-5 h-5 text-green-500" />
                            <h4 className="font-semibold text-gray-900">{item.programTitle}</h4>
                          </div>
                          <p className="text-sm text-gray-500 mt-1">Completed on {item.completedDate}</p>
                          <p className="text-sm text-gray-500">Score: {item.score}%</p>
                          <p className="text-sm text-[#b22698] mt-1">
                            <span className="font-medium">Remarks:</span> {item.remarks || 'Good performance'}
                          </p>
                        </div>
                        <div className="flex gap-2">
                          <button
                            onClick={() => {
                              setSelectedCompleted(item);
                              setShowReactionModal(true);
                            }}
                            className="text-sm text-[#b22698] hover:underline"
                          >
                            Give Feedback
                          </button>
                          <button
                            onClick={() => {
                              setSelectedCompleted(item);
                              setShowCertificateUpload(true);
                            }}
                            className="text-sm text-[#b22698] hover:underline"
                          >
                            Upload Certificate
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {activeTab === 'requests' && (
              <div className="space-y-4">
                <h3 className="text-lg font-semibold text-gray-900">My Training Requests</h3>
                {hosRequests.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">No requests submitted yet</div>
                ) : (
                  <div className="space-y-3">
                    {hosRequests.map((req: any) => (
                      <div key={req.id} className="bg-gray-50 rounded-lg p-4 border border-gray-100">
                        <div className="flex items-center justify-between">
                          <div>
                            <h4 className="font-semibold text-gray-900">{req.courseRequested}</h4>
                            <p className="text-sm text-gray-500">{req.trainingProvider} - {req.trainingMode}</p>
                          </div>
                          <span
                            className={`px-3 py-1 rounded-full text-xs font-medium ${
                              req.status === 'Approved'
                                ? 'bg-green-100 text-green-700'
                                : req.status === 'Rejected'
                                ? 'bg-red-100 text-red-700'
                                : 'bg-yellow-100 text-yellow-700'
                            }`}
                          >
                            {req.status}
                          </span>
                        </div>
                        <p className="text-sm text-gray-500 mt-2">
                          {req.preferredStartDate} to {req.preferredEndDate} | KES {(req.estimatedCost || 0).toLocaleString()}
                        </p>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Request Training Modal */}
        {showRequestModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
              <div className="px-6 py-4 border-b border-gray-100" style={{ background: '#b22698' }}>
                <h2 className="text-xl font-bold text-white">New Training Request</h2>
              </div>
              <div className="p-6 space-y-4">
                {formErrors.length > 0 && (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                    <div className="flex items-center gap-2">
                      <AlertCircle className="w-4 h-4 text-red-500" />
                      <p className="text-sm font-medium text-red-700">Please fill in all required fields:</p>
                    </div>
                    <ul className="mt-1 ml-6 list-disc text-sm text-red-600">
                      {formErrors.map((err, i) => (
                        <li key={i}>{err}</li>
                      ))}
                    </ul>
                  </div>
                )}

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Course Name <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={trainingForm.courseName}
                    onChange={(e) => setTrainingForm({ ...trainingForm, courseName: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Training Provider <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={trainingForm.provider}
                    onChange={(e) => setTrainingForm({ ...trainingForm, provider: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Training Mode <span className="text-red-500">*</span>
                  </label>
                  <div className="flex gap-3">
                    {['Physical (In Person)', 'Virtual (Online)', 'Hybrid (Both)'].map((mode) => (
                      <button
                        key={mode}
                        onClick={() => setTrainingForm({ ...trainingForm, mode })}
                        className={`px-4 py-2 rounded-lg text-sm border transition-colors whitespace-nowrap ${
                          trainingForm.mode === mode
                            ? 'border-[#b22698] bg-[#b22698]/10 text-[#b22698]'
                            : 'border-gray-200 text-gray-600 hover:border-gray-300'
                        }`}
                      >
                        {mode}
                      </button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Registration Number <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={trainingForm.regNumber}
                    onChange={(e) => setTrainingForm({ ...trainingForm, regNumber: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Email Address <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="email"
                    value={trainingForm.email}
                    onChange={(e) => setTrainingForm({ ...trainingForm, email: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                    placeholder="your.email@uwezo.go.ke"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Estimated Cost (KES) <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="number"
                    value={trainingForm.cost}
                    onChange={(e) => setTrainingForm({ ...trainingForm, cost: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Start Date <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="date"
                      value={trainingForm.startDate}
                      onChange={(e) => setTrainingForm({ ...trainingForm, startDate: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      End Date <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="date"
                      value={trainingForm.endDate}
                      onChange={(e) => setTrainingForm({ ...trainingForm, endDate: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Proforma Invoice (PDF) <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="file"
                    accept=".pdf"
                    onChange={(e) => setTrainingForm({ ...trainingForm, proformaInvoice: e.target.files?.[0] || null })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Admission Letter (PDF) <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="file"
                    accept=".pdf"
                    onChange={(e) => setTrainingForm({ ...trainingForm, admissionLetter: e.target.files?.[0] || null })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Justification <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    value={trainingForm.justification}
                    onChange={(e) => setTrainingForm({ ...trainingForm, justification: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Expected Outcomes <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    value={trainingForm.expectedOutcomes}
                    onChange={(e) => setTrainingForm({ ...trainingForm, expectedOutcomes: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>

                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="previousTraining"
                    checked={trainingForm.previousTraining}
                    onChange={(e) => setTrainingForm({ ...trainingForm, previousTraining: e.target.checked })}
                    className="w-4 h-4 rounded border-gray-300 text-[#b22698] focus:ring-[#b22698]"
                  />
                  <label htmlFor="previousTraining" className="text-sm text-gray-700">
                    Have you attended similar training before?
                  </label>
                </div>
              </div>
              <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
                <button
                  onClick={() => {
                    setShowRequestModal(false);
                    setFormErrors([]);
                  }}
                  className="px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handleRequestSubmit}
                  className="px-4 py-2 bg-[#b22698] text-white rounded-lg hover:bg-[#9a1f84]"
                >
                  Submit Request
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Reaction Modal */}
        {showReactionModal && selectedCompleted && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl max-w-lg w-full">
              <div className="p-6 border-b border-gray-100">
                <h2 className="text-xl font-bold text-gray-900">Training Feedback</h2>
                <p className="text-gray-500">{selectedCompleted.programTitle}</p>
              </div>
              <div className="p-6 space-y-4">
                {[
                  { label: 'Content Relevance', key: 'contentRelevance' },
                  { label: 'Facilitator Knowledge', key: 'facilitatorKnowledge' },
                  { label: 'Materials Quality', key: 'materialsQuality' },
                  { label: 'Overall Satisfaction', key: 'overallSatisfaction' },
                ].map((item) => (
                  <div key={item.key}>
                    <label className="block text-sm font-medium text-gray-700 mb-1">{item.label}</label>
                    <div className="flex gap-2">
                      {[1, 2, 3, 4, 5].map((n) => (
                        <button
                          key={n}
                          onClick={() => setReactionForm({ ...reactionForm, [item.key]: n })}
                          className={`w-10 h-10 rounded-lg text-sm font-medium border transition-colors ${
                            reactionForm[item.key as keyof typeof reactionForm] === n
                              ? 'border-[#b22698] bg-[#b22698]/10 text-[#b22698]'
                              : 'border-gray-200 text-gray-600 hover:border-gray-300'
                          }`}
                        >
                          {n}
                        </button>
                      ))}
                    </div>
                  </div>
                ))}
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="recommend"
                    checked={reactionForm.wouldRecommend}
                    onChange={(e) => setReactionForm({ ...reactionForm, wouldRecommend: e.target.checked })}
                    className="w-4 h-4 rounded border-gray-300 text-[#b22698] focus:ring-[#b22698]"
                  />
                  <label htmlFor="recommend" className="text-sm text-gray-700">
                    Would you recommend this training?
                  </label>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Additional Feedback</label>
                  <textarea
                    value={reactionForm.feedback}
                    onChange={(e) => setReactionForm({ ...reactionForm, feedback: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#b22698]"
                  />
                </div>
              </div>
              <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
                <button
                  onClick={() => setShowReactionModal(false)}
                  className="px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handleReactionSubmit}
                  className="px-4 py-2 bg-[#b22698] text-white rounded-lg hover:bg-[#9a1f84]"
                >
                  Submit Feedback
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Certificate Upload Modal */}
        {showCertificateUpload && selectedCompleted && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl max-w-lg w-full">
              <div className="p-6 border-b border-gray-100">
                <h2 className="text-xl font-bold text-gray-900">Upload Certificate</h2>
                <p className="text-gray-500">{selectedCompleted.programTitle}</p>
              </div>
              <div className="p-6 space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Certificate (PDF/Image)</label>
                  <input
                    type="file"
                    accept=".pdf,.png,.jpg,.jpeg"
                    onChange={(e) => setCertificateFile(e.target.files?.[0] || null)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                  />
                </div>
                {certificateFile && (
                  <div className="flex items-center gap-2 text-sm text-green-600">
                    <CheckCircle className="w-4 h-4" />
                    <span>{certificateFile.name}</span>
                  </div>
                )}
              </div>
              <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
                <button
                  onClick={() => {
                    setShowCertificateUpload(false);
                    setCertificateFile(null);
                  }}
                  className="px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handleCertificateUpload}
                  disabled={!certificateFile}
                  className="px-4 py-2 bg-[#b22698] text-white rounded-lg hover:bg-[#9a1f84] disabled:opacity-50"
                >
                  Upload
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Program Detail Modal */}
      {selectedProgram && (
        <ProgramViewModal program={selectedProgram} onClose={() => setSelectedProgram(null)} />
      )}
    </HOSLayout>
  );
}