"use client"

import { useEffect, useMemo, useState } from "react"
import { Box, IconButton, Stack, Typography } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import { TableType, TimeUnit } from "@/shared/types/common"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"

import type { IFileImport, IVacance } from "@/shared/types/vacance"
import {
  _vacances,
  _vacationFileImportData,
  _vacationFileImportHeaders,
  DEFAULT_VACANCES_TABLE_HEAD,
  DEFAULT_VACATION_FILE_IMPORT,
  getVacancePeriods,
  INITIAL_VACANCES_DATA,
} from "@/shared/_mock/_vacance"
import VacanceTableRow from "./vacance-table-row"
import VacationForm from "./vacance-new-view"
import CustomDrawer from "@/shared/components/drawer/custom-drawer"
import { ExtendedWhiteIconButtonStyle, ScheduleToolbar } from "@/shared/components/schedule/schedule-toolbar"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { AddButton, lightColor } from "@/shared/components/table/styles"
import { faAngleDoubleLeft, faFileExport, faSquarePlus } from "@fortawesome/free-solid-svg-icons"
import { Dayjs } from "dayjs"
import { CalendarEvent, useCalendar } from "@/hooks/use-calendar"
import VacanceYearCalendar from "@/shared/components/calendar/vacance-year-calendar"
import VacanceCalendar from "@/shared/components/calendar/vacance-calendar"
import ExportButton from '@/shared/components/table/table-export-button';

const defaultVacancesConfig: TableConfig<IVacance> = {
  initialData: _vacances,
  defaultTableHead: DEFAULT_VACANCES_TABLE_HEAD,
}

const fileImportConfig: TableConfig<IFileImport> = {
  initialData: _vacationFileImportData,
  defaultTableHead: _vacationFileImportHeaders,
}

const fileImportTabsConfig: TabConfig<IFileImport> = {
  type: TableType.Vacance,
  listTitle: "Liste vacances/Jours fériés",
  newItemTitle: "Nouvelle période",
  initialData: DEFAULT_VACATION_FILE_IMPORT,
  getItemCode: (vacance) => vacance.fileName,
}

interface Props {
  vacancesConfig?: TableConfig<IVacance>
  isChild?: boolean
}


export default function VacanceCalendarListView({
  vacancesConfig = defaultVacancesConfig,
  isChild = false,
}: Props) {

  const {
    table: vacancesTable,
    filteredData: vacancesFilteredData,
    filters: vacancesFilters,
    tableHead: vacancesTableHead,
    notFound: vacancesNotFound,
    handleFilterChange: handleVacancesFilterChange,
    handleResetFilters: handleVacancesResetFilters,
    handleResetColumns: handleVacancesResetColumns,
    handleColumnsChange: handleVacancesColumnsChange,
    handleSave: handleVacancesSave,
  } = useTableManager<IVacance>(vacancesConfig)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<IFileImport>(fileImportConfig)

  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const [selectedDate, setSelectedDate] = useState(new Date())
  const [zoomLevel, setZoomLevel] = useState(50)
  const [vacancePeriods, setVacancePeriods] = useState<CalendarEvent[]>(getVacancePeriods(vacancesFilteredData))
  const [timeUnit, setTimeUnit] = useState<TimeUnit>("month")

  useEffect(() => {
    setVacancePeriods(getVacancePeriods(vacancesFilteredData))
  }, [vacancesFilteredData])

  const handleDateChange = (date: Dayjs | Date, newTimeUnit?: TimeUnit) => {
    setSelectedDate(date instanceof Date ? date : date.toDate())
    if (newTimeUnit) {
      setTimeUnit(newTimeUnit)
    }
  }
  
  const handleZoomChange = (zoom: number) => {
    setZoomLevel(zoom)
  }

  const {
    tabs: fileImportTabs,
    activeTab: fileImportActiveTab,
    handleTabClose: handleFileImportTabClose,
    handleTabChange: handleFileImportTabChange,
    handleTabAdd: handleFileImportTabAdd,
    handleEdit: handleFileImportEdit,
    handleView: handleFileImportView,
    handleCancel: handleFileImportCancel,
    handleCopy: handleFileImportCopy,
  } = useTabsManager<IFileImport>(fileImportTabsConfig)

  const {
    formattedMonth,
    calendarData,
    isToday,
    isCurrentMonth,
    getEventsForDate,
    goToPreviousMonth,
    goToNextMonth,
    goToToday,
    yearCalendarData,
    handleAddEvent,
  } = useCalendar({
    initialDate: selectedDate,
    initialEvents : vacancePeriods,
    onAddEvent: handleFileImportTabAdd,
  })

  const handleViewList = () => {
    setIsDrawerOpen(true)
  }

  const activeTabData = useMemo(() => {
    return fileImportTabs.find((tab) => tab.id === fileImportActiveTab)
  }, [fileImportTabs, fileImportActiveTab])

  const renderRow = (row: IFileImport) => (
    <VacanceTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleFileImportEdit}
      handleCopy={handleFileImportCopy}
      handleDetails={handleFileImportView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  )
  const DRAWER_WIDTH = 560
  const isList = fileImportActiveTab === "list"
  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        width: isDrawerOpen ? `calc(100% - ${DRAWER_WIDTH}px)` : undefined,
        height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)`,
      }}
    >
      {isList ? (
        <ScheduleToolbar
          date={selectedDate}
          onDateChange={handleDateChange}
          onZoomChange={handleZoomChange}
          onResetFilters={handleVacancesResetFilters}
          onFilters={handleVacancesFilterChange}
          initialColumns={vacancesTableHead.slice(0, -1)}
          type={TableType.Vacance}
          timeUnit={timeUnit}
          goToPreviousMonth={goToPreviousMonth}
          goToNextMonth={goToNextMonth}
          customAction={
            <CustomTooltip title={"Consulter liste des Vacances"} arrow>
              <IconButton sx={isChild ? lightColor : ExtendedWhiteIconButtonStyle} onClick={handleViewList}>
                <FontAwesome width={18} icon={faAngleDoubleLeft} />
              </IconButton>
            </CustomTooltip>
          }
          rightAction={
            <ExportButton
              isTableExport
              tooltipTitle={"Exporter"}
              type={TableType.Vacance}
              filteredData={vacancesFilteredData}
              tableHead={vacancesTableHead.slice(0, -1)}
            />

          }
          isChild={isChild}
        />
      ) : (
        <Stack direction="row" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
          <CustomTooltip title={"Ajouter Une Nouvelle période"} arrow>
            <AddButton
              onClick={handleFileImportTabAdd}
              variant="contained"
              endIcon={<FontAwesome icon={faSquarePlus} width={18} />}
            >
              Nouvelle période
            </AddButton>
          </CustomTooltip>
        </Stack>
      )}
      <TabsCustom
        type={TableType.Vacance}
        tabs={fileImportTabs}
        activeTab={fileImportActiveTab}
        handleTabChange={handleFileImportTabChange}
        handleTabClose={handleFileImportTabClose}
      />

      {isList ? (
        timeUnit === "year" ? (
          <VacanceYearCalendar
            date={selectedDate}
            isToday={isToday}
            handleTabAdd={handleFileImportTabAdd}
            zoomLevel={zoomLevel}
            yearCalendarData={yearCalendarData}
            isChild={isChild}
          />
        ) : (
          <VacanceCalendar
            date={selectedDate}
            handleTabAdd={handleFileImportTabAdd}
            formattedMonth={formattedMonth}
            calendarData={calendarData}
            isToday={isToday}
            isCurrentMonth={isCurrentMonth}
            getPeriodsForDate={getEventsForDate}
            goToPreviousMonth={goToPreviousMonth}
            goToNextMonth={goToNextMonth}
            goToToday={goToToday}
            zoomLevel={zoomLevel}
            isChild={isChild}
          />
        )
      ) : (
        <VacationForm
          vacation={activeTabData?.content as IFileImport}
          mode={activeTabData?.mode || "view"}
          onSave={handleSave}
          onClose={() => handleFileImportCancel(fileImportActiveTab)}
          onEdit={handleFileImportEdit}
          isChild={isChild}
        />
      )}
      <CustomDrawer drawerWidth={DRAWER_WIDTH} open={isDrawerOpen} onClose={() => setIsDrawerOpen(false)}>
        <Typography
          variant="h5"
          sx={{
            my: 2,
            color: "primary.main",
            fontWeight: (theme) => theme.typography.fontWeightBold,
          }}
        >
          Liste vacances/Jours fériés
        </Typography>

        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          isDrawer
          sx={{ backgroundColor: "primary.lighter", pr: 0 }}
          fixedHeight="calc(100vh - 110px)"
        />
      </CustomDrawer>
    </Box>
  )
}

