import { apiRequest } from './api';

export type ProjectStatus = 'Planned' | 'Active' | 'On hold' | 'Completed' | 'Cancelled';

export type BudgetType = 'Days' | 'Hours' | 'Fixed amount';

export interface ProjectMemberRecord {
  id: string;
  projectId: string;
  userId: string;
  roleLabel: string;
  joinedAt: string;
  loggedHours?: number;
  user?: {
    id: string;
    name: string;
    email: string;
  };
}

export interface MilestoneRecord {
  id: string;
  projectId: string;
  title: string;
  dueDate: string;
  isDone: boolean;
  orderIndex: number;
  createdAt: string;
  updatedAt: string;
}

export interface ProjectRecord {
  id: string;
  projectNumber: string;
  name: string;
  description: string | null;
  status: ProjectStatus;
  startDate: string;
  targetEndDate: string;
  budgetType: BudgetType;
  budgetHours: number;
  budgetAmount: number;
  accountId: string;
  dealId: string | null;
  ownerId: string;
  createdAt: string;
  updatedAt: string;
  completedAt: string | null;
  account?: {
    id: string;
    name: string;
    city: string | null;
  };
  deal?: {
    id: string;
    title: string;
    dealNumber: string;
    amount: number | string;
  } | null;
  owner?: {
    id: string;
    name: string;
    email: string;
  };
  members?: ProjectMemberRecord[];
  milestones?: MilestoneRecord[];
  loggedHours: number;
  billableHours: number;
  doneMilestones: number;
  totalMilestones: number;
  isAtRisk: boolean;
  _count?: {
    tasks: number;
    milestones: number;
    timeEntries: number;
  };
}

export interface ProjectDetailRecord extends ProjectRecord {
  tasks: Array<{
    id: string;
    title: string;
    dueDate: string;
    completed: boolean;
    priority: string;
    owner?: { id: string; name: string };
    milestone?: { id: string; title: string };
  }>;
  timeEntries: Array<{
    id: string;
    date: string;
    hours: number;
    isBillable: boolean;
    note: string | null;
    user?: { id: string; name: string };
    milestone?: { id: string; title: string };
  }>;
  activities: Array<{
    id: string;
    type: string;
    subject: string;
    description: string | null;
    performedAt: string;
    owner?: { id: string; name: string };
  }>;
  leftHours: number;
  isOverBudget: boolean;
}

export interface ProjectsStats {
  activeProjects: number;
  atRiskProjects: number;
  completedProjects: number;
  totalProjects: number;
  teamHoursThisWeek: number;
  billablePercentThisWeek: number;
}

export interface ProjectsListResponse {
  data: ProjectRecord[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    stats: ProjectsStats;
  };
}

export interface WonDealOption {
  id: string;
  dealNumber: string;
  title: string;
  amount: number | string;
  estimatedHours: number | null;
  accountId: string | null;
  account?: {
    id: string;
    name: string;
  } | null;
}

export interface CreateProjectInput {
  name: string;
  description?: string;
  dealId?: string;
  accountId?: string;
  ownerId?: string;
  status?: ProjectStatus;
  startDate?: string;
  targetEndDate?: string;
  budgetType?: BudgetType;
  budgetHours?: number;
  budgetAmount?: number;
  teamMemberIds?: string[];
}

export interface UpdateProjectInput {
  name?: string;
  description?: string;
  status?: ProjectStatus;
  startDate?: string;
  targetEndDate?: string;
  budgetType?: BudgetType;
  budgetHours?: number;
  budgetAmount?: number;
  ownerId?: string;
}

export interface CreateMilestoneInput {
  title: string;
  dueDate?: string;
  orderIndex?: number;
}

export interface UpdateMilestoneInput {
  title?: string;
  dueDate?: string;
  isDone?: boolean;
  orderIndex?: number;
}

export const projectsApi = {
  async list(
    params: {
      view?: 'active' | 'mine' | 'at_risk' | 'completed' | 'all';
      q?: string;
      page?: number;
      limit?: number;
      accountId?: string;
      ownerId?: string;
      status?: string;
      targetFrom?: string;
      targetTo?: string;
    } = {},
  ): Promise<ProjectsListResponse> {
    const qs = new URLSearchParams();
    if (params.view) qs.set('view', params.view);
    if (params.q) qs.set('q', params.q);
    if (params.page) qs.set('page', String(params.page));
    if (params.limit) qs.set('limit', String(params.limit));
    if (params.accountId) qs.set('accountId', params.accountId);
    if (params.ownerId) qs.set('ownerId', params.ownerId);
    if (params.status) qs.set('status', params.status);
    if (params.targetFrom) qs.set('targetFrom', params.targetFrom);
    if (params.targetTo) qs.set('targetTo', params.targetTo);

    const query = qs.toString();
    return apiRequest<ProjectsListResponse>(`/projects${query ? `?${query}` : ''}`, { method: 'GET' });
  },

  async get(id: string): Promise<ProjectDetailRecord> {
    return apiRequest<ProjectDetailRecord>(`/projects/${id}`, {
      method: 'GET',
    });
  },

  async create(input: CreateProjectInput): Promise<ProjectRecord> {
    return apiRequest<ProjectRecord>('/projects', {
      method: 'POST',
      body: JSON.stringify(input),
    });
  },

  async update(id: string, input: UpdateProjectInput): Promise<ProjectRecord> {
    return apiRequest<ProjectRecord>(`/projects/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(input),
    });
  },

  async delete(id: string): Promise<{ success: boolean }> {
    return apiRequest<{ success: boolean }>(`/projects/${id}`, {
      method: 'DELETE',
    });
  },

  async getWonDeals(): Promise<WonDealOption[]> {
    return apiRequest<WonDealOption[]>('/projects/won-deals', {
      method: 'GET',
    });
  },

  async addMember(projectId: string, input: { userId: string; roleLabel?: string }): Promise<ProjectMemberRecord> {
    return apiRequest<ProjectMemberRecord>(`/projects/${projectId}/members`, {
      method: 'POST',
      body: JSON.stringify(input),
    });
  },

  async removeMember(projectId: string, memberId: string): Promise<{ success: boolean }> {
    return apiRequest<{ success: boolean }>(`/projects/${projectId}/members/${memberId}`, { method: 'DELETE' });
  },

  async addMilestone(projectId: string, input: CreateMilestoneInput): Promise<MilestoneRecord> {
    return apiRequest<MilestoneRecord>(`/projects/${projectId}/milestones`, {
      method: 'POST',
      body: JSON.stringify(input),
    });
  },

  async updateMilestone(projectId: string, milestoneId: string, input: UpdateMilestoneInput): Promise<MilestoneRecord> {
    return apiRequest<MilestoneRecord>(`/projects/${projectId}/milestones/${milestoneId}`, {
      method: 'PATCH',
      body: JSON.stringify(input),
    });
  },

  async deleteMilestone(projectId: string, milestoneId: string): Promise<{ success: boolean }> {
    return apiRequest<{ success: boolean }>(`/projects/${projectId}/milestones/${milestoneId}`, { method: 'DELETE' });
  },
};
