"use client";

import { NEXT_PUBLIC_API_URL } from '@/config/api';
import { clientAuthFetch } from '@/app/utils/clientAuthFetch';

export interface ItemCodeWithName {
  code: string;
  name: string;
}

export interface ItemCodeWithCategory {
  code: string;
  category: string;
  name?: string;
}

/**
 * Fetch item codes for SemiFG Production Analysis Report
 * @param stockCategory - Comma-separated stock categories (e.g., "FG,WIP") or empty string for all
 * @returns Array of item codes with names
 */
export const fetchSemiFGItemCodes = async (
  stockCategory: string = ''
): Promise<ItemCodeWithName[]> => {
  let url = `${NEXT_PUBLIC_API_URL}/report/semi-fg-item-codes`;
  if (stockCategory && stockCategory !== 'All' && !stockCategory.includes('All')) {
    url = `${url}?stockCategory=${stockCategory}`;
  }

  const response = await clientAuthFetch(url, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
  });

  if (response.status === 401 || response.status === 403) throw new Error("Unauthorized");
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

  return await response.json();
};

/**
 * Fetch item codes with category information for SemiFG Production Analysis Report
 * @param stockCategory - Comma-separated stock categories (e.g., "FG,WIP") or empty string for all
 * @returns Array of item codes with category and name
 */
export const fetchSemiFGItemCodesWithCategory = async (
  stockCategory: string = ''
): Promise<ItemCodeWithCategory[]> => {
  let url = `${NEXT_PUBLIC_API_URL}/report/semi-fg-item-codes-with-category`;
  if (stockCategory && stockCategory !== 'All' && !stockCategory.includes('All')) {
    url = `${url}?stockCategory=${stockCategory}`;
  }

  const response = await clientAuthFetch(url, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
  });

  if (response.status === 401 || response.status === 403) throw new Error("Unauthorized");
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

  return await response.json();
};

/**
 * Generate and download the SemiFG Production Analysis Report PDF
 * @param criteria - Report criteria parameters
 * @param reportTitle - Title of the report for filename
 * @returns Promise that resolves when download is complete
 */
export const generateSemiFGProductionAnalysisReport = async (
  criteria: Record<string, string>,
  reportTitle: string = '成品/半成品生產分析報告'
): Promise<void> => {
  const queryParams = new URLSearchParams(criteria).toString();
  const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis?${queryParams}`;

  const response = await clientAuthFetch(url, {
    method: 'GET',
    headers: { Accept: 'application/pdf' },
  });

  if (response.status === 401 || response.status === 403) throw new Error("Unauthorized");
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

  const blob = await response.blob();
  const downloadUrl = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = downloadUrl;
  
  const contentDisposition = response.headers.get('Content-Disposition');
  let fileName = `${reportTitle}.pdf`;
  if (contentDisposition?.includes('filename=')) {
    fileName = contentDisposition.split('filename=')[1].split(';')[0].replace(/"/g, '');
  }
  
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(downloadUrl);
};

/**
 * Generate and download the SemiFG Production Analysis Report as Excel
 * @param criteria - Report criteria parameters
 * @param reportTitle - Title of the report for filename
 * @returns Promise that resolves when download is complete
 */
export const generateSemiFGProductionAnalysisReportExcel = async (
  criteria: Record<string, string>,
  reportTitle: string = '成品/半成品生產分析報告'
): Promise<void> => {
  const queryParams = new URLSearchParams(criteria).toString();
  const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis-excel?${queryParams}`;

  const response = await clientAuthFetch(url, {
    method: 'GET',
    headers: { Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
  });

  if (response.status === 401 || response.status === 403) throw new Error('Unauthorized');
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

  const blob = await response.blob();
  const downloadUrl = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = downloadUrl;

  const contentDisposition = response.headers.get('Content-Disposition');
  let fileName = `${reportTitle}.xlsx`;
  if (contentDisposition?.includes('filename=')) {
    fileName = contentDisposition.split('filename=')[1].split(';')[0].replace(/"/g, '');
  }

  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(downloadUrl);
};
