"use client"

import type React from "react"

import { Box, IconButton } from '@mui/material';
import FontAwesome from '../fontawesome';
import { faSquarePlus, faRotate, faFileImport } from '@fortawesome/free-solid-svg-icons';
import { AddButton, mainColor, secoundaryColor } from './styles';
import CustomTooltip from '../tooltips/tooltip-custom';
import { ColumnSelector } from '../column-selector/column-selector';
import TableFilter from './table-filter';
import { TableColumn, TableType } from '@/shared/types/common';
import ExportButton from '@/shared/components/table/table-export-button';
import { WhiteIconButtonStyle } from '@/shared/theme/css';
import ImportButton from "@/shared/components/table/table-import-button";
import ConditionalComponent from './ConditionalComponent';
import BackendExportButton from '@/shared/components/table/table-backend-export-button';

interface TableControlBarProps<T> {
  withoutColumnSelector?: boolean;
  withImport?: boolean;
  type: string;
  activeTab: string;
  handleTabAdd?: () => void;
  onResetFilters: () => void;
  onResetColumns: () => void;
  onColumnsChange: (columns: { id: string; label: string }[]) => void;
  initialColumns: TableColumn[];
  onFilters: (key: string, value: string, condition: string) => void;
  filteredData: T[];
  action?: React.ReactNode;
  buttonAddTitle?: string;
  useBackendExport?: boolean;
  exportOptions?: { label: string; action: () => void }[];
}

const TOOLTIP_TITLES = {
  manageColumns: "Gérer les colonnes",
  refresh: "Rafraîchir",
  export: "Exporter",
  import: "importer",
  createNew: "Nouveau ",
}

export default function TableControlBar<T extends { id: string }>({
  type,
  activeTab,
  handleTabAdd,
  onResetFilters,
  onResetColumns,
  onColumnsChange,
  initialColumns,
  onFilters,
  withoutColumnSelector,
  withImport,
  filteredData,
  action,
  buttonAddTitle,
  useBackendExport,
  exportOptions,
}: TableControlBarProps<T>) {
  const handleRefresh = () => {
    onResetFilters()
    onResetColumns()
  }

  const getDefaultButtonTitle = () => {
    if (type === TableType.Vacance) return "Nouvelle période"
    if (type === TableType.AbsenceUsager) return "Nouvelle absence"
    if (type === TableType.DemandeAbsence) return "Nouvelle demande"
    if (type === TableType.Equipe) return "Nouvelle équipe"
    if (type === TableType.Notification) return "Nouvelle notification"
    if (type === TableType.DriverRoadmap) return "Nouvelle feuille de route"
    return TOOLTIP_TITLES.createNew + type
  }

  const buttonTitle = buttonAddTitle || getDefaultButtonTitle()

  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, pt: 1, pb: 1 }}>
      <ConditionalComponent isValid={!!handleTabAdd}>
        <AddButton
          onClick={handleTabAdd}
          variant="contained"
          endIcon={<FontAwesome icon={faSquarePlus} width={18} />}
        >
          {buttonTitle}
        </AddButton>
      </ConditionalComponent>

      {activeTab === 'list' ? (
        <>
          {action ? <Box sx={{ flexShrink: 0 }}> {action} </Box> : <></>}
          {!withoutColumnSelector ? (
            <CustomTooltip title={TOOLTIP_TITLES.manageColumns} arrow>
              <ColumnSelector
                sx={{
                  ...(!handleTabAdd ? mainColor : secoundaryColor),
                }}
                onConfirm={onColumnsChange}
                initialColumns={initialColumns.filter(
                  (column) => column.id !== "isActive" && column.id !== "isArchive",
                )}
              />
            </CustomTooltip>
          ) : (
            <></>
          )}

          <Box
            sx={{
              borderLeft: 1,
              height: 30,
              borderColor: (theme) => theme.palette.text.disabled,
              mx: 1,
            }}
          />

          <TableFilter
            onResetFilters={onResetFilters}
            onFilters={onFilters}
            initialColumns={initialColumns}
            type={type}
          />

          <CustomTooltip title={TOOLTIP_TITLES.refresh} arrow>
            <IconButton sx={WhiteIconButtonStyle} onClick={handleRefresh}>
              <FontAwesome icon={faRotate} width={18} />
            </IconButton>
          </CustomTooltip>
          {withImport ? (
            <ImportButton
              tooltipTitle={TOOLTIP_TITLES.import}
              isTableImport
              onImportSuccess={() => {
                handleRefresh()
              }}
              type={type}
            />
          ) : (
            <></>
          )}
          {useBackendExport && exportOptions ? (
            <BackendExportButton
              isTableExport
              tooltipTitle={TOOLTIP_TITLES.export}
              exportOptions={exportOptions}
            />
          ) : (
            <ExportButton
              isTableExport
              tooltipTitle={TOOLTIP_TITLES.export}
              type={type}
              filteredData={filteredData}
              tableHead={initialColumns}
            />
          )}
        </>
      ) : (
        <></>
      )}
    </Box>
  )
}

