'use client';
import { useState, useMemo } from 'react';
import HRLayout from '../../../components/HRLayout';
import { initialAppraisals, Appraisal, AppraisalStatus, RATING_LABELS, RATING_BG } from './performanceData';
import GoalsTab from './GoalsTab';
import CyclesTab from './CyclesTab';
import PIPTab from './PIPTab';
import PerformanceReportsTab from './PerformanceReportsTab';
import HODApprovalTab from './HODApprovalTab';
import HRAppraisalViewModal from './HRAppraisalViewModal';
import StaffPerformanceTab from './StaffPerformanceTab';

type MainTab = 'goals' | 'hr' | 'staff' | 'hod' | 'pip' | 'reports';

const mainTabDefs: { id: MainTab; label: string; icon: string }[] = [
  { id: 'goals', label: 'Goals & Objectives', icon: 'ri-flag-line' },
  { id: 'hr', label: 'HR View', icon: 'ri-admin-line' },
  { id: 'staff', label: 'Staff Performance', icon: 'ri-team-line' },
  { id: 'hod', label: 'HOD Approval', icon: 'ri-user-star-line' },
  { id: 'pip', label: 'PIP', icon: 'ri-alarm-warning-line' },
  { id: 'reports', label: 'Reports', icon: 'ri-bar-chart-2-line' },
];

const statusColors: Record<AppraisalStatus, string> = {
  'Pending Self-Assessment': 'bg-gray-100 text-gray-600',
  'Submitted': 'bg-blue-100 text-blue-700',
  'Pending HOD Approval': 'bg-orange-100 text-orange-700',
  'Approved by HOD': 'bg-purple-100 text-purple-700',
  'Completed': 'bg-green-100 text-green-700',
};

const DEPARTMENTS = ['All', 'M&E', 'ICT', 'Finance', 'Operations', 'Communications', 'HR'];
const STATUSES: (AppraisalStatus | 'All')[] = ['All', 'Pending Self-Assessment', 'Submitted', 'Pending HOD Approval', 'Approved by HOD', 'Completed'];
const TYPES = ['All', 'Employee', 'Intern'];

export default function PerformancePage() {
  const [appraisals, setAppraisals] = useState<Appraisal[]>(initialAppraisals);
  const [mainTab, setMainTab] = useState<MainTab>('hr');
  const [search, setSearch] = useState('');
  const [deptFilter, setDeptFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState<AppraisalStatus | 'All'>('All');
  const [typeFilter, setTypeFilter] = useState('All');
  const [viewAppraisal, setViewAppraisal] = useState<Appraisal | null>(null);

  const pendingHOD = useMemo(() =>
    appraisals.filter(a => a.status === 'Submitted' || a.status === 'Pending HOD Approval').length,
    [appraisals]
  );

  const handleUpdate = (updated: Appraisal) => {
    setAppraisals(prev => prev.map(a => a.id === updated.id ? updated : a));
  };

  const stats = useMemo(() => ({
    total: appraisals.length,
    pending: appraisals.filter(a => a.status === 'Pending Self-Assessment').length,
    submitted: appraisals.filter(a => a.status === 'Submitted' || a.status === 'Pending HOD Approval').length,
    approved: appraisals.filter(a => a.status === 'Approved by HOD' || a.status === 'Completed').length,
    avgRating: (() => {
      const rated = appraisals.filter(a => a.overallRating > 0);
      return rated.length > 0 ? (rated.reduce((s, a) => s + a.overallRating, 0) / rated.length).toFixed(1) : '—';
    })(),
  }), [appraisals]);

  const filtered = useMemo(() => appraisals.filter(a =>
    (deptFilter === 'All' || a.dept === deptFilter) &&
    (statusFilter === 'All' || a.status === statusFilter) &&
    (typeFilter === 'All' || a.employeeType === typeFilter) &&
    (a.name.toLowerCase().includes(search.toLowerCase()) || a.employeeId.toLowerCase().includes(search.toLowerCase()))
  ), [appraisals, deptFilter, statusFilter, typeFilter, search]);

  return (
    <HRLayout title="Performance Appraisals" breadcrumb="HR">
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm mb-6">
        <div className="flex overflow-x-auto">
          {mainTabDefs.map(tab => (
            <button
              key={tab.id}
              onClick={() => setMainTab(tab.id)}
              className={`flex items-center gap-2 px-5 py-3.5 text-sm font-medium whitespace-nowrap border-b-2 transition-all cursor-pointer`}
              style={mainTab === tab.id ? { color: '#b828a0', borderColor: '#b828a0', background: 'rgba(178,38,152,0.03)' } : { color: '#6b7280', borderColor: 'transparent' }}
            >
              <div className="w-4 h-4 flex items-center justify-center"><i className={`${tab.icon} text-sm`}></i></div>
              {tab.label}
              {tab.id === 'hod' && pendingHOD > 0 && (
                <span className="bg-orange-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full min-w-[18px] text-center leading-none">{pendingHOD}</span>
              )}
            </button>
          ))}
        </div>
      </div>

      {mainTab === 'goals' && <GoalsTab />}
      {mainTab === 'hr' && (
        <>
          <div className="grid grid-cols-5 gap-4 mb-6">
            {[
              { label: 'Total Appraisals', value: String(stats.total), icon: 'ri-file-list-3-line', bg: 'bg-purple-500' },
              { label: 'Pending Self-Assessment', value: String(stats.pending), icon: 'ri-time-line', bg: 'bg-gray-400' },
              { label: 'Pending HOD Review', value: String(stats.submitted), icon: 'ri-user-star-line', bg: 'bg-orange-500' },
              { label: 'Approved / Completed', value: String(stats.approved), icon: 'ri-checkbox-circle-line', bg: 'bg-green-500' },
              { label: 'Avg Rating', value: stats.avgRating !== '—' ? `${stats.avgRating}/5` : '—', icon: 'ri-star-line', bg: 'bg-yellow-500' },
            ].map(s => (
              <div key={s.label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
                <div className={`w-9 h-9 rounded-xl flex items-center justify-center ${s.bg} mb-3`}>
                  <i className={`${s.icon} text-white text-base`}></i>
                </div>
                <p className="text-2xl font-bold text-gray-800">{s.value}</p>
                <p className="text-xs text-gray-500 mt-0.5">{s.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">
              <div className="flex items-center gap-3 flex-wrap">
                <div className="relative">
                  <input
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                    placeholder="Search by name or ID..."
                    className="bg-gray-50 border border-gray-200 rounded-lg px-4 py-2 text-sm w-52 outline-none pr-8"
                  />
                  <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2">
                    <i className="ri-search-line text-gray-400 text-sm"></i>
                  </div>
                </div>
                <select value={deptFilter} onChange={e => setDeptFilter(e.target.value)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none bg-gray-50 pr-8">
                  {DEPARTMENTS.map(d => <option key={d} value={d}>{d === 'All' ? 'All Departments' : d}</option>)}
                </select>
                <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none bg-gray-50 pr-8">
                  {TYPES.map(t => <option key={t} value={t}>{t === 'All' ? 'All Types' : t}</option>)}
                </select>
                <select value={statusFilter} onChange={e => setStatusFilter(e.target.value as any)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none bg-gray-50 pr-8">
                  {STATUSES.map(s => <option key={s} value={s}>{s === 'All' ? 'All Statuses' : s}</option>)}
                </select>
                <span className="text-xs text-gray-400 ml-auto">{filtered.length} record{filtered.length !== 1 ? 's' : ''}</span>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    {['Employee', 'Department', 'Type', 'Period', 'Status', 'Overall Rating', 'HOD', 'PIP', 'Action'].map(h => (
                      <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide whitespace-nowrap">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {filtered.length === 0 && (
                    <tr><td colSpan={9} className="text-center py-12 text-gray-400 text-sm">No appraisals found</td></tr>
                  )}
                  {filtered.map(a => (
                    <tr key={a.id} className="border-b border-gray-50 hover:bg-pink-50/20 transition-colors">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: '#b828a0' }}>{a.avatar}</div>
                          <div>
                            <p className="text-sm font-medium text-gray-800">{a.name}</p>
                            <p className="text-xs text-gray-400">{a.employeeId}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">{a.dept}</td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${a.employeeType === 'Intern' ? 'bg-yellow-100 text-yellow-700' : 'bg-blue-100 text-blue-700'}`}>
                          {a.employeeType}
                        </span>
                      </td>
                      <td className="px-4 py-3"><span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full whitespace-nowrap">{a.period}</span></td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-1 rounded-full font-medium whitespace-nowrap ${statusColors[a.status]}`}>{a.status}</span>
                      </td>
                      <td className="px-4 py-3">
                        {a.overallRating > 0 ? (
                          <div className="flex items-center gap-2">
                            <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${RATING_BG[Math.round(a.overallRating)]}`}>
                              {a.overallRating.toFixed(1)}/5
                            </span>
                            <span className="text-xs text-gray-500">{RATING_LABELS[Math.round(a.overallRating)]}</span>
                          </div>
                        ) : (
                          <span className="text-xs text-gray-400">—</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">{a.hodName}</td>
                      <td className="px-4 py-3">
                        {a.pipStatus === 'Active' ? (
                          <button
                            onClick={() => setMainTab('pip')}
                            className="text-xs px-2 py-1 rounded-full font-medium bg-red-100 text-red-700 cursor-pointer whitespace-nowrap hover:bg-red-200 transition-colors"
                          >
                            Active PIP
                          </button>
                        ) : a.overallRating > 0 && a.overallRating < 2.5 ? (
                          <button
                            onClick={() => setMainTab('pip')}
                            className="text-xs px-2 py-1 rounded-full font-medium bg-orange-100 text-orange-700 cursor-pointer whitespace-nowrap hover:bg-orange-200 transition-colors"
                          >
                            PIP Needed
                          </button>
                        ) : (
                          <span className="text-xs text-gray-400">—</span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <button
                          onClick={() => setViewAppraisal(a)}
                          className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium text-white cursor-pointer whitespace-nowrap"
                          style={{ background: '#b828a0' }}
                        >
                          <div className="w-3 h-3 flex items-center justify-center"><i className="ri-eye-line text-xs"></i></div>
                          View
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
      {mainTab === 'staff' && <StaffPerformanceTab />}
      {mainTab === 'hod' && <HODApprovalTab appraisals={appraisals} onUpdate={handleUpdate} />}
      {mainTab === 'pip' && <PIPTab />}
      {mainTab === 'reports' && <PerformanceReportsTab />}

      {viewAppraisal && (
        <HRAppraisalViewModal
          appraisal={viewAppraisal}
          onClose={() => setViewAppraisal(null)}
        />
      )}
    </HRLayout>
  );
}
