'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Box, SelectChangeEvent, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useClientTabs } from '../hooks/use-client-tabs';
import { useClientTable } from '../hooks/use-client-table';
import ClientTabs from '../../../components/tabs/tabs-custom';
import { AddressData, TableType } from '@/shared/types/common';

import { AddressDTO, AddressType, ClientPageFilterParams, IClient } from '@/shared/types/client';
import TableManager from '@/shared/components/table/table-manager';
import ClientTableRow from './client-table-row';
import ClientForm from './client-new-view';
import { useClientStore } from '@/shared/api/stores/userStore';
import { enqueueSnackbar } from 'notistack';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

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

  const { clients, loading, error, addClient, updateClient, getAllClients, exportClients } =
    useClientStore();

  const [params, setParams] = useState<ClientPageFilterParams>({
    page: 0,
    size: 10,
    sortBy: 'id',
    sortDirection: 'desc',
  });

  const {
    table,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    dataToExport,
  } = useClientTable(clients?.content || []);

  useEffect(() => {
    const newParams: ClientPageFilterParams = {
      page: table.page,
      size: table.rowsPerPage,
      sortBy: table.orderBy,
      sortDirection: table.order.toLowerCase() as 'asc' | 'desc',
    };

    const filterParams: Record<string, string> = {};
    Object.entries(filters).forEach(([key, { value }]) => {
      if (value) {
        filterParams[key] = value;
      }
    });

    setParams({ ...newParams, ...filterParams });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

  useEffect(() => {
    getAllClients(params);
  }, [params]);

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

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

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

  const renderRow = (row: IClient) => (
    <ClientTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleCopy={handleCopy}
      handleEdit={handleEdit}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  );
  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, // Rue extraite
      city, // Ville provenant de mapAdresse
      country, // Pays provenant de mapAdresse
      zipCode: postalCode, // Code postal provenant de mapAdresse
      latitude: mapAdresse.lat as number, // Latitude
      longitude: mapAdresse.lng as number , // Longitude
      addressType: AddressType.CLIENT,
      additionalAddress: additionalAddress || undefined, // Adresse complémentaire
    };
  };

  const handleSave = async (client: IClient) => {
    try {
      const processedClient: IClient = {
        ...client,
        id: '0',
        clientType: {
          id:
            typeof client.clientType === 'string'
              ? client.clientType
              : (client.clientType?.id ?? '0'),
          name: '',
        },
        roles: [
          {
            id: '0',
            name: 'CLIENT_DO',
            description: '',
          },
        ],
        agency_id: activeTabData?.mode === 'copy' ? client.agency_id : Number(client.agencyName),
        agencyName: client.agencyName,
        addresses: client.mapAdresse?.address ? [getFormatedAddress(client.mapAdresse, '0')] : [],
      };
      await addClient(processedClient);
      if (error == null) {
        enqueueSnackbar('Client ajouté avec succès!', { variant: 'success' });
      } else {
        enqueueSnackbar('Client ajouté avec succès!');
      }
    } catch (error) {
      enqueueSnackbar("Erreur lors de l'ajout du client.", { variant: 'error' });
      console.error('Erreur lors de la sauvegarde du client : ', error);
    }
  };
  const handlleUpdate = async (client: IClient) => {
    try {
      const addressId = client?.addresses?.[0]?.id ?? '0';
      console.log(addressId);
      const processedClient: IClient = {
        ...client,
        clientType: {
          id:
            typeof client.clientType === 'string'
              ? client.clientType
              : (client.clientType?.id ?? '0'),
          name: String(client.clientType?.name ?? ''),
        },
        roles: [
          {
            id: client.roles[0].id,
            name: client.roles[0].name,
            description: client.roles[0].description,
          },
        ],
        agency_id: Number(client.agency_id),
        agencyName: client.agencyName,
        addresses:
          client.mapAdresse?.address && client.addresses?.length
            ? [getFormatedAddress(client.mapAdresse, addressId)]
            : [],
      };

      await updateClient(processedClient);
      if (error == null) {
        enqueueSnackbar('Client mis à jour avec succès!', { variant: 'success' }); // Message de succès
      } else {
        enqueueSnackbar('Erreur lors de la mise à jour du client.', { variant: 'error' }); // Message d'erreur
      }
    } catch (error) {
      enqueueSnackbar('Erreur lors de la mise à jour du client.', { variant: 'error' }); // Message d'erreur

      console.error('Erreur lors de la mise à jour du client :', error);
    }
  };
  const handleClient = async (client: IClient) => {
    try {
      if (activeTabData?.mode === 'add' || activeTabData?.mode === 'copy') {
        await handleSave(client);
      } else if (activeTabData?.mode === 'edit') {
        await handlleUpdate(client);
      }
    } catch (error) {
      console.error('Erreur lors du traitement du client :', error);
    }
  };

  const handleExport = async () => {
    try {
      const userIdString = localStorage.getItem('userId');
      if (userIdString) {
        const userId = Number(userIdString); 
        await exportClients({ ...params, userId });
        if (error == null) {
          enqueueSnackbar('Export Client est lancer avec succès!', { variant: 'success' });
        } else {
          enqueueSnackbar("Erreur lors de l'exportation des clients.", { variant: 'error' });
        }
      }
    } catch (error) {
      enqueueSnackbar("Erreur lors de l'exportation des clients.", { variant: 'error' });

      console.error("Erreur lors de l'exportation des clients :", error);
    }
  };
  const handleExportError = useCallback((error: Error) => {
    enqueueSnackbar("Erreur lors de l'export:", { variant: 'error' });
  }, []);

  const exportOptions = useMemo(
    () => [
      {
        label: 'Exporter en CSV',
        action: () => handleExport(),
      },
    ],
    [handleExport]
  );
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
        position: 'relative',
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.Client}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      <ClientTabs
        type={TableType.Client}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <TableManager
          filteredData={clients?.content || []}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          page={params.page}
          onRowsPerPageChange={handleRowsPerPageChange}
          onPageChange={handlePageChange}
          rowsPerPage={params.size}
          count={clients?.totalElements || 0}
          sortBy={params.sortBy}
          sortDirection={params.sortDirection}
          loading={loading}
        />
      ) : (
        <ClientForm
          key={activeTabData?.id}
          client={activeTabData?.content as IClient}
          mode={activeTabData?.mode || 'view'}
          onSave={handleClient}
          onClose={(forceClose) => handleCancel(activeTab, forceClose)}
          onEdit={handleEdit}
          tableHead={tableHead.slice(0, -1)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
