"use client"

import React, { useMemo, useState } from "react"
import { Box, Stack, Typography } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { TableType } from "@/shared/types/common"
import CustomTabs from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { ColumnButton } from "@/shared/components/table/styles"
import CustomDrawer from "@/shared/components/drawer/custom-drawer"
import VehicleTypeListView from "../../vehicleType/view/vehicle-type-list-view"
import { useResponsive } from "@/hooks"
import { useVehicleBrandModelTabs } from "../hooks/use-vehicle-brand-model-tabs"
import { useVehicleBrandModelTable } from "../hooks/use-vehicle-brand-model-table"
import VehicleBrandModelTableRow from "./vehicle-brand-model-table-row"
import { VehicleBrandModel } from "@/shared/types/fleet-management/vehicle-brand-model"
import VehicleBrandModelForm from "./vehicle-brand-model-new-view"
import { useSnackbar } from "notistack"

export default function VehicleBrandModelListView() {

  const { enqueueSnackbar } = useSnackbar();

  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const DRAWER_WIDTH = useResponsive("down", "lg") ? 600 : 800;

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

  const {
    error,
    loading,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    dataToExport,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalVehicleBrandModels,
    sortBy,
    sortDirection,
    handleStartExportVehicleBrandModels
  } = useVehicleBrandModelTable();

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

  const renderRow = (row: VehicleBrandModel) => (
    <VehicleBrandModelTableRow
      key={row.id}
      row={row}
      handleEdit={handleEdit}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  )

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

  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 }}>
        <CustomTooltip title={"Gestion des types de véhicules"} arrow>
          <ColumnButton variant="contained" onClick={handleViewList}>
            Types de véhicules
          </ColumnButton>
        </CustomTooltip>

        <TableControlBar
          type={TableType.VehicleBrandModel}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      <CustomTabs
        type={TableType.VehicleBrandModel}
        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={totalVehicleBrandModels}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      ) : (
        <VehicleBrandModelForm
          key={activeTab}
          vehicleBrandModel={activeTabData?.content as VehicleBrandModel}
          mode={activeTabData?.mode || "view"}
          onClose={(force) => handleCancel(activeTab, force)}
          onEdit={handleEdit}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
      <CustomDrawer
        drawerWidth={DRAWER_WIDTH}
        open={isDrawerOpen}
        onClose={() => setIsDrawerOpen(false)}
      >
        <Typography
          variant="h5"
          sx={{
            my: 3,
            color: 'primary.main',
            fontWeight: (theme) => theme.typography.fontWeightBold,
          }}
        >
          Types de véhicules
        </Typography>
        <VehicleTypeListView />
      </CustomDrawer>
    </Box>
  )
}