import { useState, useEffect } from 'react';
import { ContractPageFilterParams, ContractList, ContractStatus } from '@/shared/types/contract';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableColumn } from '@/shared/types/common';
import { useContractStore } from '@/shared/api/stores/admin-service/contractStore';
import React from 'react';

export const DEFAULT_TABLE_HEAD: TableColumn[] = [
  { id: 'id', label: 'N° Contrat', type: 'text' },
  { id: 'marketDate', label: 'Date de Marché', type: 'date' },
  { id: 'renewalDate', label: 'Date de Renouvellement', type: 'date' },
  { id: 'endDate', label: 'Date de fin', type: 'date' },
  { id: 'contractCode', label: 'Code de contrat', type: 'text' },
  { id: 'title', label: 'Intitulé', type: 'text' },
  { id: 'departmentName', label: 'Client', type: 'text' },
  { id: 'companyName', label: 'Société', type: 'text' },
  { id: 'agencyName', label: 'Agence', type: 'text' },
  { id: 'marketNumber', label: 'N° de marché', type: 'text' },
  { id: 'lotNumber', label: 'N° de lot', type: 'text' },
  { id: 'status', label: 'Status', type: 'status' },
  { id: '', label: 'Action' },
];

const contractConfig: TableConfig<ContractList> = {
  initialData: [],
  defaultTableHead: DEFAULT_TABLE_HEAD,
};

export function useContractTable() {
  const [params, setParams] = useState<ContractPageFilterParams>({
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'desc'
  });

  const { contracts, totalElements, loading, error, fetchContractsPage, startExportFiltredContracts } = useContractStore();

  useEffect(() => {
    fetchContractsPage(params);
  }, [params]);

  const tableManager = useTableManager<any>({
    ...contractConfig,
    initialData: contracts || [],
  });

  useEffect(() => {
    if (tableManager.table.rowsPerPage > 0) {
      setParams(prev => ({
        ...prev,
        page: tableManager.table.page,
        size: tableManager.table.rowsPerPage,
      }));
    }
  }, [tableManager.table.page, tableManager.table.rowsPerPage]);

  const isValidDateInput = (value: any): boolean => {
    if (!value || typeof value !== 'string') return false;
    const date = new Date(value);
    return date instanceof Date && !isNaN(date.getTime());
  };

  const isValidFilterValue = (value: any): boolean => {
    return value !== null && value !== undefined && value !== '';
  };

  useEffect(() => {
    const baseParams: ContractPageFilterParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'id',
      sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc'
    };
    const filterParams: Record<string, string | number> = {};
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (key === 'companyName' && isValidFilterValue(value)) {
        filterParams['agencyName'] = value;
      }
      if (key === 'id' && isValidFilterValue(value)) {
        filterParams[key] = Number(value);
      } else if (['renewalDate', 'endDate', 'marketDate'].includes(key) && isValidDateInput(value)) {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        filterParams[key] = `${year}-${month}-${day}T00:00:00`;
      } else if (key === 'status' && isValidFilterValue(value)) {
        let status: ContractStatus;
        switch (value.toLowerCase()) {
          case 'nouveau':
            status = ContractStatus.NEW;
            break;
          case 'en cours':
            status = ContractStatus.IN_PROGRESS;
            break;
          case 'terminé':
            status = ContractStatus.COMPLETED;
            break;
          case 'résilié':
            status = ContractStatus.CANCELLED;
            break;
          case 'archivé':
            status = ContractStatus.ARCHIVED;
            break;
          default:
            status = ContractStatus.NEW;
        }
        filterParams[key] = status;
      }
      else if (isValidFilterValue(value)) {
        filterParams[key] = value;
      }
    });

    const newParams: ContractPageFilterParams = {
      ...baseParams,
      ...filterParams
    };

    const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
    if (paramsChanged) {
      setParams(newParams);
    }
  }, [tableManager.filters, tableManager.table.orderBy, tableManager.table.order]);

  const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setParams(prev => ({
      ...prev,
      page: newPage
    }));
  };

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const size = parseInt(event.target.value, 10);
    if (!isNaN(size) && size > 0) {
      setParams(prev => ({
        ...prev,
        size,
        page: 0
      }));
    }
  };

  const handleStartExportContracts = () => {
    delete params.page;
    delete params.size;
    delete params.sortBy;
    delete params.sortDirection;
    startExportFiltredContracts(params);
  };

  return {
    ...tableManager,
    loading,
    error,
    totalContracts: totalElements || 0,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    sortBy: params.sortBy || 'id',
    sortDirection: params.sortDirection || 'desc',
    filteredData: contracts,
    handleStartExportContracts: handleStartExportContracts
  };
}