import { BaseApiService } from '@/services/api/base';
import {
  BaseProjectFlockKandang,
  ProjectFlockKandang,
  ClosingProjectFlockKandangPayload,
  CheckClosingResponse,
} from '@/types/api/production/project-flock-kandang';
import { Approvals, BaseApiResponse } from '@/types/api/api-general';
import { httpClient } from '@/services/http/client';
import axios from 'axios';

export class ProjectFlockKandangService extends BaseApiService<
  BaseProjectFlockKandang,
  ProjectFlockKandang,
  unknown
> {
  constructor(basePath: string = '') {
    super(basePath);
  }

  /**
   * Close or Unclose Project Flock Kandang
   */
  async closing(
    id: number,
    payload: ClosingProjectFlockKandangPayload
  ): Promise<BaseApiResponse<{ message: string }> | undefined> {
    try {
      const path = `${this.basePath}/${id}/closing`;

      const headers = {
        'Content-Type': 'application/json',
        ...(this.header ?? {}),
      };

      return await httpClient<BaseApiResponse<{ message: string }>>(path, {
        method: 'POST',
        body: payload,
        headers,
      });
    } catch (error: unknown) {
      if (axios.isAxiosError<BaseApiResponse<{ message: string }>>(error)) {
        return error.response?.data;
      }
      return undefined;
    }
  }

  /**
   * Check Closing Requirements for Project Flock Kandang
   * TODO: Replace with actual API call when backend is ready
   */
  async checkClosing(
    id: number
  ): Promise<BaseApiResponse<CheckClosingResponse> | undefined> {
    // Dummy data - replace with actual API call when backend is ready
    // return new Promise((resolve) => {
    //   setTimeout(() => {
    //     resolve({
    //       code: 200,
    //       status: 'success',
    //       message: 'Cek persyaratan closing kandang',
    //       data: {
    //         unfinished_expenses: id % 2 === 1 ? 2 : 0,
    //         stock_remaining: [
    //           {
    //             id: 1,
    //             product_id: 1,
    //             warehouse_id: 1,
    //             quantity: id % 2 === 1 ? 100 : 0,
    //             product: {
    //               id: 1,
    //               name: 'Pakan Starter',
    //               brand: 'Brand A',
    //               sku: 'PKN-STR-001',
    //               product_price: 15000,
    //               selling_price: 17000,
    //               tax: 0,
    //               expiry_period: 365,
    //               flags: ['active'],
    //               uom: {
    //                 id: 1,
    //                 name: 'Kg',
    //                 created_user: {
    //                   id: 1,
    //                   id_user: 1,
    //                   email: 'admin@example.com',
    //                   name: 'Admin User',
    //                 },
    //                 created_at: '2024-01-01',
    //                 updated_at: '2024-01-01',
    //               },
    //               product_category: {
    //                 id: 1,
    //                 name: 'Pakan',
    //                 code: 'PKN',
    //                 created_user: {
    //                   id: 1,
    //                   id_user: 1,
    //                   email: 'admin@example.com',
    //                   name: 'Admin User',
    //                 },
    //                 created_at: '2024-01-01',
    //                 updated_at: '2024-01-01',
    //               },
    //               suppliers: [],
    //               created_user: {
    //                 id: 1,
    //                 id_user: 1,
    //                 email: 'admin@example.com',
    //                 name: 'Admin User',
    //               },
    //               created_at: '2024-01-01',
    //               updated_at: '2024-01-01',
    //             },
    //             warehouse: {
    //               id: 1,
    //               name: 'Gudang Utama',
    //               type: 'AREA',
    //               area: {
    //                 id: 1,
    //                 name: 'Area 1',
    //               },
    //               created_user: {
    //                 id: 1,
    //                 id_user: 1,
    //                 email: 'admin@example.com',
    //                 name: 'Admin User',
    //               },
    //               created_at: '2024-01-01',
    //               updated_at: '2024-01-01',
    //             },
    //             created_user: {
    //               id: 1,
    //               id_user: 1,
    //               email: 'admin@example.com',
    //               name: 'Admin User',
    //             },
    //             created_at: '2025-01-01',
    //             updated_at: '2025-01-01',
    //           },
    //         ],
    //         expenses: [
    //           {
    //             id: 1,
    //             po_number: 'PO-BOP-LTI-00001',
    //             category: 'NON-BOP',
    //             total: 110000,
    //             status: id % 2 === 1 ? 'PENGAJUAN' : 'SELESAI',
    //             step_name: id % 2 === 1 ? 'Approval Finance' : 'Selesai',
    //             step: id % 2 === 1 ? 1 : 5,
    //             reference_number: 'BOP-LTI-00001',
    //           },
    //           {
    //             id: 3,
    //             po_number: 'PO-BOP-LTI-00003',
    //             category: 'BOP',
    //             total: 110000,
    //             status: id % 2 === 1 ? 'PENGAJUAN' : 'SELESAI',
    //             step_name: id % 2 === 1 ? 'Approval Finance' : 'Selesai',
    //             step: id % 2 === 1 ? 1 : 5,
    //             reference_number: 'BOP-LTI-00003',
    //           },
    //         ],
    //       },
    //     });
    //   }, 500); // Simulate network delay
    // });

    // Original API call - uncomment when backend is ready
    try {
      const path = `${this.basePath}/${id}/closing/check`;

      return await httpClient<BaseApiResponse<CheckClosingResponse>>(path, {
        method: 'GET',
      });
    } catch (error: unknown) {
      if (axios.isAxiosError<BaseApiResponse<CheckClosingResponse>>(error)) {
        return error.response?.data;
      }
      return undefined;
    }
  }

  async getApprovalLineHistory(
    id: number,
    page: number = 1,
    limit: number = 100
  ) {
    try {
      const approvalHistoryRes = await httpClient<Approvals>('/approvals', {
        query: {
          module_name: 'PROJECT_FLOCK_KANDANGS',
          module_id: id,
          group_step_number: 'false',
          page,
          limit,
          order_by_date: 'ASC',
        },
      });

      return approvalHistoryRes;
    } catch (error) {
      if (axios.isAxiosError<Approvals>(error)) {
        return error.response?.data;
      }

      return undefined;
    }
  }
}

export const ProjectFlockKandangApi = new ProjectFlockKandangService(
  '/production/project-flock-kandangs'
);
