'use client';
import { useState, useEffect } from 'react';
import EmployeeLayout from '../../../components/EmployeeLayout';
import { useAuth } from '../../../lib/authContext';
import { useTrainingStore } from '../../../lib/trainingStore';

const BRAND = '#B22698';

const TRAINING_MODES = ['Physical (In Person)', 'Virtual (Online)', 'Hybrid (Both)'];

const STAGE_STEPS = [
  { stage: 'HR', label: 'HR Manager', icon: 'ri-user-settings-line', color: '#d97706', bg: '#fef3c7' },
  { stage: 'HOS', label: 'Head of Secretariat', icon: 'ri-building-line', color: BRAND, bg: '#fce7f3' },
  { stage: 'Finance', label: 'Finance Officer', icon: 'ri-money-dollar-circle-line', color: '#2563eb', bg: '#dbeafe' },
];

function ApprovalChain({ currentStage }: { currentStage: string }) {
  const isComplete = currentStage === 'Complete';
  const isRejected = currentStage === 'Rejected';

  return (
    <div className="flex items-center gap-1 flex-wrap mt-3">
      {STAGE_STEPS.map((step, i) => {
        const stageOrder = ['HR', 'HOS', 'Finance', 'Complete'];
        const currentIdx = stageOrder.indexOf(currentStage);
        const stepIdx = stageOrder.indexOf(step.stage);
        const done = isComplete || currentIdx > stepIdx;
        const active = !isComplete && !isRejected && currentStage === step.stage;
        return (
          <div key={step.stage} className="flex items-center gap-1">
            <div className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${done ? 'bg-green-100 text-green-700' : active ? 'text-white' : 'bg-gray-100 text-gray-400'}`}
              style={active ? { background: step.color } : {}}>
              <div className="w-4 h-4 flex items-center justify-center">
                {done ? <i className="ri-check-line text-green-600 text-xs"></i> : <i className={`${step.icon} text-xs`}></i>}
              </div>
              <span className="hidden sm:inline">{step.label}</span>
              <span className="sm:hidden">{step.stage}</span>
            </div>
            {i < STAGE_STEPS.length - 1 && (
              <i className={`ri-arrow-right-line text-xs ${done ? 'text-green-400' : 'text-gray-300'}`}></i>
            )}
          </div>
        );
      })}
      <i className={`ri-arrow-right-line text-xs ${isComplete ? 'text-green-400' : 'text-gray-300'}`}></i>
      <div className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold ${isComplete ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}`}>
        <div className="w-4 h-4 flex items-center justify-center">
          <i className={`${isComplete ? 'ri-checkbox-circle-fill' : 'ri-checkbox-circle-line'} text-xs`}></i>
        </div>
        Approved
      </div>
    </div>
  );
}

export default function EmployeeTrainingRequestsPage() {
  const { user } = useAuth();
  const { trainingReqs, updateTrainingReqs } = useTrainingStore();
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'overview' | 'requests' | 'records'>('overview');
  const [showForm, setShowForm] = useState(false);
  const [toast, setToast] = useState('');
  const [form, setForm] = useState({
    courseRequested: '',
    trainingProvider: '',
    trainingMode: '',
    regNo: '',
    estimatedCost: '',
    proformaInvoice: '',
    admissionLetter: '',
    preferredStartDate: '',
    preferredEndDate: '',
    justification: '',
    expectedOutcomes: '',
    previousTraining: false,
  });
  const [errors, setErrors] = useState<string[]>([]);

  const empId = user?.employeeId || user?.id || '';

  // Fetch training requests from API
  const fetchTrainingRequests = async () => {
    if (!empId) return;
    setLoading(true);
    try {
      const response = await fetch(`/api/training/requests?employeeId=${empId}`);
      if (response.ok) {
        const data = await response.json();
        // Update the store with fetched data
        data.forEach((req: any) => {
          updateTrainingReqs((prev: any[]) => {
            if (prev.some(r => r.id === req.id)) return prev;
            return [req, ...prev];
          });
        });
      }
    } catch (error) {
      console.error('Error fetching training requests:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user) {
      fetchTrainingRequests();
    }
  }, [user, empId]);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const errs: string[] = [];
    if (!form.courseRequested.trim()) errs.push('Course name is required.');
    if (!form.trainingProvider.trim()) errs.push('Training provider is required.');
    if (!form.trainingMode) errs.push('Training mode is required.');
    if (!form.regNo.trim()) errs.push('Registration number is required.');
    if (!form.preferredStartDate) errs.push('Preferred start date is required.');
    if (!form.preferredEndDate) errs.push('Preferred end date is required.');
    if (form.preferredStartDate && form.preferredEndDate && form.preferredEndDate < form.preferredStartDate) errs.push('End date must be after start date.');
    if (!form.justification.trim()) errs.push('Justification is required.');
    if (!form.expectedOutcomes.trim()) errs.push('Expected outcomes are required.');
    if (errs.length > 0) { setErrors(errs); return; }
    setErrors([]);

    try {
      const response = await fetch('/api/training/requests', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employeeId: empId,
          employeeEmail: user?.email,
          employeeName: user?.name || 'Unknown',
          dept: user?.dept || 'General',
          courseRequested: form.courseRequested,
          justification: form.justification,
          trainingProvider: form.trainingProvider,
          trainingMode: form.trainingMode,
          regNo: form.regNo,
          estimatedCost: Number(form.estimatedCost) || 0,
          proformaInvoice: form.proformaInvoice,
          admissionLetter: form.admissionLetter,
          preferredStartDate: form.preferredStartDate,
          preferredEndDate: form.preferredEndDate,
          expectedOutcomes: form.expectedOutcomes,
          previousTraining: form.previousTraining,
        })
      });

      if (response.ok) {
        const newRequest = await response.json();
        updateTrainingReqs((prev: any[]) => [newRequest, ...prev]);
        
        setForm({
          courseRequested: '',
          trainingProvider: '',
          trainingMode: '',
          regNo: '',
          estimatedCost: '',
          proformaInvoice: '',
          admissionLetter: '',
          preferredStartDate: '',
          preferredEndDate: '',
          justification: '',
          expectedOutcomes: '',
          previousTraining: false,
        });
        setShowForm(false);
        showToast('Training request submitted! HR will review and respond.');
      } else {
        const error = await response.json();
        throw new Error(error.error || 'Failed to submit');
      }
    } catch (error) {
      console.error('Error submitting training request:', error);
      showToast('Failed to submit request. Please try again.');
    }
  };

  const set = (k: string, v: string | boolean) => setForm(f => ({ ...f, [k]: v }));

  const stageLabel: Record<string, string> = {
    HR: 'Pending HR Review',
    HOS: 'Pending HOS Approval',
    Finance: 'Pending Finance Approval',
    Complete: 'Fully Approved',
    Rejected: 'Rejected',
  };

  const stageColor: Record<string, string> = {
    HR: '#d97706', HOS: BRAND, Finance: '#2563eb', Complete: '#16a34a', Rejected: '#dc2626',
  };

  const stageBg: Record<string, string> = {
    HR: '#fef3c7', HOS: '#fce7f3', Finance: '#dbeafe', Complete: '#dcfce7', Rejected: '#fee2e2',
  };

  if (!user) return null;

  const myRequests = trainingReqs.filter(r => r.employeeId === empId);

  if (loading && myRequests.length === 0) {
    return (
      <EmployeeLayout title="My Training Requests">
        <div className="flex justify-center items-center h-64">
          <div className="w-8 h-8 border-2 border-pink-300 border-t-pink-600 rounded-full animate-spin"></div>
        </div>
      </EmployeeLayout>
    );
  }

  return (
    <EmployeeLayout title="My Training Requests">
      {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="max-w-4xl mx-auto space-y-5">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-gray-800">My Training Requests</h2>
            <p className="text-sm text-gray-500">Track your training requests through the 3-stage approval chain</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 hover:opacity-90"
            style={{ background: BRAND }}>
            <i className="ri-add-line"></i> New Request
          </button>
        </div>

        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
          <p className="text-xs font-semibold text-gray-500 uppercase mb-3">Approval Chain</p>
          <div className="flex items-center gap-2 flex-wrap">
            {STAGE_STEPS.map((step, i) => (
              <div key={step.stage} className="flex items-center gap-2">
                <div className="flex items-center gap-2 px-3 py-2 rounded-xl border" style={{ borderColor: step.color + '40', background: step.bg }}>
                  <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: step.color }}>{i + 1}</div>
                  <div>
                    <p className="text-xs font-semibold" style={{ color: step.color }}>{step.label}</p>
                  </div>
                </div>
                <i className="ri-arrow-right-line text-gray-300 text-sm"></i>
              </div>
            ))}
            <div className="flex items-center gap-2 px-3 py-2 rounded-xl border border-green-200 bg-green-50">
              <i className="ri-checkbox-circle-line text-green-600"></i>
              <p className="text-xs font-semibold text-green-700">Fully Approved</p>
            </div>
          </div>
        </div>

        {showForm && (
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-100" style={{ background: BRAND }}>
              <h3 className="font-bold text-white text-lg">New Training Request</h3>
              <p className="text-pink-200 text-sm mt-0.5">Your request will be reviewed by HR → HOS → Finance</p>
            </div>
            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              {errors.length > 0 && (
                <div className="bg-red-50 border border-red-200 rounded-xl p-4">
                  {errors.map((e, i) => <p key={i} className="text-xs text-red-600 flex items-center gap-1"><i className="ri-close-circle-line"></i>{e}</p>)}
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Course / Training Name *</label>
                  <input value={form.courseRequested} onChange={e => set('courseRequested', e.target.value)}
                    placeholder="e.g. Advanced Leadership Program"
                    className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400" />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Training Provider *</label>
                  <input value={form.trainingProvider} onChange={e => set('trainingProvider', e.target.value)}
                    placeholder="e.g. Kenya School of Government"
                    className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400" />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1.5">Training Mode *</label>
                <div className="flex gap-2 flex-wrap">
                  {TRAINING_MODES.map(m => (
                    <button key={m} type="button" onClick={() => set('trainingMode', m)}
                      className="px-4 py-2.5 rounded-xl text-sm font-medium border cursor-pointer transition-all"
                      style={form.trainingMode === m ? { background: BRAND + '15', borderColor: BRAND, color: BRAND } : { background: '#fff', borderColor: '#e5e7eb', color: '#4b5563' }}>
                      {m}
                    </button>
                  ))}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Registration Number *</label>
                  <input value={form.regNo} onChange={e => set('regNo', e.target.value)}
                    placeholder="Your registration number"
                    className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400" />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Estimated Cost (KES)</label>
                  <input type="number" value={form.estimatedCost} onChange={e => set('estimatedCost', e.target.value)}
                    placeholder="0"
                    className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400" />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Attach Proforma Invoice (PDF)</label>
                  <label className="border-2 border-dashed border-gray-200 rounded-xl p-4 text-center hover:border-pink-300 transition-colors cursor-pointer block">
                    <div className="w-8 h-8 flex items-center justify-center mx-auto mb-1">
                      <i className="ri-upload-cloud-2-line text-2xl text-gray-400"></i>
                    </div>
                    <p className="text-xs text-gray-500">Click to upload PDF</p>
                    <input type="file" accept=".pdf" className="hidden" onChange={e => set('proformaInvoice', e.target.files?.[0]?.name || '')} />
                  </label>
                  {form.proformaInvoice && <p className="text-xs text-green-600 mt-1"><i className="ri-check-line mr-1"></i>{form.proformaInvoice}</p>}
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Attach Admission Letter</label>
                  <label className="border-2 border-dashed border-gray-200 rounded-xl p-4 text-center hover:border-pink-300 transition-colors cursor-pointer block">
                    <div className="w-8 h-8 flex items-center justify-center mx-auto mb-1">
                      <i className="ri-upload-cloud-2-line text-2xl text-gray-400"></i>
                    </div>
                    <p className="text-xs text-gray-500">Click to upload PDF</p>
                    <input type="file" accept=".pdf" className="hidden" onChange={e => set('admissionLetter', e.target.files?.[0]?.name || '')} />
                  </label>
                  {form.admissionLetter && <p className="text-xs text-green-600 mt-1"><i className="ri-check-line mr-1"></i>{form.admissionLetter}</p>}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">Start Date *</label>
                  <input type="date" value={form.preferredStartDate} onChange={e => set('preferredStartDate', e.target.value)}
                    className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400" />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1.5">End Date *</label>
                  <input type="date" value={form.preferredEndDate} onChange={e => set('preferredEndDate', e.target.value)}
                    className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400" />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1.5">Justification *</label>
                <textarea value={form.justification} onChange={e => set('justification', e.target.value)}
                  rows={3} maxLength={500} placeholder="Explain why this training is needed and how it benefits your work..."
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400 resize-none" />
                <p className="text-xs text-gray-400 text-right mt-1">{form.justification.length}/500</p>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1.5">Expected Outcomes *</label>
                <textarea value={form.expectedOutcomes} onChange={e => set('expectedOutcomes', e.target.value)}
                  rows={2} maxLength={500} placeholder="What skills or knowledge do you expect to gain?"
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-pink-400 resize-none" />
              </div>

              <label className="flex items-center gap-3 cursor-pointer">
                <div className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${form.previousTraining ? 'border-pink-500 bg-pink-500' : 'border-gray-300'}`}
                  onClick={() => set('previousTraining', !form.previousTraining)}>
                  {form.previousTraining && <i className="ri-check-line text-white text-xs"></i>}
                </div>
                <span className="text-sm text-gray-700">Have you attended similar training before?</span>
              </label>

              <div className="flex gap-3 pt-2">
                <button type="button" onClick={() => { setShowForm(false); setErrors([]); }}
                  className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap hover:bg-gray-50">
                  Cancel
                </button>
                <button type="submit"
                  className="px-6 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap hover:opacity-90"
                  style={{ background: BRAND }}>
                  Submit Request
                </button>
              </div>
            </form>
          </div>
        )}

        {myRequests.length === 0 && !showForm ? (
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-12 text-center">
            <div className="w-14 h-14 flex items-center justify-center mx-auto mb-4 rounded-2xl" style={{ background: '#fdf0fc' }}>
              <i className="ri-graduation-cap-line text-3xl" style={{ color: BRAND }}></i>
            </div>
            <h3 className="font-semibold text-gray-800 mb-2">No Training Requests Yet</h3>
            <p className="text-sm text-gray-400 mb-4">Submit a training request and track its progress through the approval chain.</p>
            <button onClick={() => setShowForm(true)}
              className="px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap hover:opacity-90"
              style={{ background: BRAND }}>
              Submit Your First Request
            </button>
          </div>
        ) : (
          <div className="space-y-4">
            {myRequests.map(r => {
              const sc = stageColor[r.currentStage] || '#6b7280';
              const sb = stageBg[r.currentStage] || '#f3f4f6';
              const sl = stageLabel[r.currentStage] || r.currentStage;
              return (
                <div key={r.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1 pr-4">
                      <div className="flex items-center gap-2 mb-1">
                        <p className="font-bold text-gray-800">{r.courseRequested}</p>
                        <span className="text-xs font-mono text-gray-400">{r.id}</span>
                      </div>
                      <p className="text-xs text-gray-500 line-clamp-2">{r.justification?.split('Expected Outcomes:')[0]?.replace('Training Provider:', 'Provider:')}</p>
                    </div>
                    <span className="inline-flex px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap flex-shrink-0"
                      style={{ color: sc, background: sb }}>{sl}</span>
                  </div>

                  <div className="grid grid-cols-3 gap-3 mb-4 text-xs">
                    <div className="bg-gray-50 rounded-lg p-2.5">
                      <p className="text-gray-400 mb-0.5">Submitted</p>
                      <p className="font-semibold text-gray-700">{r.dateSubmitted ? new Date(r.dateSubmitted).toLocaleDateString() : '-'}</p>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-2.5">
                      <p className="text-gray-400 mb-0.5">Preferred Dates</p>
                      <p className="font-semibold text-gray-700">{r.preferredStartDate} → {r.preferredEndDate}</p>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-2.5">
                      <p className="text-gray-400 mb-0.5">Estimated Cost</p>
                      <p className="font-semibold text-gray-700">KES {r.estimatedCost?.toLocaleString() || 0}</p>
                    </div>
                  </div>

                  <div>
                    <p className="text-xs font-semibold text-gray-500 mb-2">Approval Progress</p>
                    <ApprovalChain currentStage={r.currentStage} />
                  </div>

                  {r.currentStage === 'Rejected' && r.rejectReason && (
                    <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-xl">
                      <p className="text-xs font-semibold text-red-700 mb-1">Rejection Reason</p>
                      <p className="text-xs text-red-600">{r.rejectReason}</p>
                      {r.rejectedBy && <p className="text-xs text-red-400 mt-1">Rejected by: {r.rejectedBy}</p>}
                    </div>
                  )}

                  {r.currentStage === 'Complete' && (
                    <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded-xl flex items-center justify-between">
                      <div>
                        <p className="text-xs font-semibold text-green-700">Fully Approved!</p>
                        <p className="text-xs text-green-600">All 3 approvers have signed off. Training can commence.</p>
                      </div>
                      <button onClick={() => {
                        const content = `UWEZO FUND\nTRAINING APPROVAL LETTER\n\nRef: ${r.id}\nEmployee: ${r.employeeName}\nDept: ${r.dept}\nCourse: ${r.courseRequested}\nDates: ${r.preferredStartDate} to ${r.preferredEndDate}\nCost: KES ${r.estimatedCost?.toLocaleString() || 0}\n\nApproval Trail:\nHR: ${r.hrApprovedBy || 'N/A'} on ${r.hrApprovedOn || 'N/A'}\nHOS: ${r.hosApprovedBy || 'N/A'} on ${r.hosApprovedOn || 'N/A'}\nFinance: ${r.financeApprovedBy || 'N/A'} on ${r.financeApprovedOn || 'N/A'}\n\nUwezo Fund HRMS v2.0.1`;
                        const blob = new Blob([content], { type: 'text/plain' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `Training-Approval-${r.id}.txt`;
                        a.click();
                        URL.revokeObjectURL(url);
                      }}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-white cursor-pointer whitespace-nowrap"
                        style={{ background: '#16a34a' }}>
                        <i className="ri-download-line"></i> Download Letter
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </EmployeeLayout>
  );
}