'use client';

import ActionPopMenu from '@/components/common/ActionPopMenu';
import { MyTable, ColumnData } from '@/components/common/MyTable';
import BaseButton from '@/components/ui-kit/BaseButton';
import BaseIconButton from '@/components/ui-kit/BaseIconButton';
import BaseInput from '@/components/ui-kit/BaseInput';
import BasePagination from '@/components/ui-kit/BasePagination';
import { useAuthContext } from '@/context/auth-context';
import { Customer } from '@/data/customers/customer.model';
import { customer_requests } from '@/data/customers/customer.requests';
import { Party } from '@/data/party/party.model';
import { party_requests } from '@/data/party/party.requests';
import { DEFAULT_PAGE_SIZE, pageLinks } from '@/helpers/constants';
import useInput from '@/hooks/useInput';
import { useMyTranslation } from '@/hooks/useMyTranslation';
import useRequest from '@/hooks/useRequest';
import ClientModal from '@/routes/private/clients/ClientModal';
import CreateClientModal from '@/routes/private/clients/CreateClientModal';
import EditClientModal from '@/routes/private/clients/EditClientModal';
import { file_service } from '@/services/file-service';
import { notifyUnknownError } from '@/services/notification';
import { Add, AddCircleOutline, Circle, Delete, Edit, FilterList, FilterListOff, Search } from '@mui/icons-material';
import { Box, Stack, SvgIcon, Tooltip, Typography } from '@mui/material';
import React, { useCallback, useEffect, useMemo, useState } from 'react';

type Props = {};

const DashboardClientsPage = (props: Props) => {
    const t = useMyTranslation();
    const { isAdmin } = useAuthContext();
    const [page, setPage] = useState(1);
    const [pageSize] = useState(DEFAULT_PAGE_SIZE);
    const { value: keyword, onChange: handleKeyword, setValue: setKeyword } = useInput('');
    const { value: aviaCargoIdValue, onChange: handleAviaCargoIdValue, setValue: setAviaCargoIdValue } = useInput('');
    const { value: autoCargoIdValue, onChange: handleAutoCargoIdValue, setValue: setAutoCargoIdValue } = useInput('');

    const [deleteIds, setDeleteIds] = useState<number[]>([]);
    const [downloadClientLoading, setDownloadClientsLoading] = useState(false);

    const [modal, setModal] = useState<null | 'client' | 'edit_client' | 'create_client'>(null);
    const [modalData, setModalData] = useState<null | Customer>(null);

    const getClientsQuery = useRequest(
        () =>
            customer_requests.getAll({
                page: page,
                cargoId: keyword,
            }),
        {
            selectData(data) {
                return data.data.data;
            },
            dependencies: [page],
        }
    );

    const {
        data: list,
        totalElements,
        totalPages,
    } = useMemo(() => {
        if (getClientsQuery.data?.data) {
            return {
                data: getClientsQuery.data.data,
                totalElements: getClientsQuery.data.totalElements,
                totalPages: getClientsQuery.data.totalPages,
            };
        } else {
            return {
                data: [],
                totalElements: 0,
                totalPages: 0,
            };
        }
    }, [getClientsQuery]);
    const loading = getClientsQuery.loading;

    const handleChange = (newPage: number) => {
        setPage(newPage);
    };

    const onDownloadClientsExcel = async () => {
        if (downloadClientLoading) return;

        try {
            setDownloadClientsLoading(true);
            const response = await customer_requests.downloadClientsExcel();
            const file = new File([response.data], 'Clients.xlsx', { type: response.data.type });
            file_service.download(file);
        } catch (error) {
            notifyUnknownError(error);
        } finally {
            setDownloadClientsLoading(false);
        }
    };

    const onDelete = async (id: number) => {
        if (deleteIds.includes(id)) return;

        if (window.confirm(t('are_you_sure_delete_client_id', { id: id }))) {
            try {
                setDeleteIds(p => [...p, id]);
                await customer_requests.delete({ clientId: id });
                getClientsQuery.refetch();
            } catch (error) {
                notifyUnknownError(error);
            } finally {
                setDeleteIds(prev => prev.filter(i => i !== id));
            }
        }
    };

    const resetFilter = () => {
        setPage(1);
        setKeyword('');
        setAviaCargoIdValue('');
        setAutoCargoIdValue('');
    };

    const openClientModal = useCallback((data: Customer) => {
        setModal('client');
        setModalData(data);
    }, []);

    const closeModal = useCallback(() => {
        setModal(null);
        setModalData(null);
    }, []);

    const onSuccessEdit = useCallback(() => {
        closeModal();
        getClientsQuery.refetch();
    }, []);

    useEffect(() => {
        const timeoutId = setTimeout(() => {
            setPage(1);
            getClientsQuery.refetch();
        }, 350);
        return () => clearTimeout(timeoutId);
    }, [keyword, aviaCargoIdValue, autoCargoIdValue]);

    const columns: ColumnData<Customer>[] = [
        {
            label: t('No'),
            width: 100,
            renderCell(data, rowIndex) {
                return (page - 1) * pageSize + rowIndex + 1;
            },
        },
        {
            dataKey: 'id',
            label: t('id'),
            width: 100,
        },
        {
            dataKey: 'fullName',
            label: t('fullName'),
            width: 300,
        },
        {
            dataKey: 'phone',
            label: t('phone'),
            width: 300,
        },
        {
            dataKey: 'address',
            label: t('address'),
            width: 300,
        },
        {
            dataKey: 'dateOfBirth',
            label: t('date_of_birth'),
            width: 300,
        },
        ...(isAdmin
            ? [
                  {
                      label: '',
                      width: 100,
                      numeric: true,
                      renderCell(data: Customer, rowIndex: number) {
                          return (
                              <ActionPopMenu
                                  buttons={[
                                      {
                                          icon: <Edit sx={{ path: { color: '#3489E4' } }} />,
                                          label: t('edit'),
                                          onClick: () => {
                                              setModal('edit_client');
                                              setModalData(data);
                                          },
                                      },
                                      {
                                          icon: <Delete sx={{ path: { color: '#3489E4' } }} />,
                                          label: t('delete'),
                                          onClick: () => {
                                              onDelete(data.id);
                                          },
                                          dontCloseOnClick: true,
                                          loading: deleteIds.includes(data.id),
                                      },
                                  ]}
                              />
                          );
                      },
                  },
              ]
            : []),
        // ...(isAdmin
        //     ? [
        //           {
        //               label: '',
        //               width: 100,
        //               numeric: true,
        //               renderCell(data: Customer, rowIndex: number) {
        //                   return (
        //                       <BaseButton
        //                           startIcon={<Edit color='success' />}
        //                           onClick={(event: any) => {
        //                               event.stopPropagation();
        //                               setModal('edit_client');
        //                               setModalData(data);
        //                           }}
        //                           sx={{
        //                               color: '#222',
        //                               fontWeight: 400,
        //                               fontSize: '14px',
        //                               whiteSpace: 'nowrap',
        //                               '&:hover': {
        //                                   backgroundColor: '#fff',
        //                               },
        //                           }}
        //                           variant='text'
        //                       >
        //                           {t('edit')}
        //                       </BaseButton>
        //                   );
        //               },
        //           },
        //           {
        //               label: '',
        //               width: 100,
        //               numeric: true,
        //               renderCell(data: Customer, rowIndex: number) {
        //                   return (
        //                       <BaseButton
        //                           loading={deleteIds.includes(data.id)}
        //                           startIcon={<Delete color='error' />}
        //                           onClick={(event: any) => {
        //                               event.stopPropagation();
        //                               onDelete(data.id);
        //                           }}
        //                           sx={{
        //                               color: '#222',
        //                               fontWeight: 400,
        //                               fontSize: '14px',
        //                               whiteSpace: 'nowrap',
        //                               '&:hover': {
        //                                   backgroundColor: '#fff',
        //                               },
        //                           }}
        //                           variant='text'
        //                       >
        //                           {t('delete')}
        //                       </BaseButton>
        //                   );
        //               },
        //           },
        //       ]
        //     : []),
    ];

    return (
        <Box>
            {isAdmin && (
                <Stack direction={'row'} mb={3} spacing={3}>
                    <BaseButton
                        colorVariant='blue'
                        startIcon={<Add />}
                        onClick={() => {
                            setModal('create_client');
                        }}
                    >
                        {t('create_client')}
                    </BaseButton>
                    {isAdmin && (
                        <BaseButton
                            colorVariant='blue'
                            startIcon={<Add />}
                            loading={downloadClientLoading}
                            onClick={onDownloadClientsExcel}
                        >
                            {t('download_all_clients')}
                        </BaseButton>
                    )}
                </Stack>
            )}
            <Box
                width={1}
                mb={3}
                sx={{
                    padding: '28px',
                    borderRadius: '16px',
                    backgroundColor: '#fff',
                }}
            >
                <Stack mb={3.5} direction={'row'} justifyContent={'space-between'} alignItems={'center'}>
                    <Typography
                        sx={{
                            fontSize: '20px',
                            lineHeight: '24px',
                            fontWeight: 600,
                            textTransform: 'capitalize',
                            color: '#000',
                        }}
                    >
                        {t('clients')}
                    </Typography>
                    <Stack direction={'row'} alignItems={'center'} spacing={2}>
                        {/*<BaseInput*/}
                        {/*    InputProps={{*/}
                        {/*        startAdornment: <Search color='primary' />,*/}
                        {/*    }}*/}
                        {/*    value={aviaCargoIdValue}*/}
                        {/*    onChange={handleAviaCargoIdValue}*/}
                        {/*    placeholder={t('avia_cargo_id')}*/}
                        {/*/>*/}
                        {/*<BaseInput*/}
                        {/*    InputProps={{*/}
                        {/*        startAdornment: <Search color='primary' />,*/}
                        {/*    }}*/}
                        {/*    value={autoCargoIdValue}*/}
                        {/*    onChange={handleAutoCargoIdValue}*/}
                        {/*    placeholder={t('auto_cargo_id')}*/}
                        {/*/>*/}
                        <BaseInput
                            InputProps={{
                                startAdornment: <Search color='primary' />,
                            }}
                            value={keyword}
                            onChange={handleKeyword}
                            placeholder={"Kargo ID"}
                        />

                        <BaseButton colorVariant='gray' startIcon={<FilterListOff />} size='small' onClick={resetFilter}>
                            {t('reset_filter')}
                        </BaseButton>
                    </Stack>
                </Stack>
                <Box mb={6}>
                    <MyTable columns={columns} data={list} loading={loading} onClickRow={openClientModal} />
                </Box>
                <Stack direction={'row'} justifyContent={'center'}>
                    <BasePagination page={page} pageSize={pageSize} totalCount={totalElements} onChange={handleChange} />
                </Stack>
            </Box>

            {modal === 'client' && modalData && <ClientModal data={modalData} onClose={closeModal} />}
            {modal === 'edit_client' && modalData && <EditClientModal data={modalData} onClose={closeModal} onSuccess={onSuccessEdit} />}
            {modal === 'create_client' && <CreateClientModal onClose={closeModal} onSuccess={onSuccessEdit} />}
        </Box>
    );
};

export default DashboardClientsPage;
