"use client"

import React, { useMemo, useState } from "react"
import { Box, Stack, Tab, Tabs } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { useVehicleRepairTabs } from "../hooks/use-vehicle-repair-tabs"
import { useVehicleRepairTable } from "../hooks/use-vehicle-repair-table"
import { TableType } from "@/shared/types/common"
import TableManager from "@/shared/components/table/table-manager"
import VehicleRepairForm from "./vehicle-repair-new-view"
import VehicleRepairTableRow from "./vehicle-repair-table-row"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { RepairStatus, type VehicleRepairListResponse } from "@/shared/types/fleet-management/vehicle-repair"
import { useSnackbar } from "notistack"
import CustomTabs from '@/shared/components/tabs/tabs-custom';

export default function VehicleRepairListView() {
  const { enqueueSnackbar } = useSnackbar()

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

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useVehicleRepairTabs()

  const {
    error,
    loading,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalRepairs,
    sortBy,
    sortDirection,
    handleStartCsvExportRepairs,
    setStatusFilter: setTableStatusFilter,
    handleStatusChange,
  } = useVehicleRepairTable()

  const activeTabData = React.useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab)
  }, [tabs, activeTab])

  const renderRow = (row: VehicleRepairListResponse) => (
    <VehicleRepairTableRow
      key={row.id}
      row={row}
      handleCopyRepair={handleCopy}
      handleEditRepair={handleEdit}
      handleDetailsRepair={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
    />
  )

  const exportOptions = useMemo(
    () => [
      {
        label: "Lancer l'export en CSV",
        action: () => handleStartCsvExportRepairs(),
      },
    ],
    [handleStartCsvExportRepairs],
  )

  const handleStatusTabChange = (event: React.SyntheticEvent, newValue: RepairStatus | "ALL") => {
    setStatusFilter(newValue)
    setTableStatusFilter(newValue === "ALL" ? undefined : newValue)
  }

  if (error) {
    enqueueSnackbar(error, { variant: "error" })
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
        <TableControlBar
          type={TableType.VehicleRepair}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      {activeTab === "list" && (
        <Box sx={{ borderBottom: 1, borderColor: "divider", mb: 2 }}>
          <Tabs
            value={statusFilter}
            onChange={handleStatusTabChange}
            aria-label="status filter tabs"
            sx={{
              "& .MuiTab-root": {
                textTransform: "none",
                fontWeight: 500,
                fontSize: "0.95rem",
                minWidth: 120,
              },
            }}
          >
            <Tab label="Tous" value="ALL" />
            <Tab label="En attente" value={RepairStatus.PENDING} />
            <Tab label="En cours" value={RepairStatus.IN_PROGRESS} />
            <Tab label="Clôturé" value={RepairStatus.CLOSED} />
          </Tabs>
        </Box>
      )}

      <CustomTabs
        type={TableType.VehicleRepair}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === "list" ? (
        <TableManager
          loading={loading}
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          onPageChange={onPageChange}
          page={page || 0}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage || 20}
          count={totalRepairs}
          sortBy={sortBy || "id"}
          sortDirection={sortDirection || "desc"}
        />
      ) : (
        <VehicleRepairForm
          key={activeTabData?.id}
          repair={activeTabData?.content as VehicleRepairListResponse}
          mode={activeTabData?.mode || "view"}
          onClose={() => handleCancel(activeTab, true)}
          onEdit={handleEdit}
          tableHead={tableHead}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  )
}
