'use client';
import { useEffect, useState } from 'react';
import { useAuth } from '../../../lib/authContext';
import InternLayout from '../../../components/InternLayout';
import { initialAppraisals, Appraisal, PIP, RATING_LABELS, RATING_BG, COMPANY_GOALS } from '../../hr/performance/performanceData';
import SelfAssessmentForm from '../../employee/performance/SelfAssessmentForm';
import WorkPlanCard, { WorkPlan, WorkPlanTask } from '../../employee/performance/WorkPlanCard';
import KPIGauge, { KPIType } from '../../employee/performance/KPIGauge';
import QuarterlyTargetCard, { QuarterlyTargetType } from '../../employee/performance/QuarterlyTargetCard';
import IPICard, { IPIType } from '../../employee/performance/IPICard';
import { motion } from 'framer-motion';
import { usePerformanceStore } from '../../../lib/performanceStore';
import { updateKpi, updateQuarterlyTarget, updateIpi } from '../../../lib/performanceApi';

type Tab = 'workplan' | 'kpis' | 'quarterly' | 'ipis' | 'appraisals' | 'pip';

const BRAND = '#b828a0';

export default function InternPerformancePage() {
  // ========== ALL HOOKS FIRST (before any conditional returns) ==========
  const { user } = useAuth();
  const { getDeptTargets, getCommentsFor, markRead } = usePerformanceStore();
  
  const DEPT_TARGETS = getDeptTargets(user?.dept || '');
  
  const [appraisals, setAppraisals] = useState<Appraisal[]>(initialAppraisals);
  const [assessingAppraisal, setAssessingAppraisal] = useState<Appraisal | null>(null);
  const [viewAppraisal, setViewAppraisal] = useState<Appraisal | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>('workplan');
  const [toast, setToast] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  
  const [workPlans, setWorkPlans] = useState<WorkPlan[]>([]);
  const [showAddWorkPlan, setShowAddWorkPlan] = useState(false);
  const [showAddTask, setShowAddTask] = useState<string | null>(null);
  const [newWorkPlan, setNewWorkPlan] = useState({ objective: '', target: '', dueDate: '', linkedTargetId: '', status: 'Not Started' as const, progress: 0 });
  const [newTask, setNewTask] = useState({ title: '', objective: '', expectedOutput: '', startDate: '', endDate: '', remarks: '' });

  const [kpis, setKpis] = useState<KPIType[]>([]);
  const [showAddKPI, setShowAddKPI] = useState(false);
  const [newKPI, setNewKPI] = useState<{ title: string; description: string; targetValue: string; measurementMethod: string; frequency: 'Monthly' | 'Quarterly' | 'Annual'; targetDeadline: string; weight: string; linkedGoalId: string }>({ 
    title: '', description: '', targetValue: '', measurementMethod: '', frequency: 'Monthly', targetDeadline: '', weight: '', linkedGoalId: '' 
  });

  const [ipis, setIpis] = useState<IPIType[]>([]);
  const [showAddIPI, setShowAddIPI] = useState(false);
  const [newIPI, setNewIPI] = useState({ workPlanTaskId: '', workPlanId: '', indicatorName: '', target: '', measurementCriteria: '', expectedPerformance: '', ratingScale: '' });
  
  const [pips, setPips] = useState<PIP[]>([]);
  const [quarterlyTargets, setQuarterlyTargets] = useState<QuarterlyTargetType[]>([]);
  const [showAddQuarterly, setShowAddQuarterly] = useState(false);
  const [newQuarterly, setNewQuarterly] = useState({ quarter: 'Q1', year: '2026', title: '', kpiMeasurement: '', expectedOutcome: '', completionTimeline: '', weight: '10', linkedWorkPlanId: '' });

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

  // Helper function to parse tasks from API response
  const parseWorkPlanTasks = (workPlan: any): WorkPlan => {
    let tasks: WorkPlanTask[] = [];
    if (workPlan.tasks) {
      if (Array.isArray(workPlan.tasks)) {
        tasks = workPlan.tasks;
      } else if (typeof workPlan.tasks === 'string') {
        try {
          tasks = JSON.parse(workPlan.tasks);
        } catch (e) {
          tasks = [];
        }
      }
    }
    return {
      id: workPlan.id,
      employeeId: workPlan.employeeId,
      objective: workPlan.objective,
      target: workPlan.target,
      progress: workPlan.progress || 0,
      dueDate: workPlan.dueDate,
      status: workPlan.status || 'Not Started',
      linkedTargetId: workPlan.linkedTargetId || '',
      tasks: tasks
    };
  };

  // Load data from API on mount
  useEffect(() => {
    const loadAllData = async () => {
      const employeeIdentifier = user?.employeeId || user?.id;
      if (!employeeIdentifier) {
        console.log('No employee identifier found');
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      try {
        const employeeIdEncoded = encodeURIComponent(employeeIdentifier);
        
        console.log('Loading data for employee:', employeeIdentifier);
        
        // Fetch work plans
        const workPlansRes = await fetch(`/api/performance/workplans?employeeId=${employeeIdEncoded}`);
        if (workPlansRes.ok) {
          let workPlansData = await workPlansRes.json();
          console.log('Raw work plans from API:', workPlansData);
          
          if (Array.isArray(workPlansData)) {
            const parsedWorkPlans = workPlansData.map(parseWorkPlanTasks);
            setWorkPlans(parsedWorkPlans);
            console.log('Parsed work plans:', parsedWorkPlans);
          } else {
            setWorkPlans([]);
          }
        } else {
          console.error('Failed to fetch work plans:', workPlansRes.status);
          setWorkPlans([]);
        }
        
        // Fetch KPIs
        const kpisRes = await fetch(`/api/performance/kpis?employeeId=${employeeIdEncoded}`);
        if (kpisRes.ok) {
          const kpisData = await kpisRes.json();
          setKpis(Array.isArray(kpisData) ? kpisData : []);
        } else {
          setKpis([]);
        }
        
        // Fetch quarterly targets
        const quarterlyRes = await fetch(`/api/performance/quarterly?employeeId=${employeeIdEncoded}`);
        if (quarterlyRes.ok) {
          const quarterlyData = await quarterlyRes.json();
          setQuarterlyTargets(Array.isArray(quarterlyData) ? quarterlyData : []);
        } else {
          setQuarterlyTargets([]);
        }
        
        // Fetch IPIs
        const ipisRes = await fetch(`/api/performance/ipis?employeeId=${employeeIdEncoded}`);
        if (ipisRes.ok) {
          const ipisData = await ipisRes.json();
          setIpis(Array.isArray(ipisData) ? ipisData : []);
        } else {
          setIpis([]);
        }
        
        // Fetch PIPs
        const pipsRes = await fetch(`/api/performance/pips?employeeId=${employeeIdEncoded}`);
        if (pipsRes.ok) {
          const pipsData = await pipsRes.json();
          setPips(Array.isArray(pipsData) ? pipsData : []);
        } else {
          setPips([]);
        }
        
      } catch (error) {
        console.error('Error loading performance data:', error);
        showToast('Error loading data', 'error');
        setWorkPlans([]);
        setKpis([]);
        setQuarterlyTargets([]);
        setIpis([]);
        setPips([]);
      } finally {
        setIsLoading(false);
      }
    };

    loadAllData();
  }, [user?.employeeId, user?.id]);

  // ========== CONDITIONAL RETURN ==========
  if (!user) return null;

  const empId = user.employeeId || user.id || '';
  const myAppraisals = appraisals.filter(a => a.employeeId === empId);
  const myPIPs = pips.filter(p => p.employeeId === empId);
  const myComments = getCommentsFor(empId);
  const unreadComments = myComments.filter(c => !c.read);

  // ========== WORK PLAN UPDATE HANDLER ==========
  const handleUpdateWorkPlan = async (planId: string, updates: Partial<WorkPlan>) => {
    try {
      const updateData: any = { ...updates };
      if (updates.tasks && Array.isArray(updates.tasks)) {
        updateData.tasks = JSON.stringify(updates.tasks);
      }
      
      const response = await fetch(`/api/performance/workplans/${planId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updateData)
      });
      
      if (response.ok) {
        const updatedPlan = await response.json();
        const parsedPlan = parseWorkPlanTasks(updatedPlan);
        setWorkPlans(prev => prev.map(wp => wp.id === planId ? parsedPlan : wp));
        return true;
      }
      return false;
    } catch (error) {
      console.error('Error updating work plan:', error);
      return false;
    }
  };

  // ========== CREATE HANDLERS ==========
  const handleAddWorkPlan = async () => {
    if (!newWorkPlan.objective || !newWorkPlan.target) {
      showToast('Please fill in objective and target', 'error');
      return;
    }
    
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    
    setIsLoading(true);
    try {
      // Create a default task
      const defaultTask: WorkPlanTask = {
        id: `TASK-${Date.now()}`,
        title: newWorkPlan.objective.substring(0, 50),
        objective: newWorkPlan.objective,
        expectedOutput: newWorkPlan.target,
        startDate: new Date().toISOString().split('T')[0],
        endDate: newWorkPlan.dueDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        status: 'Not Started',
        remarks: '',
        weeklyProgress: []
      };
      
      const response = await fetch('/api/performance/workplans', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employeeId: employeeIdentifier,
          objective: newWorkPlan.objective,
          target: newWorkPlan.target,
          dueDate: newWorkPlan.dueDate,
          linkedTargetId: newWorkPlan.linkedTargetId || '',
          quarter: 'Q2',
          year: new Date().getFullYear(),
          status: 'Not Started',
          progress: 0,
          tasks: JSON.stringify([defaultTask])
        })
      });
      
      if (response.ok) {
        const savedWorkPlan = await response.json();
        const parsedPlan = parseWorkPlanTasks(savedWorkPlan);
        setWorkPlans(prev => [...prev, parsedPlan]);
        setNewWorkPlan({ objective: '', target: '', dueDate: '', linkedTargetId: '', status: 'Not Started', progress: 0 });
        setShowAddWorkPlan(false);
        showToast('Work plan created successfully!', 'success');
      } else {
        const error = await response.text();
        console.error('Error response:', error);
        showToast('Error creating work plan', 'error');
      }
    } catch (error) {
      console.error('Error saving work plan:', error);
      showToast('Error creating work plan', 'error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddTask = async (planId: string) => {
    if (!newTask.title || !newTask.objective) {
      showToast('Please fill in task title and objective', 'error');
      return;
    }
    
    const plan = workPlans.find(wp => wp.id === planId);
    if (!plan) return;
    
    const newTaskObj: WorkPlanTask = {
      id: `T-${planId}-${Date.now()}`,
      title: newTask.title,
      objective: newTask.objective,
      expectedOutput: newTask.expectedOutput,
      startDate: newTask.startDate,
      endDate: newTask.endDate,
      status: 'Not Started',
      remarks: newTask.remarks,
      weeklyProgress: [],
    };
    
    const existingTasks = Array.isArray(plan.tasks) ? plan.tasks : [];
    const updatedTasks: WorkPlanTask[] = [...existingTasks, newTaskObj];
    
    const success = await handleUpdateWorkPlan(planId, { tasks: updatedTasks });
    
    if (success) {
      setWorkPlans(prev => prev.map(wp => 
        wp.id === planId ? { ...wp, tasks: updatedTasks } : wp
      ));
      setNewTask({ title: '', objective: '', expectedOutput: '', startDate: '', endDate: '', remarks: '' });
      setShowAddTask(null);
      showToast('Task added successfully!', 'success');
    } else {
      showToast('Error adding task', 'error');
    }
  };

  const handleUpdateProgress = async (planId: string, week: number, progress: number, notes: string) => {
    const plan = workPlans.find(wp => wp.id === planId);
    if (!plan) return;
    
    const currentProgress = plan.progress || 0;
    const newProgress = Math.min(100, currentProgress + progress);
    const newStatus = newProgress >= 100 ? 'Completed' : newProgress > 0 ? 'In Progress' : 'Not Started';
    
    const existingTasks = Array.isArray(plan.tasks) ? plan.tasks : [];
    const weeklyEntry = { week, progress, notes, date: new Date().toISOString() };
    
    let updatedTasks: WorkPlanTask[] = [...existingTasks];
    if (updatedTasks.length > 0) {
      updatedTasks = updatedTasks.map((task, index) => {
        if (index === 0) {
          const existingWeeklyProgress = Array.isArray(task.weeklyProgress) ? task.weeklyProgress : [];
          return {
            ...task,
            weeklyProgress: [...existingWeeklyProgress, weeklyEntry],
            status: newProgress >= 100 ? 'Completed' : newProgress > 0 ? 'In Progress' : 'Not Started'
          };
        }
        return task;
      });
    }
    
    // Update local state
    setWorkPlans(prev => prev.map(wp => wp.id === planId ? {
      ...wp,
      progress: newProgress,
      status: newStatus,
      tasks: updatedTasks,
    } : wp));
    
    // Save to backend
    const success = await handleUpdateWorkPlan(planId, { 
      progress: newProgress, 
      status: newStatus,
      tasks: updatedTasks 
    });
    
    if (success) {
      showToast(`Week ${week} progress updated to ${newProgress}%!`, 'success');
    } else {
      showToast('Error saving progress', 'error');
      // Revert on error
      setWorkPlans(prev => prev.map(wp => wp.id === planId ? plan : wp));
    }
  };

  const handleAddKPI = async () => {
    if (!newKPI.title || !newKPI.targetValue) {
      showToast('Please fill in KPI title and target value', 'error');
      return;
    }
    
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    
    setIsLoading(true);
    try {
      const response = await fetch('/api/performance/kpis', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employeeId: employeeIdentifier,
          title: newKPI.title,
          description: newKPI.description,
          targetValue: newKPI.targetValue,
          measurementMethod: newKPI.measurementMethod,
          frequency: newKPI.frequency,
          targetDeadline: newKPI.targetDeadline,
          linkedGoalId: newKPI.linkedGoalId,
          weight: newKPI.weight ? parseInt(newKPI.weight) : 10
        })
      });
      
      if (response.ok) {
        const savedKPI = await response.json();
        setKpis(prev => [...prev, savedKPI]);
        setNewKPI({ title: '', description: '', targetValue: '', measurementMethod: '', frequency: 'Monthly', targetDeadline: '', weight: '', linkedGoalId: '' });
        setShowAddKPI(false);
        showToast('KPI saved successfully!', 'success');
      } else {
        showToast('Error saving KPI', 'error');
      }
    } catch (error) {
      console.error('Error saving KPI:', error);
      showToast('Error saving KPI', 'error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddIPI = async () => {
    if (!newIPI.indicatorName || !newIPI.indicatorName.trim()) {
      showToast('Please enter an indicator name', 'error');
      return;
    }
    
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    
    let taskTitle = '';
    let workPlanId = newIPI.workPlanId;
    let workPlanTaskId = newIPI.workPlanTaskId;
    
    if (newIPI.workPlanTaskId) {
      const allTasks = workPlans.flatMap(wp => Array.isArray(wp.tasks) ? wp.tasks : []);
      const task = allTasks.find(t => t.id === newIPI.workPlanTaskId);
      taskTitle = task?.title || '';
      const parentPlan = workPlans.find(wp => Array.isArray(wp.tasks) && wp.tasks.some(t => t.id === newIPI.workPlanTaskId));
      workPlanId = parentPlan?.id || '';
    } else if (newIPI.workPlanId) {
      const plan = workPlans.find(wp => wp.id === newIPI.workPlanId);
      taskTitle = plan?.objective || '';
      workPlanTaskId = '';
    }
    
    setIsLoading(true);
    try {
      const response = await fetch('/api/performance/ipis', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employeeId: employeeIdentifier,
          workPlanId: workPlanId,
          workPlanTaskId: workPlanTaskId,
          indicatorName: newIPI.indicatorName,
          target: newIPI.target || '',
          measurementCriteria: newIPI.measurementCriteria || '',
          expectedPerformance: newIPI.expectedPerformance || '',
          ratingScale: newIPI.ratingScale || '',
          taskTitle: taskTitle
        })
      });
      
      if (response.ok) {
        const savedIPI = await response.json();
        setIpis(prev => [...prev, savedIPI]);
        setNewIPI({ workPlanTaskId: '', workPlanId: '', indicatorName: '', target: '', measurementCriteria: '', expectedPerformance: '', ratingScale: '' });
        setShowAddIPI(false);
        showToast('IPI saved successfully!', 'success');
      } else {
        showToast('Error saving IPI', 'error');
      }
    } catch (error) {
      console.error('Error saving IPI:', error);
      showToast('Error saving IPI', 'error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddQuarterly = async () => {
    if (!newQuarterly.title || !newQuarterly.kpiMeasurement) {
      showToast('Please fill in title and KPI measurement', 'error');
      return;
    }
    
    const employeeIdentifier = user?.employeeId || user?.id;
    if (!employeeIdentifier) return;
    
    setIsLoading(true);
    try {
      const response = await fetch('/api/performance/quarterly', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employeeId: employeeIdentifier,
          title: newQuarterly.title,
          quarter: newQuarterly.quarter,
          year: Number(newQuarterly.year),
          target: newQuarterly.kpiMeasurement,
          kpiMeasurement: newQuarterly.kpiMeasurement,
          expectedOutcome: newQuarterly.expectedOutcome,
          completionTimeline: newQuarterly.completionTimeline,
          weight: Number(newQuarterly.weight),
          linkedWorkPlanId: newQuarterly.linkedWorkPlanId
        })
      });
      
      if (response.ok) {
        const savedTarget = await response.json();
        setQuarterlyTargets(prev => [...prev, savedTarget]);
        setNewQuarterly({ quarter: 'Q1', year: '2026', title: '', kpiMeasurement: '', expectedOutcome: '', completionTimeline: '', weight: '10', linkedWorkPlanId: '' });
        setShowAddQuarterly(false);
        showToast('Quarterly target saved successfully!', 'success');
      } else {
        showToast('Error saving quarterly target', 'error');
      }
    } catch (error) {
      console.error('Error saving quarterly target:', error);
      showToast('Error saving quarterly target', 'error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSave = (updated: Appraisal) => {
    setAppraisals(prev => prev.map(a => a.id === updated.id ? updated : a));
    setAssessingAppraisal(null);
    showToast('Self-assessment saved successfully!', 'success');
  };

  const TABS: { id: Tab; label: string; icon: string }[] = [
    { id: 'workplan', label: 'Work Plan', icon: 'ri-file-list-3-line' },
    { id: 'kpis', label: 'My KPIs', icon: 'ri-bar-chart-line' },
    { id: 'quarterly', label: 'Quarterly Targets', icon: 'ri-calendar-check-line' },
    { id: 'ipis', label: 'My IPIs', icon: 'ri-line-chart-line' },
    { id: 'appraisals', label: 'Appraisals', icon: 'ri-star-line' },
    { id: 'pip', label: 'PIP', icon: 'ri-alarm-warning-line' },
  ];

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

  return (
    <InternLayout title="My Performance">
      {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 animate-fade-in">
          {toast}
        </div>
      )}

      {isLoading && (
        <div className="fixed inset-0 bg-black/50 z-[200] flex items-center justify-center">
          <div className="bg-white rounded-xl p-6 flex items-center gap-3">
            <div className="w-6 h-6 border-2 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
            <span className="text-sm text-gray-700">Loading...</span>
          </div>
        </div>
      )}

      <div className="mb-5">
        <h2 className="text-lg font-bold text-gray-800">Performance Management</h2>
        <p className="text-sm text-gray-500 mt-0.5">Work plan, KPIs, targets, and appraisals</p>
      </div>

      {unreadComments.length > 0 && (
        <div className="mb-4 bg-purple-50 border border-purple-300 rounded-xl px-4 py-3">
          <div className="flex items-center gap-2 mb-2">
            <i className="ri-chat-3-line text-purple-600"></i>
            <p className="text-sm font-semibold text-purple-800">{unreadComments.length} new comment{unreadComments.length > 1 ? 's' : ''} from your supervisor</p>
          </div>
          <div className="space-y-2">
            {unreadComments.map(c => (
              <div key={c.id} className="bg-white rounded-lg px-3 py-2.5 border border-purple-200 flex items-start justify-between gap-3">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-purple-100 text-purple-700">{c.itemType.toUpperCase()}</span>
                    <span className="text-xs font-medium text-gray-700">{c.itemTitle}</span>
                    <span className="text-xs text-gray-400">{c.createdAt}</span>
                  </div>
                  <p className="text-xs text-gray-700">{c.comment}</p>
                  <p className="text-xs text-purple-500 mt-1">From: <strong>{c.commentBy}</strong></p>
                </div>
                <button onClick={() => markRead(c.id)} className="text-xs text-purple-600 cursor-pointer whitespace-nowrap flex items-center gap-1">
                  <i className="ri-check-line"></i> Mark read
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="mb-5 overflow-x-auto">
        <div className="flex gap-1 bg-white rounded-xl shadow-sm border border-gray-100 p-1 min-w-max">
          {TABS.map((tab) => (
            <button key={tab.id} onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${activeTab === tab.id ? 'text-white shadow-sm' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
              style={activeTab === tab.id ? { background: BRAND } : {}}>
              <i className={`${tab.icon} text-xs`}></i>
              {tab.label}
              {tab.id === 'pip' && myPIPs.filter(p => p.status === 'Active').length > 0 && (
                <span className="ml-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center font-bold">!</span>
              )}
            </button>
          ))}
        </div>
      </div>

      {/* Work Plan Tab */}
      {activeTab === 'workplan' && (
        <div className="space-y-4">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="font-bold text-gray-800">My Work Plan {new Date().getFullYear()}</h3>
                <p className="text-xs text-gray-500 mt-0.5">Based on departmental targets set by your HOD</p>
              </div>
              <button onClick={() => setShowAddWorkPlan(true)} className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: BRAND }}>
                <i className="ri-add-line"></i> Add Work Plan
              </button>
            </div>

            {workPlans.length === 0 ? (
              <div className="text-center py-8 text-gray-400">
                <i className="ri-file-list-line text-4xl mb-2 block"></i>
                <p>No work plans yet. Click "Add Work Plan" to create one.</p>
              </div>
            ) : (
              <div className="space-y-4">
                {workPlans.map(plan => (
                  <WorkPlanCard 
                    key={plan.id} 
                    plan={plan} 
                    deptTargetTitle={DEPT_TARGETS.find(t => t.id === plan.linkedTargetId)?.title} 
                    onAddTask={(id: string) => setShowAddTask(id)} 
                    onUpdateProgress={handleUpdateProgress}
                    onUpdate={(updatedPlan) => {
                      setWorkPlans(prev => prev.map(wp => wp.id === updatedPlan.id ? updatedPlan : wp));
                      handleUpdateWorkPlan(updatedPlan.id, updatedPlan);
                    }}
                  />
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* KPIs Tab */}
      {activeTab === 'kpis' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="font-bold text-gray-800">My Key Performance Indicators</h3>
            <button onClick={() => setShowAddKPI(true)} className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white" style={{ background: BRAND }}>
              <i className="ri-add-line"></i> Add KPI
            </button>
          </div>
          {kpis.length === 0 ? (
            <div className="text-center py-8 text-gray-400">
              <i className="ri-bar-chart-line text-4xl mb-2 block"></i>
              <p>No KPIs yet. Click "Add KPI" to create one.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {kpis.map((k, i) => (
                <KPIGauge 
                  key={k.id} 
                  kpi={k} 
                  index={i} 
                  onUpdate={async (updated) => {
                    const saved = await updateKpi(updated.id, updated);
                    if (saved) {
                      setKpis(prev => prev.map(kp => (kp.id === saved.id ? saved : kp)));
                      showToast('KPI updated successfully!', 'success');
                    } else {
                      showToast('Error updating KPI', 'error');
                    }
                  }}
                />
              ))}
            </div>
          )}
        </div>
      )}

      {/* Quarterly Targets Tab */}
      {activeTab === 'quarterly' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="font-bold text-gray-800">Quarterly Targets</h3>
            <button onClick={() => setShowAddQuarterly(true)} className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white" style={{ background: BRAND }}>
              <i className="ri-add-line"></i> Add Target
            </button>
          </div>
          {quarterlyTargets.length === 0 ? (
            <div className="text-center py-8 text-gray-400">
              <i className="ri-calendar-line text-4xl mb-2 block"></i>
              <p>No quarterly targets yet. Click "Add Target" to create one.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {quarterlyTargets.map((q, i) => (
                <QuarterlyTargetCard 
                  key={q.id} 
                  target={q} 
                  index={i} 
                  workPlanTitle={workPlans.find(w => w.id === q.linkedWorkPlanId)?.objective} 
                  onUpdate={async (updated) => {
                    const saved = await updateQuarterlyTarget(updated.id, updated);
                    if (saved) {
                      setQuarterlyTargets(prev => prev.map(qt => (qt.id === saved.id ? saved : qt)));
                      showToast('Quarterly target updated successfully!', 'success');
                    } else {
                      showToast('Error updating quarterly target', 'error');
                    }
                  }}
                />
              ))}
            </div>
          )}
        </div>
      )}

      {/* IPIs Tab */}
      {activeTab === 'ipis' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-2">
            <div>
              <h3 className="font-bold text-gray-800">My Individual Performance Indicators (IPIs)</h3>
              <p className="text-xs text-gray-500 mt-0.5">Linked to work plan activities for effectiveness measurement</p>
            </div>
            <button onClick={() => setShowAddIPI(true)} className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white" style={{ background: BRAND }}>
              <i className="ri-add-line"></i> Add IPI
            </button>
          </div>
          {ipis.length === 0 ? (
            <div className="text-center py-8 text-gray-400">
              <i className="ri-line-chart-line text-4xl mb-2 block"></i>
              <p>No IPIs yet. Click "Add IPI" to create one.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {ipis.map((ipi, i) => (
                <IPICard 
                  key={ipi.id} 
                  ipi={ipi} 
                  index={i} 
                  onUpdate={async (updated) => {
                    const saved = await updateIpi(updated.id, updated);
                    if (saved) {
                      setIpis(prev => prev.map(ip => (ip.id === saved.id ? saved : ip)));
                      showToast('IPI updated successfully!', 'success');
                    } else {
                      showToast('Error updating IPI', 'error');
                    }
                  }}
                />
              ))}
            </div>
          )}
        </div>
      )}

      {/* Appraisals Tab */}
      {activeTab === 'appraisals' && (
        <div className="space-y-4">
          {myAppraisals.length === 0 ? (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center">
              <i className="ri-bar-chart-line text-4xl text-gray-300 mb-2 block"></i>
              <p className="text-gray-500 font-medium">No appraisals yet</p>
              <p className="text-gray-400 text-sm mt-1">Your HR team will create an appraisal for you when the cycle begins.</p>
            </div>
          ) : (
            myAppraisals.map(a => {
              const canAssess = a.status === 'Pending Self-Assessment';
              const allRatings = [...a.companyGoalRatings, ...a.deptGoalRatings];
              const avgSelf = allRatings.length > 0 ? (allRatings.reduce((s, r) => s + r.selfRating, 0) / allRatings.length).toFixed(1) : null;
              return (
                <div key={a.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h3 className="font-bold text-gray-800">{a.period}</h3>
                      <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${statusColors[a.status]}`}>{a.status}</span>
                      <p className="text-sm text-gray-500 mt-1">HOD: {a.hodName}</p>
                    </div>
                    <div className="text-right">
                      {a.overallRating > 0 ? (
                        <p className="text-3xl font-bold" style={{ color: BRAND }}>{a.overallRating.toFixed(1)}</p>
                      ) : avgSelf ? (
                        <p className="text-2xl font-bold text-blue-600">{avgSelf}</p>
                      ) : (
                        <p className="text-2xl font-bold text-gray-300">—</p>
                      )}
                    </div>
                  </div>
                  {canAssess && (
                    <button onClick={() => setAssessingAppraisal(a)} className="px-4 py-2 text-white rounded-xl text-sm font-semibold" style={{ background: BRAND }}>
                      Start Self-Assessment
                    </button>
                  )}
                </div>
              );
            })
          )}
        </div>
      )}

      {/* PIP Tab */}
      {activeTab === 'pip' && (
        <div className="space-y-4">
          {myPIPs.length === 0 ? (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center">
              <i className="ri-checkbox-circle-line text-4xl text-green-500 mb-2 block"></i>
              <p className="text-gray-500 font-medium">No Performance Improvement Plans</p>
              <p className="text-gray-400 text-sm mt-1">You currently have no active PIPs. Keep up the great work!</p>
            </div>
          ) : (
            myPIPs.map(pip => (
              <div key={pip.id} className="bg-white rounded-2xl shadow-sm border border-red-200 p-5">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <h3 className="font-bold text-gray-800">PIP — {pip.id}</h3>
                    <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${pip.status === 'Active' ? 'bg-red-100 text-red-700' : pip.status === 'Successful' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}`}>{pip.status}</span>
                    <p className="text-sm text-gray-500 mt-1">Started: {pip.startDate}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-2xl font-bold text-red-600">{pip.checkIns?.[pip.checkIns.length - 1]?.progress || 0}%</p>
                  </div>
                </div>
                <div className="w-full bg-gray-100 rounded-full h-2 mb-3">
                  <div className="h-2 rounded-full bg-red-500" style={{ width: `${pip.checkIns?.[pip.checkIns.length - 1]?.progress || 0}%` }}></div>
                </div>
                <div>
                  <p className="text-xs font-semibold text-gray-600 mb-1">Improvement Areas:</p>
                  {pip.improvementAreas?.map((area, i) => (
                    <div key={i} className="flex items-center gap-2 text-xs text-gray-600">
                      <i className="ri-arrow-right-s-line text-red-400"></i>
                      <span>{area}</span>
                    </div>
                  ))}
                </div>
              </div>
            ))
          )}
        </div>
      )}

      {/* Add Work Plan Modal */}
      {showAddWorkPlan && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-md w-full">
            <div className="px-6 py-4 border-b border-gray-100" style={{ background: BRAND }}>
              <h2 className="text-xl font-bold text-white">New Work Plan</h2>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Linked Departmental Target</label>
                <select value={newWorkPlan.linkedTargetId} onChange={e => setNewWorkPlan(p => ({ ...p, linkedTargetId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none">
                  <option value="">Select target...</option>
                  {DEPT_TARGETS.map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Objective *</label>
                <input value={newWorkPlan.objective} onChange={e => setNewWorkPlan(p => ({ ...p, objective: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Target / Success Metric</label>
                <input value={newWorkPlan.target} onChange={e => setNewWorkPlan(p => ({ ...p, target: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Due Date</label>
                <input type="date" value={newWorkPlan.dueDate} onChange={e => setNewWorkPlan(p => ({ ...p, dueDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
            </div>
            <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
              <button onClick={() => setShowAddWorkPlan(false)} className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">Cancel</button>
              <button onClick={handleAddWorkPlan} className="px-4 py-2 text-white rounded-lg hover:opacity-90 cursor-pointer" style={{ background: BRAND }}>Save</button>
            </div>
          </div>
        </div>
      )}

      {/* Add Task Modal */}
      {showAddTask && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-lg w-full">
            <div className="px-6 py-4 border-b border-gray-100" style={{ background: BRAND }}>
              <h2 className="text-xl font-bold text-white">Add Task</h2>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Task Title *</label>
                <input value={newTask.title} onChange={e => setNewTask(p => ({ ...p, title: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Objective *</label>
                <input value={newTask.objective} onChange={e => setNewTask(p => ({ ...p, objective: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Expected Output</label>
                <input value={newTask.expectedOutput} onChange={e => setNewTask(p => ({ ...p, expectedOutput: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                  <input type="date" value={newTask.startDate} onChange={e => setNewTask(p => ({ ...p, startDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                  <input type="date" value={newTask.endDate} onChange={e => setNewTask(p => ({ ...p, endDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Remarks</label>
                <textarea value={newTask.remarks} onChange={e => setNewTask(p => ({ ...p, remarks: e.target.value }))} rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
            </div>
            <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
              <button onClick={() => setShowAddTask(null)} className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">Cancel</button>
              <button onClick={() => handleAddTask(showAddTask!)} className="px-4 py-2 text-white rounded-lg hover:opacity-90 cursor-pointer" style={{ background: BRAND }}>Save</button>
            </div>
          </div>
        </div>
      )}

      {/* Add KPI Modal */}
      {showAddKPI && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-lg w-full">
            <div className="px-6 py-4 border-b border-gray-100" style={{ background: BRAND }}>
              <h2 className="text-xl font-bold text-white">New KPI</h2>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Linked Strategic Goal</label>
                <select value={newKPI.linkedGoalId} onChange={e => setNewKPI(p => ({ ...p, linkedGoalId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none">
                  <option value="">Select goal...</option>
                  {COMPANY_GOALS.map(g => <option key={g.id} value={g.id}>{g.title}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">KPI Title *</label>
                <input value={newKPI.title} onChange={e => setNewKPI(p => ({ ...p, title: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                <textarea value={newKPI.description} onChange={e => setNewKPI(p => ({ ...p, description: e.target.value }))} rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Target Value *</label>
                  <input value={newKPI.targetValue} onChange={e => setNewKPI(p => ({ ...p, targetValue: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Measurement Method</label>
                  <input value={newKPI.measurementMethod} onChange={e => setNewKPI(p => ({ ...p, measurementMethod: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Frequency</label>
                  <select value={newKPI.frequency} onChange={e => setNewKPI(p => ({ ...p, frequency: e.target.value as any }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none">
                    <option value="Monthly">Monthly</option>
                    <option value="Quarterly">Quarterly</option>
                    <option value="Annual">Annual</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Target Deadline</label>
                  <input type="date" value={newKPI.targetDeadline} onChange={e => setNewKPI(p => ({ ...p, targetDeadline: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
                </div>
              </div>
            </div>
            <div className="p-6 border-t border-gray-100 flex justify-end gap-3">
              <button onClick={() => setShowAddKPI(false)} className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">Cancel</button>
              <button onClick={handleAddKPI} className="px-4 py-2 text-white rounded-lg hover:opacity-90 cursor-pointer" style={{ background: BRAND }}>Save</button>
            </div>
          </div>
        </div>
      )}

      {assessingAppraisal && (
        <SelfAssessmentForm appraisal={assessingAppraisal} onSave={handleSave} onClose={() => setAssessingAppraisal(null)} />
      )}
      
      {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-2xl max-h-[90vh] flex flex-col shadow-2xl">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: BRAND }}>
              <h2 className="text-white font-bold">Appraisal Details</h2>
              <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="p-6 overflow-y-auto flex-1">
              <p className="text-gray-500">Appraisal details will be shown here.</p>
            </div>
            <div className="px-6 pb-6">
              <button onClick={() => setViewAppraisal(null)} className="w-full py-3 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 hover:bg-gray-50 cursor-pointer">Close</button>
            </div>
          </div>
        </div>
      )}
    </InternLayout>
  );
}