'use client';
import { useState } from 'react';
import { Appraisal, COMPANY_GOALS, DEPARTMENT_GOALS, RATING_LABELS, RATING_BG, getDeptGoals } from './performanceData';

interface Props {
  appraisals: Appraisal[];
  onUpdate: (updated: Appraisal) => void;
}

export default function HODApprovalTab({ appraisals, onUpdate }: Props) {
  const [selectedDept, setSelectedDept] = useState('All');
  const [viewAppraisal, setViewAppraisal] = useState<Appraisal | null>(null);
  const [hodComments, setHodComments] = useState('');
  const [hodRatings, setHodRatings] = useState<Record<string, number>>({});
  const [toast, setToast] = useState('');

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

  const pendingAppraisals = appraisals.filter(a =>
    a.status === 'Submitted' || a.status === 'Pending HOD Approval'
  );

  const DEPARTMENTS = ['All', ...Array.from(new Set(pendingAppraisals.map(a => a.dept)))];

  const filtered = selectedDept === 'All'
    ? pendingAppraisals
    : pendingAppraisals.filter(a => a.dept === selectedDept);

  const handleOpenReview = (appraisal: Appraisal) => {
    setViewAppraisal(appraisal);
    setHodComments(appraisal.hodComments || '');
    const initRatings: Record<string, number> = {};
    [...appraisal.companyGoalRatings, ...appraisal.deptGoalRatings].forEach(r => {
      if (r.hodRating) initRatings[r.goalId] = r.hodRating;
    });
    setHodRatings(initRatings);
  };

  const handleApprove = () => {
    if (!viewAppraisal) return;
    const updatedCGR = viewAppraisal.companyGoalRatings.map(r => ({
      ...r,
      hodRating: hodRatings[r.goalId] || r.selfRating,
      hodComment: hodComments,
    }));
    const updatedDGR = viewAppraisal.deptGoalRatings.map(r => ({
      ...r,
      hodRating: hodRatings[r.goalId] || r.selfRating,
      hodComment: hodComments,
    }));
    const allRatings = [...updatedCGR, ...updatedDGR].map(r => r.hodRating || r.selfRating);
    const avg = allRatings.length > 0 ? allRatings.reduce((s, v) => s + v, 0) / allRatings.length : 0;
    const updated: Appraisal = {
      ...viewAppraisal,
      status: 'Approved by HOD',
      overallRating: Math.round(avg * 10) / 10,
      hodComments,
      hodApprovedDate: new Date().toISOString().split('T')[0],
      companyGoalRatings: updatedCGR,
      deptGoalRatings: updatedDGR,
    };
    onUpdate(updated);
    setViewAppraisal(null);
    showToast(`${viewAppraisal.name}'s appraisal approved successfully.`);
  };

  const handleReject = () => {
    if (!viewAppraisal) return;
    const updated: Appraisal = {
      ...viewAppraisal,
      status: 'Pending Self-Assessment',
      hodComments: `Returned for revision: ${hodComments}`,
    };
    onUpdate(updated);
    setViewAppraisal(null);
    showToast(`${viewAppraisal.name}'s appraisal returned for revision.`);
  };

  return (
    <div>
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2">
          <div className="w-5 h-5 flex items-center justify-center"><i className="ri-checkbox-circle-line text-lg"></i></div>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="flex items-center justify-between mb-5">
        <div>
          <h3 className="font-semibold text-gray-800">HOD Approval Queue</h3>
          <p className="text-xs text-gray-500 mt-0.5">{pendingAppraisals.length} appraisal{pendingAppraisals.length !== 1 ? 's' : ''} pending HOD review</p>
        </div>
        <div className="flex gap-2">
          {DEPARTMENTS.map(d => (
            <button
              key={d}
              onClick={() => setSelectedDept(d)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${selectedDept === d ? 'text-white' : 'bg-gray-100 text-gray-600'}`}
              style={selectedDept === d ? { background: '#b828a0' } : {}}
            >
              {d}
            </button>
          ))}
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="bg-white rounded-xl border border-gray-100 p-12 text-center">
          <div className="w-14 h-14 flex items-center justify-center mx-auto mb-3 rounded-2xl" style={{ background: '#fdf2fb' }}>
            <i className="ri-checkbox-circle-line text-3xl" style={{ color: '#b828a0' }}></i>
          </div>
          <p className="text-gray-500 font-medium">All caught up!</p>
          <p className="text-gray-400 text-sm mt-1">No appraisals pending HOD approval</p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map(a => (
            <div key={a.id} className="bg-white border border-gray-100 rounded-xl p-4 shadow-sm hover:border-pink-200 transition-colors">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm" style={{ background: '#b828a0' }}>
                    {a.avatar}
                  </div>
                  <div>
                    <p className="font-semibold text-gray-800 text-sm">{a.name}</p>
                    <p className="text-xs text-gray-500">{a.role} · {a.dept} · {a.period}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <p className="text-xs text-gray-400">Submitted</p>
                    <p className="text-xs font-medium text-gray-700">{a.submittedDate || '—'}</p>
                  </div>
                  <span className="text-xs px-2 py-1 rounded-full font-medium bg-orange-100 text-orange-700">{a.status}</span>
                  <button
                    onClick={() => handleOpenReview(a)}
                    className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap"
                    style={{ background: '#b828a0' }}
                  >
                    <div className="w-4 h-4 flex items-center justify-center"><i className="ri-eye-line text-sm"></i></div>
                    Review
                  </button>
                </div>
              </div>
              <div className="mt-3 flex items-center gap-4 text-xs text-gray-500">
                <span>{a.companyGoalRatings.length} company goal{a.companyGoalRatings.length !== 1 ? 's' : ''} rated</span>
                <span>{a.deptGoalRatings.length} dept goal{a.deptGoalRatings.length !== 1 ? 's' : ''} rated</span>
                {a.selfAssessmentComments && <span className="text-green-600">Self-assessment submitted</span>}
              </div>
            </div>
          ))}
        </div>
      )}

      {viewAppraisal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl w-full max-w-3xl max-h-[92vh] flex flex-col shadow-2xl">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b828a0' }}>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full flex items-center justify-center bg-white/20 text-white font-bold text-sm">
                  {viewAppraisal.avatar}
                </div>
                <div>
                  <h2 className="text-white font-bold">{viewAppraisal.name}</h2>
                  <p className="text-pink-200 text-xs">{viewAppraisal.role} · {viewAppraisal.dept} · {viewAppraisal.period}</p>
                </div>
              </div>
              <button onClick={() => setViewAppraisal(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="flex-1 overflow-y-auto p-6 space-y-5">
              {viewAppraisal.selfAssessmentComments && (
                <div className="bg-blue-50 border border-blue-100 rounded-xl p-4">
                  <p className="text-xs font-semibold text-blue-700 mb-1">Employee Self-Assessment Comments</p>
                  <p className="text-sm text-gray-700">{viewAppraisal.selfAssessmentComments}</p>
                </div>
              )}

              {viewAppraisal.companyGoalRatings.length > 0 && (
                <div>
                  <h4 className="font-semibold text-gray-800 text-sm mb-3">Company Goal Ratings</h4>
                  <div className="space-y-3">
                    {viewAppraisal.companyGoalRatings.map(r => {
                      const goal = COMPANY_GOALS.find(g => g.id === r.goalId);
                      return (
                        <div key={r.goalId} className="border border-gray-100 rounded-xl p-4">
                          <p className="text-sm font-semibold text-gray-800 mb-1">{goal?.title || r.goalId}</p>
                          <p className="text-xs text-gray-500 mb-3">{goal?.kra}</p>
                          <div className="grid grid-cols-2 gap-3">
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">Employee Self-Rating</p>
                              <div className="flex items-center gap-2">
                                <span className={`text-xs px-2 py-1 rounded-full font-medium ${RATING_BG[r.selfRating]}`}>{r.selfRating}/5 — {RATING_LABELS[r.selfRating]}</span>
                              </div>
                              {r.selfComment && <p className="text-xs text-gray-500 mt-1 italic">"{r.selfComment}"</p>}
                            </div>
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">Your HOD Rating</p>
                              <div className="flex gap-1">
                                {[1, 2, 3, 4, 5].map(v => (
                                  <button
                                    key={v}
                                    onClick={() => setHodRatings(prev => ({ ...prev, [r.goalId]: v }))}
                                    className={`w-8 h-8 rounded-lg text-sm font-bold cursor-pointer transition-all ${(hodRatings[r.goalId] || r.selfRating) === v ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                                    style={(hodRatings[r.goalId] || r.selfRating) === v ? { background: '#b828a0' } : {}}
                                  >
                                    {v}
                                  </button>
                                ))}
                              </div>
                              <p className="text-xs text-gray-400 mt-1">{RATING_LABELS[hodRatings[r.goalId] || r.selfRating]}</p>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {viewAppraisal.deptGoalRatings.length > 0 && (
                <div>
                  <h4 className="font-semibold text-gray-800 text-sm mb-3">Department Goal Ratings</h4>
                  <div className="space-y-3">
                    {viewAppraisal.deptGoalRatings.map(r => {
                      const goal = DEPARTMENT_GOALS.find(g => g.id === r.goalId);
                      return (
                        <div key={r.goalId} className="border border-gray-100 rounded-xl p-4">
                          <p className="text-sm font-semibold text-gray-800 mb-1">{goal?.title || r.goalId}</p>
                          <p className="text-xs text-gray-500 mb-3">{goal?.department} Department</p>
                          <div className="grid grid-cols-2 gap-3">
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">Employee Self-Rating</p>
                              <span className={`text-xs px-2 py-1 rounded-full font-medium ${RATING_BG[r.selfRating]}`}>{r.selfRating}/5 — {RATING_LABELS[r.selfRating]}</span>
                              {r.selfComment && <p className="text-xs text-gray-500 mt-1 italic">"{r.selfComment}"</p>}
                            </div>
                            <div>
                              <p className="text-xs font-medium text-gray-500 mb-1">Your HOD Rating</p>
                              <div className="flex gap-1">
                                {[1, 2, 3, 4, 5].map(v => (
                                  <button
                                    key={v}
                                    onClick={() => setHodRatings(prev => ({ ...prev, [r.goalId]: v }))}
                                    className={`w-8 h-8 rounded-lg text-sm font-bold cursor-pointer transition-all ${(hodRatings[r.goalId] || r.selfRating) === v ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                                    style={(hodRatings[r.goalId] || r.selfRating) === v ? { background: '#b828a0' } : {}}
                                  >
                                    {v}
                                  </button>
                                ))}
                              </div>
                              <p className="text-xs text-gray-400 mt-1">{RATING_LABELS[hodRatings[r.goalId] || r.selfRating]}</p>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">HOD Comments</label>
                <textarea
                  value={hodComments}
                  onChange={e => setHodComments(e.target.value)}
                  rows={3}
                  maxLength={500}
                  placeholder="Add your overall comments on this employee's performance..."
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none resize-none focus:ring-2 focus:ring-pink-300"
                />
              </div>
            </div>

            <div className="px-6 pb-6 flex gap-3">
              <button
                onClick={handleReject}
                className="flex-1 py-3 rounded-xl border-2 border-red-200 text-red-600 text-sm font-semibold cursor-pointer whitespace-nowrap hover:bg-red-50 transition-colors"
              >
                Return for Revision
              </button>
              <button
                onClick={handleApprove}
                className="flex-1 py-3 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: '#b828a0' }}
              >
                Approve Appraisal
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
