'use client';

import React, { useEffect, useRef } from 'react';
import { Box, Stack, Container } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useCongeTabs } from '../hooks/use-conge-tab';
import { useCongeTable } from '../hooks/use-conge-table';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import CongeTable from '../components/conge-table';
import { TableType } from '@/shared/types/common';
import { useSearchParams } from 'next/navigation';
import CongeOverview from '../components/conge-overview';
import { ScrollBox } from '@/shared/theme/css';
import CongeForm from './conge-new-view';
import { ILeave } from '@/shared/types/leave';
import { _leaves } from '@/shared/_mock/_conge';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

export default function CongeListView() {
  const searchParams = useSearchParams();
  const congeId = searchParams.get('id');
  
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleViewHistory,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useCongeTabs();

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

  const isFirstRender = useRef(true);

  useEffect(() => {
    if (congeId && isFirstRender.current) {
      const conge = _leaves.find(c => c.id === congeId);
      if (conge) {
        handleView(conge);
        isFirstRender.current = false;
      }
    }
  }, [congeId, handleView]);

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

  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
    <Container maxWidth={false}>
       
      {/* Overview Section */}
      <Box sx={{ mb: 3 }}>
  <CongeOverview data={filteredData} />
</Box>

      {/* Main Content */}
      
        <Stack
          flexGrow={0}
          direction="row"
          alignItems="center"
          justifyContent="flex-end"
          spacing={{ xs: 0.5, sm: 1 }}
        >
          <TableControlBar
            type={TableType.Conge}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
          />
        </Stack>

        <CustomTabs
          type={TableType.Conge}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />

        {activeTab === 'list' ? (
          <CongeTable
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            handleEdit={handleEdit}
            handleView={handleView}
            handleViewHistory={handleViewHistory}
          />
        ) : (
          <CongeForm
            key={activeTab}
            conge={activeTabData?.content as ILeave}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(forceClose) => handleCancel(activeTab, forceClose)}
            onEdit={handleEdit}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        )}

    </Container>
    <UnsavedChangesDialog
      open={showConfirmDialog}
      onClose={() => setShowConfirmDialog(false)}
      onConfirm={handleConfirmDialogAction}
      onCancel={() => setShowConfirmDialog(false)}
    />
    </ScrollBox>
  );
}