﻿import { WorkPlan, WorkPlanTask } from '@/app/employee/performance/WorkPlanCard';
import { Appraisal, PIP } from '@/app/hr/performance/performanceData';

export interface KPIType {
  id: string;
  title: string;
  description: string;
  targetValue: string;
  currentValue: string;
  measurementMethod: string;
  frequency: 'Monthly' | 'Quarterly' | 'Annual';
  progress: number;
  performanceScore: number;
  targetDeadline: string;
  linkedGoalId: string;
  employeeId: string;
}

export interface QuarterlyTargetType {
  id: string;
  title: string;
  quarter: string;
  year: number;
  target: string;
  kpiMeasurement: string;
  expectedOutcome: string;
  completionTimeline: string;
  weight: number;
  progress: number;
  status: 'Not Started' | 'Completed' | 'In Progress';
  linkedWorkPlanId: string;
  employeeId: string;
}

export interface IPIType {
  id: string;
  workPlanId: string;
  workPlanTaskId: string;
  indicatorName: string;
  target: string;
  measurementCriteria: string;
  expectedPerformance: string;
  ratingScale: string;
  taskTitle: string;
  employeeId: string;
  progress: number;
  current: string;
}

const API_BASE = '/api/performance';

async function apiRequest<T>(url: string, options?: RequestInit): Promise<T | null> {
  try {
    const response = await fetch(url, {
      headers: { 'Content-Type': 'application/json' },
      ...options,
    });
    if (!response.ok) {
      console.error('API Error:', await response.text());
      return null;
    }
    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    return null;
  }
}

// ========== WORK PLANS ==========
export async function fetchWorkPlans(employeeId: string): Promise<WorkPlan[]> {
  return (await apiRequest<WorkPlan[]>(`${API_BASE}/workplans?employeeId=${employeeId}`)) || [];
}

export async function createWorkPlan(data: Partial<WorkPlan>): Promise<WorkPlan | null> {
  return apiRequest<WorkPlan>(`${API_BASE}/workplans`, {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

export async function updateWorkPlan(id: string, updates: Partial<WorkPlan>): Promise<WorkPlan | null> {
  return apiRequest<WorkPlan>(`${API_BASE}/workplans/id/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates),
  });
}

// ========== KPIs ==========
export async function fetchKpis(employeeId: string): Promise<KPIType[]> {
  const kpis = await apiRequest<KPIType[]>(`${API_BASE}/kpis?employeeId=${employeeId}`);
  return (kpis || []).map(k => ({ 
    id: k.id || '',
    title: k.title || '',
    description: k.description || '',
    targetValue: k.targetValue || '',
    currentValue: k.currentValue || '',
    measurementMethod: k.measurementMethod || '',
    frequency: k.frequency || 'Monthly',
    progress: k.progress || 0,
    performanceScore: k.performanceScore || 0,
    targetDeadline: k.targetDeadline || '',
    linkedGoalId: k.linkedGoalId || '',
    employeeId: k.employeeId || employeeId
  }));
}

export async function createKpi(data: Partial<KPIType>): Promise<KPIType | null> {
  const kpiData: KPIType = {
    id: data.id || '',
    title: data.title || '',
    description: data.description || '',
    targetValue: data.targetValue || '',
    currentValue: data.currentValue || '',
    measurementMethod: data.measurementMethod || '',
    frequency: data.frequency || 'Monthly',
    progress: data.progress || 0,
    performanceScore: data.performanceScore || 0,
    targetDeadline: data.targetDeadline || '',
    linkedGoalId: data.linkedGoalId || '',
    employeeId: data.employeeId || ''
  };
  return apiRequest<KPIType>(`${API_BASE}/kpis`, {
    method: 'POST',
    body: JSON.stringify(kpiData),
  });
}

export async function updateKpi(id: string, updates: Partial<KPIType>): Promise<KPIType | null> {
  return apiRequest<KPIType>(`${API_BASE}/kpis/id/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates),
  });
}

// ========== QUARTERLY TARGETS ==========
export async function fetchQuarterlyTargets(employeeId: string): Promise<QuarterlyTargetType[]> {
  const targets = await apiRequest<QuarterlyTargetType[]>(`${API_BASE}/quarterly?employeeId=${employeeId}`);
  return (targets || []).map(t => {
    let status: 'Not Started' | 'Completed' | 'In Progress' = 'Not Started';
    const rawStatus = (t.status || '').toLowerCase();
    if (rawStatus === 'completed') status = 'Completed';
    else if (rawStatus === 'in progress' || rawStatus === 'in_progress') status = 'In Progress';
    else status = 'Not Started';
    
    return { 
      id: t.id || '',
      title: t.title || '',
      quarter: t.quarter || 'Q1',
      year: t.year || new Date().getFullYear(),
      target: t.target || '',
      kpiMeasurement: t.kpiMeasurement || '',
      expectedOutcome: t.expectedOutcome || '',
      completionTimeline: t.completionTimeline || '',
      weight: t.weight || 0,
      progress: t.progress || 0,
      status: status,
      linkedWorkPlanId: t.linkedWorkPlanId || '',
      employeeId: t.employeeId || employeeId
    };
  });
}

export async function createQuarterlyTarget(data: Partial<QuarterlyTargetType>): Promise<QuarterlyTargetType | null> {
  const targetData: QuarterlyTargetType = {
    id: data.id || '',
    title: data.title || '',
    quarter: data.quarter || 'Q1',
    year: data.year || new Date().getFullYear(),
    target: data.target || '',
    kpiMeasurement: data.kpiMeasurement || '',
    expectedOutcome: data.expectedOutcome || '',
    completionTimeline: data.completionTimeline || '',
    weight: data.weight || 0,
    progress: data.progress || 0,
    status: data.status || 'Not Started',
    linkedWorkPlanId: data.linkedWorkPlanId || '',
    employeeId: data.employeeId || ''
  };
  return apiRequest<QuarterlyTargetType>(`${API_BASE}/quarterly`, {
    method: 'POST',
    body: JSON.stringify(targetData),
  });
}

export async function updateQuarterlyTarget(id: string, updates: Partial<QuarterlyTargetType>): Promise<QuarterlyTargetType | null> {
  return apiRequest<QuarterlyTargetType>(`${API_BASE}/quarterly/id/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates),
  });
}

// ========== IPIs ==========
export async function fetchIpis(employeeId: string): Promise<IPIType[]> {
  const ipis = await apiRequest<IPIType[]>(`${API_BASE}/ipis?employeeId=${employeeId}`);
  return (ipis || []).map(i => ({ 
    id: i.id || '',
    workPlanId: i.workPlanId || '',
    workPlanTaskId: i.workPlanTaskId || '',
    indicatorName: i.indicatorName || '',
    target: i.target || '',
    measurementCriteria: i.measurementCriteria || '',
    expectedPerformance: i.expectedPerformance || '',
    ratingScale: i.ratingScale || '',
    taskTitle: i.taskTitle || '',
    employeeId: i.employeeId || employeeId,
    progress: i.progress || 0,
    current: i.current || '0'
  }));
}

export async function createIpi(data: Partial<IPIType>): Promise<IPIType | null> {
  const ipiData: IPIType = {
    id: data.id || '',
    workPlanId: data.workPlanId || '',
    workPlanTaskId: data.workPlanTaskId || '',
    indicatorName: data.indicatorName || '',
    target: data.target || '',
    measurementCriteria: data.measurementCriteria || '',
    expectedPerformance: data.expectedPerformance || '',
    ratingScale: data.ratingScale || '',
    taskTitle: data.taskTitle || '',
    employeeId: data.employeeId || '',
    progress: data.progress || 0,
    current: data.current || '0'
  };
  return apiRequest<IPIType>(`${API_BASE}/ipis`, {
    method: 'POST',
    body: JSON.stringify(ipiData),
  });
}

export async function updateIpi(id: string, updates: Partial<IPIType>): Promise<IPIType | null> {
  return apiRequest<IPIType>(`${API_BASE}/ipis/id/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates),
  });
}

// ========== PIPS ==========
export async function fetchPIPs(employeeId: string): Promise<PIP[]> {
  const pips = await apiRequest<any[]>(`${API_BASE}/pips?employeeId=${employeeId}`);
  
  if (!pips || pips.length === 0) {
    return [];
  }
  
  // Return COMPLETE PIP objects with ALL required fields
  // This ensures that when the page does { ...pip, improvementAreas: ..., checkIns: ... }
  // all the fields are included
  return pips.map(p => ({
    id: p.id,
    employeeId: p.employeeId,
    employeeName: p.employeeName || '',
    dept: p.dept || '',
    triggerRating: p.triggerRating || 2.5,
    appraisalPeriod: p.appraisalPeriod || '',
    startDate: p.startDate,
    endDate: p.endDate,
    duration: p.duration || '90 days',
    improvementAreas: Array.isArray(p.improvementAreas) ? p.improvementAreas : [],
    actionPlan: p.actionPlan || '',
    successMetrics: p.successMetrics || '',
    status: p.status || 'Active',
    hod: p.hod || p.supervisor || 'HOD',
    checkIns: Array.isArray(p.checkIns) ? p.checkIns : [],
    aiGenerated: p.aiGenerated || false
  }));
}

export async function createPIP(data: Partial<PIP>): Promise<PIP | null> {
  return apiRequest<PIP>(`${API_BASE}/pips`, {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

// ========== APPRAISALS ==========
export async function fetchAppraisals(employeeId: string): Promise<Appraisal[]> {
  return (await apiRequest<Appraisal[]>(`${API_BASE}/appraisals?employeeId=${employeeId}`)) || [];
}

export async function updateAppraisal(id: string, updates: Partial<Appraisal>): Promise<Appraisal | null> {
  return apiRequest<Appraisal>(`${API_BASE}/appraisals/id/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates),
  });
}

// ========== COMPANY GOALS ==========
export async function fetchCompanyGoals(): Promise<any[]> {
  return (await apiRequest<any[]>(`${API_BASE}/company-goals`)) || [];
}

// ========== DEPARTMENT GOALS ==========
export async function fetchDepartmentGoals(dept: string): Promise<any[]> {
  return (await apiRequest<any[]>(`${API_BASE}/department-goals?dept=${dept}`)) || [];
}

// ========== COMBINED FETCH ==========
export async function fetchPerformanceData(employeeId: string): Promise<{
  workPlans: WorkPlan[];
  kpis: KPIType[];
  quarterlyTargets: QuarterlyTargetType[];
  ipis: IPIType[];
  pips: PIP[];
}> {
  const [workPlans, kpis, quarterlyTargets, ipis, pips] = await Promise.all([
    fetchWorkPlans(employeeId),
    fetchKpis(employeeId),
    fetchQuarterlyTargets(employeeId),
    fetchIpis(employeeId),
    fetchPIPs(employeeId),
  ]);
  return { workPlans, kpis, quarterlyTargets, ipis, pips };
}