import { ActionIcon, Group, Loader, ScrollArea, Stack, Table, Title, Tooltip } from "@mantine/core";
import { t } from "@/config/i18n";
import { createShipment, editShipment, getShipment, getShipments } from "@/services/api";
import { IconPlus } from "@tabler/icons-react";
import ShipmentRow from "@/components/Shipments/Row";
import { useLocation, useNavigate, useSearchParams } from "react-router";
import { useCallback, useMemo } from "react";
import { shipmentCreateFromShipmentInputs, type Shipment, type ShipmentInputs } from "@/services/resources/shipments";
import ShipmentModal from "@/components/Shipments/Modal";
import ShipmentsFilters from "@/components/Shipments/Filter";

export default function Shipments() {
    const [ searchParams, setSearchParams ] = useSearchParams();
    const location = useLocation();
    const navigate = useNavigate();

    const isCreate = location.pathname === "/dashboard/shipments/create";
    const isEdit = location.pathname.includes("/edit");

    const editId = useMemo(() => {
        if (isEdit) {
            return location.pathname.split("/")[3]
        }
        return null
    }, [location, isEdit])
    
    const closeModal = () => {
        navigate("/dashboard/shipments");
    };

    const { data: shipments, isPending } = getShipments(searchParams);
    const { data: currentShipment } = getShipment(Number(editId), { enabled: !!editId });
    const { data: allShipments } = getShipments();

    const names = useMemo(() => {
        return allShipments?.map((shipment: Shipment) => (shipment.name))
            .filter((season, index, array) => array.indexOf(season) === index)
    }, [allShipments])

    const createShipmentMutation = createShipment();
    const editShipmentMutation = editShipment();

    const handleCreateShipment = useCallback(async (shipment: ShipmentInputs) => {
        await createShipmentMutation.mutateAsync(shipmentCreateFromShipmentInputs(shipment));
        closeModal();
    }, [createShipmentMutation]);

    const handleEditShipment = useCallback(async (shipment: ShipmentInputs, id?: number) => {
        if (!id)
            return;
        await editShipmentMutation.mutateAsync({
            id: id,
            shipment: shipmentCreateFromShipmentInputs(shipment)
        });
        closeModal();
    }, []);
    
    const onFilterChange = useCallback((values: string[], filter: string) => {
        setSearchParams(prev => {
            const params = new URLSearchParams(prev);
            params.delete(filter)
            
            values.forEach(value => {
                params.append(filter, value);
            });
            return params;
        });
    }, [searchParams, setSearchParams])

    if (!shipments || isPending)
        return <Loader/>

    return (
        <Stack>
            <Group justify="space-between">
                <Title order={2}>{t("all shipments", {capfirst: true})}</Title>
                <Tooltip label={t("create shipment", {capfirst: true})}>
                    <ActionIcon
                        onClick={(e) => {
                            e.stopPropagation();
                            navigate(`/dashboard/shipments/create`);
                        }}
                    >
                        <IconPlus/>
                    </ActionIcon>
                </Tooltip>
                <ShipmentModal
                    opened={isCreate} 
                    onClose={closeModal} 
                    handleSubmit={handleCreateShipment}
                />
                <ShipmentModal
                    opened={isEdit}
                    onClose={closeModal}
                    currentShipment={currentShipment}
                    handleSubmit={handleEditShipment}
                />
            </Group>
            <ShipmentsFilters
                names={names || []}
                filters={searchParams}
                onFilterChange={onFilterChange}
            />
            <ScrollArea type="auto">
                <Table striped>
                    <Table.Thead>
                        <Table.Tr>
                            <Table.Th>{t("name", {capfirst: true})}</Table.Th>
                            <Table.Th>{t("date", {capfirst: true})}</Table.Th>
                            <Table.Th>{t("formulare", {capfirst: true})}</Table.Th>
                            <Table.Th>{t("actions", {capfirst: true})}</Table.Th>
                        </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>
                        {
                            shipments.map((shipment) => (
                                <ShipmentRow 
                                    shipment={shipment}
                                    key={shipment.id}
                                />
                            ))
                        }
                    </Table.Tbody>
                </Table>
            </ScrollArea>
        </Stack>
    );
}