"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 { VacationType, ZoneType, type IVacance } from "@/shared/types/vacance"
import {
  _vacationFileImportData,
  _vacationFileImportHeaders,
  DEFAULT_VACANCES_TABLE_HEAD
} from "@/shared/_mock/_vacance"
import VacanceTableRow from "./holiday-import-table-row"
import VacationForm from "./holiday-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';
import dayjs from "dayjs"
import { useCalendarHolidays } from "../hooks/use-calendar-holidays"
import { useHolidayImportTable } from "../hooks/use-holiday-import-table"
import { useHolidayImportTabs } from "../hooks/use-holiday-import-tabs"
import { IHolidayGeneral, IHolidayImport } from "@/shared/types/establishment"
import HolidayImportTableRow from "./holiday-import-table-row"

export const DEFAULT_VACATION_FILE_IMPORT: IHolidayImport = {
  id: "",
  holidayImportName: "",
  createdAt: "",
  importedBy: "",
  zones: [],
}
interface Props {
  isChild?: boolean
}

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

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

  const {
    table: vacancesTable,
    filteredData: calendarHolidaysFilteredData,
    filters: vacancesFilters,
    tableHead: vacancesTableHead,
    notFound: vacancesNotFound,
    handleFilterChange: handleVacancesFilterChange,
    handleResetFilters: handleVacancesResetFilters,
    handleResetColumns: handleVacancesResetColumns,
    handleColumnsChange: handleVacancesColumnsChange,
    handleSave: handleVacancesSave,
    handleCsvExportHolidays
  } = useCalendarHolidays(selectedDate, timeUnit);

  const exportOptions = useMemo(() => [
    {
      label: "Exporter en CSV",
      action: () => handleCsvExportHolidays()
    }
  ], [handleCsvExportHolidays]);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    onResetFilters
  } = useHolidayImportTable();

  const mapToCalendarEvent = (holidays: IHolidayGeneral[]) => {
    return holidays.map((holiday) => ({
      id: holiday.id,
      startDate: new Date(holiday.startDate),
      endDate: new Date(holiday.endDate),
      label: holiday.name,
      color: holiday.zoneName.toLowerCase() === "zone a" ? HolidayZoneColor.ERROR : holiday.zoneName.toLowerCase() === "zone b" ? HolidayZoneColor.INFO : holiday.zoneName.toLowerCase() === "zone c" ? HolidayZoneColor.WARNING : HolidayZoneColor.PRIMARY,
      bgColor: holiday.zoneName.toLowerCase() === "zone a" ? getBgColor(HolidayZoneColor.ERROR) : holiday.zoneName.toLowerCase() === "zone b" ? getBgColor(HolidayZoneColor.INFO) : holiday.zoneName.toLowerCase() === "zone c" ? getBgColor(HolidayZoneColor.WARNING) : getBgColor(HolidayZoneColor.PRIMARY)
    }))
  }

  useEffect(() => {
    setCalendarEvents(mapToCalendarEvent(calendarHolidaysFilteredData))
    console.log("calendarHolidaysFilteredData", calendarHolidaysFilteredData)
    console.log("mapToCalendarEvent", mapToCalendarEvent(calendarHolidaysFilteredData))
  }, [calendarHolidaysFilteredData])

  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,
  } = useHolidayImportTabs();

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

  const handlePreviousMonth = () => {
    goToPreviousMonth()
    setSelectedDate(dayjs(selectedDate).subtract(1, 'month').toDate())
  }

  const handleNextMonth = () => {
    goToNextMonth()
    setSelectedDate(dayjs(selectedDate).add(1, 'month').toDate())
  }

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

  const isLastCreated = (row: IHolidayImport) => {
    if (!filteredData.length) return false;
    const sorted = [...filteredData].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    return row.id === sorted[0].id;
  }

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

  const renderRow = (row: IHolidayImport) => (
    <HolidayImportTableRow
      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)}
      isLastCreated={isLastCreated(row)}
    />
  )
  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={onResetFilters}
          onFilters={handleVacancesFilterChange}
          initialColumns={vacancesTableHead.slice(0, -1)}
          type={TableType.Vacance}
          timeUnit={timeUnit}
          goToPreviousMonth={handlePreviousMonth}
          goToNextMonth={handleNextMonth}
          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={calendarHolidaysFilteredData}
              tableHead={vacancesTableHead.slice(0, -1)}
              options={exportOptions}
            />

          }
          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
            key={calendarEvents.map(e => e.id).join("-")}
            date={selectedDate}
            handleTabAdd={handleFileImportTabAdd}
            formattedMonth={formattedMonth}
            calendarData={calendarData}
            isToday={isToday}
            isCurrentMonth={isCurrentMonth}
            getPeriodsForDate={getEventsForDate}
            goToPreviousMonth={handlePreviousMonth}
            goToNextMonth={handleNextMonth}
            goToToday={goToToday}
            zoomLevel={zoomLevel}
            isChild={isChild}
          />
        )
      ) : (
        <VacationForm
          holidayImport={activeTabData?.content as IHolidayImport}
          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 des importations de vacances/Jours fériés
        </Typography>

        <TableManager
          filteredData={filteredData as IHolidayImport[]}
          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>
  )
}

export enum HolidayZoneColor {
  ERROR = "#FF3434",
  SUCCESS = "#30BA1D",
  WARNING = "#F9B90B",
  INFO = "#5176FE",
  PRIMARY = "#746CD4",
  GREY = "#919EAB",
}

export const getBgColor = (color: HolidayZoneColor) => {
  switch (color) {
    case HolidayZoneColor.ERROR:
      return "#FFEBEB";
    case HolidayZoneColor.SUCCESS:
      return "#EAF8E8";
    case HolidayZoneColor.WARNING:
      return "#FEF8E7";
    case HolidayZoneColor.INFO:
      return "#EEF1FF";
    case HolidayZoneColor.GREY:
      return "#DFE3E8";
    case HolidayZoneColor.PRIMARY:
      return 'primary.lighter';
    default:
      return 'primary.lighter';
  }
};