'use client';
import { useState } from 'react';
import { individualDevelopmentPlans, IDP } from './trainingModuleData';

const STATUS_COLORS: Record<string, string> = {
  'Not Started': 'bg-gray-100 text-gray-500',
  'In Progress': 'bg-blue-100 text-blue-700',
  'Completed': 'bg-green-100 text-green-700',
};

export default function IDPTab() {
  const [idps, setIdps] = useState<IDP[]>(individualDevelopmentPlans);
  const [selected, setSelected] = useState<IDP | null>(null);
  const [showCreate, setShowCreate] = useState(false);
  const [toast, setToast] = useState('');
  const [createForm, setCreateForm] = useState({ employeeName: '', dept: '', period: '', managerName: '' });

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

  const handleCreate = () => {
    if (!createForm.employeeName || !createForm.dept) return;
    const newIDP: IDP = {
      id: `IDP${String(idps.length + 1).padStart(3, '0')}`,
      employeeId: `UF0${idps.length + 10}`,
      employeeName: createForm.employeeName,
      dept: createForm.dept,
      period: createForm.period || 'Q1–Q4 2026',
      managerSigned: false,
      managerName: createForm.managerName || 'TBD',
      createdDate: new Date().toISOString().split('T')[0],
      overallProgress: 0,
      status: 'Active',
      goals: [],
    };
    setIdps(prev => [...prev, newIDP]);
    showToast('IDP created successfully!');
    setShowCreate(false);
    setCreateForm({ employeeName: '', dept: '', period: '', managerName: '' });
  };

  const totalGoals = idps.reduce((s, i) => s + i.goals.length, 0);
  const completedGoals = idps.reduce((s, i) => s + i.goals.filter(g => g.status === 'Completed').length, 0);
  const avgProgress = idps.length > 0 ? Math.round(idps.reduce((s, i) => s + i.overallProgress, 0) / idps.length) : 0;

  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: 'Active IDPs', value: idps.length, icon: 'ri-file-user-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Total Goals', value: totalGoals, icon: 'ri-focus-3-line', color: 'text-purple-600 bg-purple-50' },
          { label: 'Goals Completed', value: completedGoals, icon: 'ri-checkbox-circle-line', color: 'text-green-600 bg-green-50' },
          { label: 'Avg. Progress', value: `${avgProgress}%`, icon: 'ri-progress-4-line', color: 'text-pink-600 bg-pink-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">
          <div>
            <h3 className="font-semibold text-gray-800">Individual Development Plans</h3>
            <p className="text-xs text-gray-400 mt-0.5">{idps.length} active plans across all departments</p>
          </div>
          <button onClick={() => setShowCreate(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 IDP
          </button>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                {['Employee', 'Department', 'Period', 'Goals', 'Progress %', '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>
              {idps.map(idp => (
                <tr key={idp.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-gray-800">{idp.employeeName}</p>
                    <p className="text-xs text-gray-400">{idp.employeeId}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">{idp.dept}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{idp.period}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5">
                      <span className="text-sm font-semibold text-gray-800">{idp.goals.length}</span>
                      <span className="text-xs text-gray-400">goals</span>
                      <span className="text-xs text-green-600 font-medium">({idp.goals.filter(g => g.status === 'Completed').length} done)</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-20 bg-gray-100 rounded-full h-1.5">
                        <div className="h-1.5 rounded-full" style={{ width: `${idp.overallProgress}%`, background: '#b22698' }}></div>
                      </div>
                      <span className="text-xs font-bold" style={{ color: '#b22698' }}>{idp.overallProgress}%</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex flex-col gap-1">
                      <span className={`px-2.5 py-1 rounded-full text-xs font-semibold w-fit ${idp.status === 'Active' ? 'bg-blue-100 text-blue-700' : idp.status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
                        {idp.status}
                      </span>
                      <span className={`text-xs ${idp.managerSigned ? 'text-green-600' : 'text-orange-500'}`}>
                        {idp.managerSigned ? 'Manager signed' : 'Awaiting sign-off'}
                      </span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <button onClick={() => setSelected(idp)}
                      className="text-xs px-3 py-1.5 rounded-lg cursor-pointer font-medium text-white whitespace-nowrap hover:opacity-80"
                      style={{ background: '#b22698' }}>
                      View
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {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">Individual Development Plan</h2>
                <p className="text-pink-200 text-sm">{selected.employeeName} · {selected.period}</p>
              </div>
              <button onClick={() => 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-5">
              <div className="grid grid-cols-3 gap-4 pb-4 border-b border-gray-100">
                <div>
                  <p className="text-xs text-gray-400 mb-1">Employee</p>
                  <p className="text-sm font-semibold text-gray-800">{selected.employeeName}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-400 mb-1">Department</p>
                  <p className="text-sm font-semibold text-gray-800">{selected.dept}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-400 mb-1">Overall Progress</p>
                  <div className="flex items-center gap-2">
                    <div className="flex-1 bg-gray-100 rounded-full h-2">
                      <div className="h-2 rounded-full" style={{ width: `${selected.overallProgress}%`, background: '#b22698' }}></div>
                    </div>
                    <span className="text-sm font-bold" style={{ color: '#b22698' }}>{selected.overallProgress}%</span>
                  </div>
                </div>
              </div>

              <div>
                <h3 className="font-semibold text-gray-800 mb-3">Development Goals</h3>
                {selected.goals.length === 0 ? (
                  <p className="text-sm text-gray-400 text-center py-6">No goals defined yet</p>
                ) : (
                  <div className="space-y-3">
                    {selected.goals.map(g => (
                      <div key={g.id} className="border border-gray-100 rounded-xl p-4">
                        <div className="flex items-start justify-between gap-3 mb-2">
                          <p className="text-sm font-medium text-gray-800 flex-1">{g.goal}</p>
                          <span className={`px-2 py-0.5 rounded-full text-xs font-semibold whitespace-nowrap ${STATUS_COLORS[g.status]}`}>{g.status}</span>
                        </div>
                        <div className="flex items-center gap-4 mb-2">
                          <p className="text-xs text-gray-400">Linked: <span className="text-gray-600 font-medium">{g.linkedTraining}</span></p>
                          <p className="text-xs text-gray-400">Due: <span className="text-gray-600">{g.targetDate}</span></p>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-gray-100 rounded-full h-1.5">
                            <div className="h-1.5 rounded-full" style={{ width: `${g.progress}%`, background: g.progress === 100 ? '#22c55e' : '#b22698' }}></div>
                          </div>
                          <span className="text-xs font-semibold text-gray-600">{g.progress}%</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <div className="border-t border-gray-100 pt-4 flex items-center justify-between">
                <div>
                  <p className="text-xs text-gray-400 mb-1">Manager Sign-off</p>
                  <div className="flex items-center gap-2">
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center ${selected.managerSigned ? 'bg-green-100' : 'bg-gray-100'}`}>
                      <i className={`text-xs ${selected.managerSigned ? 'ri-check-line text-green-600' : 'ri-time-line text-gray-400'}`}></i>
                    </div>
                    <span className="text-sm text-gray-700">{selected.managerName}</span>
                    {selected.managerSigned && <span className="text-xs text-green-600 font-medium">Signed</span>}
                  </div>
                </div>
                {!selected.managerSigned && (
                  <button onClick={() => {
                    setIdps(prev => prev.map(i => i.id === selected.id ? { ...i, managerSigned: true } : i));
                    setSelected(prev => prev ? { ...prev, managerSigned: true } : null);
                    showToast('IDP signed off by manager');
                  }}
                    className="px-4 py-2 rounded-xl text-white text-sm font-semibold cursor-pointer hover:opacity-90"
                    style={{ background: '#b22698' }}>
                    Sign & Approve IDP
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {showCreate && (
        <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-md">
            <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">Create New IDP</h2>
              <button onClick={() => setShowCreate(false)} 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: 'Employee Name *', key: 'employeeName', placeholder: 'e.g. Jane Mwangi' },
                { label: 'Department *', key: 'dept', placeholder: 'e.g. ICT' },
                { label: 'Period', key: 'period', placeholder: 'e.g. Q1–Q4 2026' },
                { label: 'Manager Name', key: 'managerName', placeholder: 'e.g. Dr. Faith Mutua' },
              ].map(({ label, key, placeholder }) => (
                <div key={key}>
                  <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
                  <input value={(createForm as any)[key]} onChange={e => setCreateForm(p => ({ ...p, [key]: e.target.value }))}
                    placeholder={placeholder}
                    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={handleCreate}
                  className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer hover:opacity-90"
                  style={{ background: '#b22698' }}>
                  Create IDP
                </button>
                <button onClick={() => setShowCreate(false)}
                  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>
      )}
    </div>
  );
}
