'use client';
import { useState } from 'react';
type SkillLevel = 'Beginner' | 'Intermediate' | 'Advanced' | 'Expert';
type SkillCategory = 'Technical' | 'Soft Skills' | 'Compliance' | 'Leadership';
type SkillDefinition = { id: string; name: string; category: SkillCategory; description: string; targetLevel: SkillLevel; applicableDepts: string[]; applicablePositions: string[] };
type EmployeeSkill = { employeeId: string; employeeName: string; dept: string; position: string; skillId: string; currentLevel: SkillLevel; targetLevel: SkillLevel; gapExists: boolean; suggestedTraining?: string };
const skillDefinitions: SkillDefinition[] = [
  { id: 'SK001', name: 'Data Analysis & Reporting', category: 'Technical', description: 'Ability to collect, analyze, and present data using tools like Excel, Power BI, SPSS', targetLevel: 'Advanced', applicableDepts: ['Monitoring & Evaluation', 'ICT'], applicablePositions: ['M&E Officer', 'Data Analyst'] },
  { id: 'SK002', name: 'Public Procurement Law', category: 'Compliance', description: 'Knowledge of PPRA regulations, PPADA 2015, and public procurement procedures', targetLevel: 'Expert', applicableDepts: ['Procurement'], applicablePositions: ['Procurement Officer'] },
  { id: 'SK003', name: 'Leadership & Team Management', category: 'Leadership', description: 'Ability to lead teams, delegate effectively, manage performance and conflict', targetLevel: 'Advanced', applicableDepts: ['All Departments'], applicablePositions: ['Manager', 'Coordinator'] },
  { id: 'SK004', name: 'Network Security & Infrastructure', category: 'Technical', description: 'Skills in configuring, monitoring, and securing network infrastructure', targetLevel: 'Expert', applicableDepts: ['ICT'], applicablePositions: ['Network Engineer'] },
  { id: 'SK005', name: 'Communication & Stakeholder Engagement', category: 'Soft Skills', description: 'Effective written and verbal communication with internal and external stakeholders', targetLevel: 'Advanced', applicableDepts: ['Corporate Communication'], applicablePositions: ['Communications Officer'] },
  { id: 'SK006', name: 'Financial Management & Budgeting', category: 'Compliance', description: 'Public sector financial management, IFMIS, budget preparation and monitoring', targetLevel: 'Advanced', applicableDepts: ['Procurement', 'Finance'], applicablePositions: ['Finance Officer'] },
];
const employeeSkills: EmployeeSkill[] = [
  { employeeId: 'UF001', employeeName: 'Jane Mwangi', dept: 'Monitoring & Evaluation', position: 'M&E Officer', skillId: 'SK001', currentLevel: 'Intermediate', targetLevel: 'Advanced', gapExists: true, suggestedTraining: 'Advanced Data Analysis with Power BI' },
  { employeeId: 'UF002', employeeName: 'Peter Otieno', dept: 'ICT', position: 'Systems Administrator', skillId: 'SK004', currentLevel: 'Advanced', targetLevel: 'Expert', gapExists: true, suggestedTraining: 'Cisco CCNA Network Security' },
  { employeeId: 'UF005', employeeName: 'Grace Wanjiku', dept: 'Procurement', position: 'Procurement Officer', skillId: 'SK002', currentLevel: 'Intermediate', targetLevel: 'Expert', gapExists: true, suggestedTraining: 'Public Procurement & Asset Disposal Act Training' },
  { employeeId: 'UF009', employeeName: 'Alice Odhiambo', dept: 'ICT', position: 'Software Developer', skillId: 'SK004', currentLevel: 'Intermediate', targetLevel: 'Expert', gapExists: true, suggestedTraining: 'AWS Cloud Practitioner Certification' },
  { employeeId: 'UF003', employeeName: 'Mary Kamau', dept: 'Corporate Communication', position: 'Communications Officer', skillId: 'SK005', currentLevel: 'Advanced', targetLevel: 'Advanced', gapExists: false },
  { employeeId: 'UF012', employeeName: 'Brian Omondi', dept: 'ICT', position: 'Network Engineer', skillId: 'SK004', currentLevel: 'Intermediate', targetLevel: 'Expert', gapExists: true, suggestedTraining: 'Cisco CCNA Network Security' },
];

const LEVEL_ORDER: SkillLevel[] = ['Beginner', 'Intermediate', 'Advanced', 'Expert'];
const LEVEL_COLORS: Record<SkillLevel, string> = {
  Beginner: 'bg-gray-100 text-gray-600',
  Intermediate: 'bg-blue-100 text-blue-700',
  Advanced: 'bg-purple-100 text-purple-700',
  Expert: 'bg-green-100 text-green-700',
};
const CAT_COLORS: Record<SkillCategory, string> = {
  Technical: 'bg-blue-100 text-blue-700',
  'Soft Skills': 'bg-orange-100 text-orange-700',
  Compliance: 'bg-red-100 text-red-700',
  Leadership: 'bg-purple-100 text-purple-700',
};

function LevelBar({ current, target }: { current: SkillLevel; target: SkillLevel }) {
  const ci = LEVEL_ORDER.indexOf(current);
  const ti = LEVEL_ORDER.indexOf(target);
  return (
    <div className="flex items-center gap-1">
      {LEVEL_ORDER.map((l, i) => (
        <div key={l} title={l}
          className={`h-2 flex-1 rounded-full transition-all ${i <= ci ? '' : 'bg-gray-100'}`}
          style={i <= ci ? { background: i >= ti ? '#22c55e' : '#b22698' } : {}}></div>
      ))}
    </div>
  );
}

export default function SkillPlansTab() {
  const [activeView, setActiveView] = useState<'skills' | 'gap'>('skills');
  const [filterCat, setFilterCat] = useState<string>('All');
  const [filterDept, setFilterDept] = useState<string>('All');

  const depts = ['All', ...Array.from(new Set(employeeSkills.map(e => e.dept)))];
  const cats: string[] = ['All', 'Technical', 'Soft Skills', 'Compliance', 'Leadership'];

  const gapEmployees = employeeSkills.filter(e =>
    e.gapExists &&
    (filterDept === 'All' || e.dept === filterDept)
  );

  const filteredSkills = skillDefinitions.filter(s =>
    (filterCat === 'All' || s.category === filterCat)
  );

  const gapCount = employeeSkills.filter(e => e.gapExists).length;
  const noGapCount = employeeSkills.filter(e => !e.gapExists).length;

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Defined Skills', value: String(skillDefinitions.length), icon: 'ri-lightbulb-line', color: 'text-purple-600 bg-purple-50' },
          { label: 'Employees Assessed', value: String(new Set(employeeSkills.map(e => e.employeeId)).size), icon: 'ri-user-search-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Skill Gaps Found', value: String(gapCount), icon: 'ri-alert-line', color: 'text-red-600 bg-red-50' },
          { label: 'Skills Met', value: String(noGapCount), icon: 'ri-checkbox-circle-line', color: 'text-green-600 bg-green-50' },
        ].map(({ label, value, icon, color }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-xl ${color} flex items-center justify-center mb-3`}>
              <i className={`${icon} text-lg`}></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{value}</p>
            <p className="text-sm text-gray-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100">
        <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
          <div className="flex gap-1 bg-gray-100 rounded-xl p-1">
            {(['skills', 'gap'] as const).map(v => (
              <button key={v} onClick={() => setActiveView(v)}
                className={`px-4 py-1.5 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap transition-all ${activeView === v ? 'bg-white shadow text-gray-800' : 'text-gray-500'}`}>
                {v === 'skills' ? 'Skill Definitions' : 'Gap Analysis'}
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            {activeView === 'skills' && cats.map(c => (
              <button key={c} onClick={() => setFilterCat(c)}
                className="px-3 py-1 rounded-full text-xs font-medium cursor-pointer transition-all whitespace-nowrap"
                style={filterCat === c ? { background: '#b22698', color: 'white' } : { background: '#f3f4f6', color: '#6b7280' }}>
                {c}
              </button>
            ))}
            {activeView === 'gap' && depts.map(d => (
              <button key={d} onClick={() => setFilterDept(d)}
                className="px-3 py-1 rounded-full text-xs font-medium cursor-pointer transition-all whitespace-nowrap"
                style={filterDept === d ? { background: '#b22698', color: 'white' } : { background: '#f3f4f6', color: '#6b7280' }}>
                {d}
              </button>
            ))}
          </div>
        </div>

        {activeView === 'skills' && (
          <div className="p-5 grid grid-cols-2 gap-4">
            {filteredSkills.map(s => (
              <div key={s.id} className="border border-gray-100 rounded-xl p-4 hover:shadow-md transition-shadow">
                <div className="flex items-start justify-between mb-2">
                  <div className="flex-1">
                    <h4 className="text-sm font-bold text-gray-800">{s.name}</h4>
                    <p className="text-xs text-gray-400 mt-0.5">{s.description}</p>
                  </div>
                  <span className={`ml-3 px-2.5 py-0.5 rounded-full text-xs font-semibold whitespace-nowrap ${CAT_COLORS[s.category]}`}>{s.category}</span>
                </div>
                <div className="flex items-center gap-3 mt-3">
                  <span className="text-xs text-gray-400">Target Level:</span>
                  <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${LEVEL_COLORS[s.targetLevel]}`}>{s.targetLevel}</span>
                </div>
                <div className="mt-2">
                  <p className="text-xs text-gray-400 mb-1">Applies to:</p>
                  <div className="flex flex-wrap gap-1">
                    {s.applicableDepts.map(d => (
                      <span key={d} className="px-2 py-0.5 bg-gray-100 rounded-full text-xs text-gray-600">{d}</span>
                    ))}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {activeView === 'gap' && (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-100">
                  {['Employee','Department','Skill','Current Level','Target Level','Gap','Suggested Training'].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>
                {gapEmployees.map((e, idx) => {
                  const skill = skillDefinitions.find(s => s.id === e.skillId);
                  return (
                    <tr key={idx} 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">{e.employeeName}</p>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">{e.dept}</td>
                      <td className="px-4 py-3">
                        <p className="text-sm text-gray-700">{skill?.name || e.skillId}</p>
                        {skill && <span className={`text-xs px-1.5 py-0.5 rounded-full ${CAT_COLORS[skill.category]}`}>{skill.category}</span>}
                      </td>
                      <td className="px-4 py-3">
                        <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${LEVEL_COLORS[e.currentLevel]}`}>{e.currentLevel}</span>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${LEVEL_COLORS[e.targetLevel]}`}>{e.targetLevel}</span>
                      </td>
                      <td className="px-4 py-3 min-w-[120px]">
                        <LevelBar current={e.currentLevel} target={e.targetLevel} />
                        <p className="text-xs text-red-500 mt-0.5 font-medium">
                          {LEVEL_ORDER.indexOf(e.targetLevel) - LEVEL_ORDER.indexOf(e.currentLevel)} level(s) gap
                        </p>
                      </td>
                      <td className="px-4 py-3">
                        {e.suggestedTraining ? (
                          <span className="px-2.5 py-1 bg-pink-50 text-pink-700 rounded-lg text-xs font-medium border border-pink-100">{e.suggestedTraining}</span>
                        ) : (
                          <span className="text-xs text-gray-400">—</span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            {gapEmployees.length === 0 && (
              <div className="text-center py-10 text-gray-400 text-sm">No skill gaps found for selected department</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
