'use client';

import { useCallback, useMemo, useState } from 'react';
import { Box, Stack, Typography } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { TableType } from '@/shared/types/common';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import EstablishmentForm from './establishment-form-view';
import ScheduleTable from '@/shared/components/form/schedule-table';
import { ScrollBox } from '@/shared/theme/css';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { EstablishmentTableItem } from '@/shared/types/establishment';
import { useEstablishmentTabs } from '../hooks/use-establishment-tabs';
import { useEstablishmentTable } from '../hooks/use-establishment-table';
import EstablishmentTableRow from './establishment-table-row';


export default function EstablishmentListView() {
  const [scheduleState, setScheduleState] = useState({
    showScheduleTable: false,
    selectedEtablissement: null as EstablishmentTableItem | null,
    defaultTime: "08:00 AM",
  })

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useEstablishmentTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    totalEstablishments,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    sortBy,
    sortDirection,
  } = useEstablishmentTable();

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

  const handleHoraireClick = useCallback((etablissement: EstablishmentTableItem) => {
    setScheduleState((prevState) => {
      if (prevState.selectedEtablissement?.id === etablissement.id) {
        return {
          ...prevState,
          showScheduleTable: !prevState.showScheduleTable,
          selectedEtablissement: null,
        }
      } else {
        const randomHour = Math.floor(Math.random() * 12) + 1
        const amPm = Math.random() < 0.5 ? "AM" : "PM"
        const newTime = `${randomHour.toString().padStart(2, "0")}:00 ${amPm}`
        return {
          showScheduleTable: true,
          selectedEtablissement: etablissement,
          defaultTime: newTime,
        }
      }
    })
  }, [])

  const renderRow = (row: EstablishmentTableItem) => (
    <EstablishmentTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleHoraireClick={handleHoraireClick}
      handleEdit={handleEdit}
      handleCopy={handleCopy}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      selectedHoraire={row.id === scheduleState.selectedEtablissement?.id}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  );

  const isList = activeTab === 'list';
  const CustomBox = isList && scheduleState.showScheduleTable ? ScrollBox : Box;

  return (
    <CustomBox
      sx={
        isList && scheduleState.showScheduleTable
          ? { pb: 0, height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }
          : {
            display: 'flex',
            flexDirection: 'column',
            height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
          }
      }
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.Etablissement}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
        />
      </Stack>
      {scheduleState.showScheduleTable ? (
        <Typography
          variant="h5"
          sx={{
            mb: 2,
            color: 'primary.main',
            fontWeight: 'bold',
          }}
        >
          Liste Établissements
        </Typography>
      ) : (
        <></>
      )}
      <TabsCustom
        type={TableType.Etablissement}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {isList ? (
        <>
          <TableManager
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
            fixedHeight={scheduleState.showScheduleTable ? `calc(100vh - ${HEADER.H_DESKTOP + 195}px)` : undefined}
            onPageChange={onPageChange}
            page={page || 0}
            onRowsPerPageChange={onRowsPerPageChange}
            rowsPerPage={rowsPerPage || 20}
            sortBy={sortBy || 'id'}
            sortDirection={sortDirection || 'desc'}
            count={totalEstablishments || 0}
          />
          {scheduleState.showScheduleTable ? (
            <ScheduleTable
              title={`${scheduleState.selectedEtablissement?.establishmentName} (Horaire)`}
              defaultTime={scheduleState.defaultTime}
              mode="time"
              isInEstablishment
            />
          ) : (
            <></>
          )}
        </>
      ) : (
        <EstablishmentForm
          key={activeTab}
          etablissement={activeTabData?.content as EstablishmentTableItem}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={(force) => handleCancel(activeTab, force)}
          onEdit={handleEdit}
          tableHead={tableHead.slice(0, -1)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </CustomBox>
  );
}