'use client';

import React, { useMemo } from 'react';
import { Box, Stack } from '@mui/material';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useAgentTable } from '../hooks/use-agent-table';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import AgentTable from '../components/agent-table';
import { AddressData, TableType } from '@/shared/types/common';
import { useAgentTabs } from '../hooks/use-agent-tabs';
import AgentForm from './agent-new-view';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import {
  AddressDTO,
  AddressType,
  CollaboratorExportFilterRequest,
  CollaboratorStatus,
  IAgent,
  MapAddresse,
} from '@/shared/types/client';
import { useCollaboratorStore } from '@/shared/api/stores/CollaboratorStore';
import { enqueueSnackbar } from 'notistack';
import { _AGENT_STATUS } from '@/shared/_mock/_agent';
import { SelectChangeEvent } from '@mui/material';

export default function AgentContent() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useAgentTabs();

  const {
    collaborators,
    loading,
    error,
    addCollaborator,
    updateCollaborator,
    searchCollaborators,
    exportCollaborators,
    changeStatus,
  } = useCollaboratorStore();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
  } = useAgentTable(collaborators?.content || []);

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

  const [params, setParams] = React.useState<{
    page: number;
    size: number;
    sortBy: string;
    sortDirection: 'asc' | 'desc';
  }>({
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'asc',
  });

  React.useEffect(() => {
    const newParams = {
      page: table.page,
      size: table.rowsPerPage,
      sortBy: table.orderBy === 'status' ? 'collaboratorStatus' : table.orderBy,
      sortDirection: table.order.toLowerCase() as 'asc' | 'desc',
    };
    const filterParams: Record<string, string> = {};
    Object.entries(filters).forEach(([key, { value }]) => {
      if (value) {
        if (key === 'status') {
          const statusValue = _AGENT_STATUS.find((item) => item.label === value)?.value;
          if (statusValue) {
            filterParams[key] = statusValue;
          }
        } else {
          filterParams[key] = value;
        }
      }
    });
    setParams({ ...newParams, ...filterParams });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

  React.useEffect(() => {
    if (filters.status?.value) {
      const statusValue = _AGENT_STATUS.find((item) => item.label === filters.status.value)?.value;
      if (!statusValue) {
        return;
      }
    }
    const sortBy = table.orderBy === 'status' ? 'CollaboratorStatus' : table.orderBy;

    searchCollaborators(params);
  }, [params]);

  const handlePageChange = (event: unknown, newPage: number) => {
    table.onChangePage(event, newPage);
  };

  const handleRowsPerPageChange = (event: SelectChangeEvent<number>) => {
    table.onChangeRowsPerPage(event);
  };

const getFormatedAddress = (mapAdresse: AddressData, adresseId: string): AddressDTO => {
  const street = mapAdresse.address.split(',')[0].trim();
  const city = mapAdresse.city || '';
  const postalCode = mapAdresse.postalCode || '';
  const country = mapAdresse.country || '';
  const additionalAddress = mapAdresse.formattedAddress || '';
  return {
    id: adresseId,
    createdAt: '',
    updatedAt: '',
    street, 
    city,
    country, 
    zipCode: postalCode, 
    latitude: mapAdresse.lat as number, 
    longitude: mapAdresse.lng as number , 
    addressType: AddressType.COLLABORATOR,
    additionalAddress: additionalAddress || undefined,
  };
};
const handleUpdateAgent = async (agent: IAgent) => {
  try {
    const addressId = agent?.addresses?.[0]?.id ?? '0';

    const processedAgent: IAgent = {
      ...agent,
      teams: agent.teams ?? [],
      addresses:
        (agent.addresses == null || agent.addresses.length === 0) && agent.mapAdresse
          ? [getFormatedAddress(agent.mapAdresse, addressId)]
          : agent.addresses ?? [],
      schedule: agent.schedule, // Inclure l'emploi du temps
    };
    
    
    await updateCollaborator(processedAgent);
    enqueueSnackbar('Agent mis à jour avec succès!', { variant: 'success' });
  } catch (error) {
    enqueueSnackbar("Erreur lors de la mise à jour de l'agent.", { variant: 'error' });
    console.error('Erreur handleUpdateAgent:', error);
  }
};

const handleExport = async () => {
  try {
    const simpleFilters = Object.fromEntries(
      Object.entries(filters).map(([key, { value }]) => [key, value])
    );

    await exportCollaborators(simpleFilters as CollaboratorExportFilterRequest);
    if (error == null) {
      enqueueSnackbar('Export Collaborateur est lancer avec succès!', { variant: 'success' });
    } else {
      enqueueSnackbar("Erreur lors de l'exportation des collaborateurs.", { variant: 'error' });
    }
  } catch (error) {
    enqueueSnackbar("Erreur lors de l'exportation des collaborateurs.", { variant: 'error' });

    console.error("Erreur lors de l'exportation des collaborateurs :", error);
  }
};
const exportOptions = useMemo(
  () => [
    {
      label: 'Exporter en CSV',
      action: () => handleExport(),
    },
  ],
  [handleExport]
);

const handleSaveAgent = async (agent: IAgent) => {
  try {
    const isAddMode = activeTabData?.mode === 'add';
    const statusEnumName = Object.keys(CollaboratorStatus).find(
      (key) => CollaboratorStatus[key as keyof typeof CollaboratorStatus] === agent.collaboratorStatus
    ) || 'APPROVED';
    
    const processedAgent: IAgent = {
      ...agent,
      id: '0',
      agencyId: isAddMode ? Number(agent.agencyName) : agent.agencyId,
      agencyName: isAddMode ? '' : agent.agencyName,
      departmentId: isAddMode ? Number(agent.departmentName) : agent.departmentId,
      departmentName: isAddMode ? '' : agent.departmentName,
      roles: (agent.roles || []).map((r: any) => ({
        id: r.id,
        name: r.name,
        description: r.description ?? '',
        permissions: [],
      })),
      teams: agent.teams || [],
      addresses: agent.mapAdresse?.address ? [getFormatedAddress(agent.mapAdresse, '0')] : [],
      collaboratorStatus: isAddMode ? statusEnumName as CollaboratorStatus : agent.collaboratorStatus,
      schedule: agent.schedule ? { 
        ...agent.schedule, 
        id: null, 
        collaboratorId: null,
        createdAt: null,
        updatedAt: null,
        weeklySchedule: {
          ...agent.schedule.weeklySchedule,
          id: null,
          createdAt: null,
          updatedAt: null,
          monday: { ...agent.schedule.weeklySchedule.monday, id: null, createdAt: null, updatedAt: null },
          tuesday: { ...agent.schedule.weeklySchedule.tuesday, id: null, createdAt: null, updatedAt: null },
          wednesday: { ...agent.schedule.weeklySchedule.wednesday, id: null, createdAt: null, updatedAt: null },
          thursday: { ...agent.schedule.weeklySchedule.thursday, id: null, createdAt: null, updatedAt: null },
          friday: { ...agent.schedule.weeklySchedule.friday, id: null, createdAt: null, updatedAt: null },
          saturday: { ...agent.schedule.weeklySchedule.saturday, id: null, createdAt: null, updatedAt: null },
          sunday: { ...agent.schedule.weeklySchedule.sunday, id: null, createdAt: null, updatedAt: null },
        }
      } : undefined,
    };

    await addCollaborator(processedAgent);
    enqueueSnackbar('Agent ajouté avec succès!', { variant: 'success' });
  } catch (error) {
    enqueueSnackbar("Erreur lors de la sauvegarde de l'agent.", { variant: 'error' });
    console.error('Erreur handleSaveAgent:', error);
  }
};


  const handleCollaboratorSave = async (agent: IAgent) => {
    try {
      if (activeTabData?.mode === 'add' || activeTabData?.mode === 'copy') {
        await handleSaveAgent(agent);
       
      } else if (activeTabData?.mode === 'edit') {
        await handleUpdateAgent(agent);
      }
    } catch (error) {
      enqueueSnackbar('Une erreur est survenue.', { variant: 'error' });
      console.error("Erreur lors du traitement de l'agent:", error);
    }
  };

  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.Agent}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          handleTabAdd={handleTabAdd}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

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

      {activeTab === 'list' ? (
        <AgentTable
          filteredData={collaborators?.content || []}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleView={handleView}
          onStatusChange={handleStatusChange}
          loading={loading}
          page={params.page}
          onPageChange={handlePageChange}
          onRowsPerPageChange={handleRowsPerPageChange}
          rowsPerPage={params.size}
          count={collaborators?.totalElements || 0}
          sortBy={params.sortBy}
          sortDirection={params.sortDirection}
        />
      ) : (
        <AgentForm
          key={activeTab}
          agent={activeTabData?.content as IAgent}
          mode={activeTabData?.mode || 'add'}
          onSave={handleCollaboratorSave}
          onClose={(force) => handleCancel(activeTab, force)}
          onEdit={handleEdit}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
