'use client';

import React from 'react';
import { Box, Stack } from '@mui/material';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useRoleTable } from '../hooks/use-role-table';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import { IRole } from '@/shared/types/role';
import { RoleStatus } from '@/shared/api/stores/roleStore';
import { useRoleStore } from '@/shared/api/stores/roleStore';

import { TableType } from '@/shared/types/common';
import { useRoleTabs } from '../hooks/use-role-tabs';
import RoleForm from './role-new-view';
import RoleTable from '../components/role-table';
import { UnsavedChangesDialog } from '../../../../../components/dialog/UnsavedChangesDialog';

export default function RoleContent() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useRoleTabs();

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

  const { toggleRoleStatus } = useRoleStore();

  const handleEditRole = (role: IRole) => {
    handleEdit(role);
  };

  const handleDetailsRole = (role: IRole) => {
    handleView(role);
  };

  const handleArchiveRole = (role: IRole) => {
    toggleRoleStatus(role.id, 'DISABLED');
  };

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

  const handleStatusChange = (row: IRole, newStatus: RoleStatus) => {
    toggleRoleStatus(row.id, newStatus);
  };


  const handleRoleSave = async (roleData: IRole) => {
    try {
      await handleSave(roleData);
      handleCancel(activeTab);
    } catch (error) {
      console.error('Error saving role:', error);
    }
  };

  const handleRoleClose = () => {
    const currentTabData = tabs.find(tab => tab.id === activeTab);
    
    if (currentTabData?.hasUnsavedChanges) {
      setShowConfirmDialog(true);
    } else {
      handleCancel(activeTab);
    }
  };

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.Role}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
        />
      </Stack>

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

      {activeTab === 'list' ? (
        <RoleTable
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleEdit={handleEditRole}
          handleView={handleDetailsRole}
          handleArchive={handleArchiveRole}
          onStatusChange={handleStatusChange}
        />
      ) : (
        <RoleForm
          key={activeTab}
          role={activeTabData?.content as IRole}
          mode={activeTabData?.mode || 'view'}
          onSave={handleRoleSave}
          onClose={() => handleCancel(activeTab, true)}
          onEdit={handleEdit}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}