"use client"

import type React from "react"

import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import { useVehicleRepairStore } from "@/shared/api/stores/fleet-service/vehicle-repair-store"
import type { TableColumn } from "@/shared/types/common"
import type { VehicleRepairListResponse, VehicleRepairPageFilterParams, RepairStatus } from "@/shared/types/fleet-management/vehicle-repair"
import { useEffect, useState } from "react"
import { useSnackbar } from "notistack"

export const DEFAULT_VEHICLE_REPAIR_TABLE_HEAD: TableColumn[] = [
  { id: "id", label: "Id", type: "text" },
  { id: "vehicleName", label: "Véhicule", type: "text" },
  { id: "interventionName", label: "Intervention", type: "text" },
  { id: "garageName", label: "Garage", type: "text" },
  { id: "sectorName", label: "Sécteur", type: "text" },
  { id: "departmentName", label: "Département", type: "text" },
  { id: "repairStatus", label: "Statut", type: "text" },
  { id: "costTTC", label: "Coût TTC", type: "number" },
  { id: "", label: "Action" },
]


const vehicleRepairConfig: TableConfig<VehicleRepairListResponse> = {
  initialData: [],
  defaultTableHead: DEFAULT_VEHICLE_REPAIR_TABLE_HEAD,
}

export function useVehicleRepairTable() {
  const { enqueueSnackbar } = useSnackbar()

  const [statusFilter, setStatusFilter] = useState<RepairStatus | undefined>(undefined)

  const [params, setParams] = useState<VehicleRepairPageFilterParams>({
    page: 0,
    size: 20,
    orderBy: "id",
    orderDir: "desc",
  })

  const { loading, error, repairsPage, totalElements, fetchRepairsPage, startCsvExport } = useVehicleRepairStore()

  useEffect(() => {
    const fetchParams: VehicleRepairPageFilterParams = {
      page: params.page,
      size: params.size,
      orderBy: "id",
      orderDir: "desc",
    }

    if (statusFilter) {
      fetchParams.repairStatus = statusFilter
    }

    fetchRepairsPage(fetchParams)
  }, [statusFilter, params.page, params.size, fetchRepairsPage])

  const tableManager = useTableManager<any>({
    ...vehicleRepairConfig,
    initialData: repairsPage || [],
  })

  const onResetFilters = () => {
    tableManager.handleResetFilters()
    setStatusFilter(undefined)
    setParams({
      page: 0,
      size: 20,
      orderBy: "id",
      orderDir: "desc",
    })
  }

  // Now sorting and filtering are handled client-side by tableManager

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

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

  const userId = localStorage.getItem("userId")

  const handleStartCsvExportRepairs = () => {
    if (userId) {
      const exportParams: VehicleRepairPageFilterParams = {
        page: 0,
        size: totalElements || 1000, // Export all records
        orderBy: tableManager.table.orderBy || "id",
        orderDir: tableManager.table.order.toLowerCase() as "asc" | "desc",
      }

      if (statusFilter) {
        exportParams.repairStatus = statusFilter
      }

      startCsvExport(userId, exportParams)
    } else {
      enqueueSnackbar("Nous n'avons pas pu identifier l'utilisateur connecté.")
    }
  }

  return {
    ...tableManager,
    loading,
    error,
    totalRepairs: totalElements || 0,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    sortBy: tableManager.table.orderBy || "id",
    sortDirection: tableManager.table.order || "desc",
    filteredData: tableManager.filteredData,
    handleStartCsvExportRepairs,
    onResetFilters: onResetFilters,
    setStatusFilter,
  }
}
