"use client"

import React, { useMemo } from "react"
import { Box, Stack } from "@mui/material"
import { useVehicleTypeTabs } from "../hooks/use-vehicle-type-tabs"
import { TableType } from "@/shared/types/common"
import CustomTabs from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import VehicleTypeForm from "./vehicle-type-new-view"
import VehicleTypeTableRow from "./vehicle-type-table-row"
import { useVehicleTypeTable } from "../hooks/use-vehicle-type-table"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { AddButton } from "@/shared/components/table/styles"
import FontAwesome from "@/shared/components/fontawesome"
import { faSquarePlus } from "@fortawesome/free-solid-svg-icons"
import { VehicleType } from "@/shared/types/fleet-management/vehicleType"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { useSnackbar } from "notistack"

export default function VehicleTypeListView() {

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    error,
    loading,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleSave,
    handleResetColumns,
    handleResetFilters,
    handleColumnsChange,
    dataToExport,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalVehicleTypes,
    sortBy,
    sortDirection,
    handleStartExportVehicleTypes,
  } = useVehicleTypeTable()

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

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

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

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

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        mt: 2
      }}
    >
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
        <TableControlBar
          type={TableType.VehicleType}
          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.VehicleType}
        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}
          sx={{ backgroundColor: 'primary.lighter' }}
          fixedHeight="calc(100vh - 200px)"
          onPageChange={onPageChange}
          page={page || 0}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage || 20}
          count={totalVehicleTypes}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      ) : (
        <VehicleTypeForm
          key={activeTab}
          vehicleType={activeTabData?.content as VehicleType}
          mode={activeTabData?.mode || "view"}
          onSave={handleSave}
          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)}
      />
    </Box>
  )
}