"use client"

import React, { useEffect, useMemo, useState } from "react"
import { Box, Stack, Typography, TextField, InputAdornment } from "@mui/material"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { TableType } from "@/shared/types/common"
import TableManager from "@/shared/components/table/table-manager"
import FontAwesome from "@/shared/components/fontawesome"
import { faSearch, faSquarePlus } from "@fortawesome/free-solid-svg-icons"
import { enqueueSnackbar, useSnackbar } from "notistack"
import { FuelType } from "@/shared/types/fleet-management/fuelType"
import { useFuelTypeTable } from "../hooks/use-fuel-type-table"
import FuelTypeTableRow from "./fuel-type-table-row"
import { useFuelTypeTabs } from "../hooks/use-fuel-type-tabs"
import { AddButton } from "@/shared/components/table/styles"
import CustomTabs from "@/shared/components/tabs/tabs-custom"
import FuelTypeForm from "./fuel-type-new-view"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

export default function FuelTypeTable() {

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    error,
    loading,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalFuelTypes,
    sortBy,
    sortDirection,
    dataToExport,
    handleColumnsChange,
    keyword,
    setKeyword,
    handleStartExportFuelTypes
  } = useFuelTypeTable();

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

  useEffect(() => {
    if (keyword) {
      handleResetFilters();
    }
  }, [keyword, handleResetFilters]);

  useEffect(() => {
    if (filters.id?.value || filters.name?.value) {
      setKeyword("");
    }
  }, [filters, setKeyword]);

  const renderRow = (row: FuelType) => (
    <FuelTypeTableRow
      key={row.id}
      row={row}
      onEdit={handleEdit}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead}
    />
  )

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

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

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        mt: 2
      }}
    >

      <Stack
        flexGrow={0}
        direction="column"
        alignItems="flex-end"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
        sx={{ mb: 4 }}
      >
        <TableControlBar
          type={TableType.FuelType}
          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.FuelType}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      <ConditionalComponent isValid={activeTab === "list"} >
        <TextField
          size="small"
          placeholder="Rechercher par nom ou identifiant..."
          value={keyword}
          onChange={(e) => setKeyword(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <FontAwesome icon={faSearch} sx={{ color: "text.secondary" }} />
              </InputAdornment>
            ),
          }}
          sx={{
            width: 300,
            "& .MuiOutlinedInput-root": {
              borderRadius: 2,
            },
            mt: 2,
            mb: 2
          }}
        />

        <TableManager
          loading={loading}
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          onPageChange={onPageChange}
          page={page}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage}
          count={totalFuelTypes}
          sortBy={sortBy}
          sortDirection={sortDirection}
          fixedHeight="calc(100vh - 380px)"
          sx={{
            backgroundColor: "white",
            "& .MuiTableContainer-root": {
              borderRadius: 2,
            }
          }}
        />
      </ConditionalComponent>
      <ConditionalComponent isValid={activeTab !== "list"} >
        <FuelTypeForm
          key={activeTab}
          fuelType={activeTabData?.content as FuelType}
          mode={activeTabData?.mode || "view"}
          onClose={(force) => handleCancel(activeTab, force)}
          onEdit={handleEdit}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  )
}