import {t} from "@lingui/macro";
import {Badge, Button, Group, Table as MantineTable, Text} from '@mantine/core';
import {IdParam} from "../../../types.ts";
import {IconCopy, IconCurrencyDollar, IconPencil, IconPlus, IconShare, IconTrash, IconUsers} from "@tabler/icons-react";
import {useClipboard, useDisclosure} from "@mantine/hooks";
import {useState} from "react";
import {NoResultsSplash} from "../NoResultsSplash";
import {EditAffiliateModal} from "../../modals/EditAffiliateModal";
import {ShareModal} from "../../modals/ShareModal";
import {useDeleteAffiliate} from "../../../mutations/useDeleteAffiliate";
import {showError, showSuccess} from "../../../utilites/notifications.tsx";
import {confirmationDialog} from "../../../utilites/confirmationDialog.tsx";
import {useParams} from "react-router";
import {Affiliate} from "../../../api/affiliate.client.ts";
import classes from "./AffiliateTable.module.scss";
import {Table, TableHead} from "../Table";
import {ActionMenu} from "../ActionMenu";
import {eventHomepageUrl} from "../../../utilites/urlHelper.ts";
import {useGetEvent} from "../../../queries/useGetEvent.ts";

interface AffiliateTableProps {
    affiliates: Affiliate[];
    openCreateModal: () => void;
}

export const AffiliateTable = ({affiliates, openCreateModal}: AffiliateTableProps) => {
    const [editModalOpen, {open: openEditModal, close: closeEditModal}] = useDisclosure(false);
    const [shareModalOpen, {open: openShareModal, close: closeShareModal}] = useDisclosure(false);
    const [selectedAffiliateId, setSelectedAffiliateId] = useState<IdParam>();
    const [selectedAffiliate, setSelectedAffiliate] = useState<Affiliate>();
    const deleteMutation = useDeleteAffiliate();
    const {eventId} = useParams();
    const copy = useClipboard()
    const {data: event} = useGetEvent(eventId);

    const handleDeleteAffiliate = (affiliateId: IdParam, eventId: IdParam) => {
        deleteMutation.mutate({affiliateId, eventId}, {
            onSuccess: () => {
                showSuccess(t`Affiliate deleted successfully`);
            },
            onError: (error: any) => {
                showError(error.message);
            }
        });
    }

    const copyToClipboard = (text: string) => {
        copy.copy(text)
        showSuccess(t`Copied to clipboard`);
    };

    if (affiliates.length === 0) {
        return (
            <NoResultsSplash
                heading={t`No Affiliates to show`}
                imageHref={'/blank-slate/affiliates.png'}
                subHeading={(
                    <>
                        <p>
                            {t`Affiliates help you track sales generated by partners and influencers. Create affiliate codes and share them to monitor performance.`}
                        </p>
                        <Button
                            size={'xs'}
                            leftSection={<IconPlus/>}
                            color={'green'}
                            onClick={openCreateModal}
                        >
                            {t`Create Affiliate`}
                        </Button>
                    </>
                )}
            />
        );
    }

    return (
        <>
            <Table>
                <TableHead>
                    <MantineTable.Tr>
                        <MantineTable.Th miw={200}>{t`Code`}</MantineTable.Th>
                        <MantineTable.Th>{t`Affiliate`}</MantineTable.Th>
                        <MantineTable.Th miw={120}>{t`Status`}</MantineTable.Th>
                        <MantineTable.Th miw={250}>{t`Performance`}</MantineTable.Th>
                        <MantineTable.Th w={50}></MantineTable.Th>
                    </MantineTable.Tr>
                </TableHead>
                <MantineTable.Tbody>
                    {affiliates.map((affiliate) => (
                        <MantineTable.Tr key={affiliate.id}>

                            <MantineTable.Td>
                                <div className={classes.codeCell}>
                                    <div className={classes.codeWrapper}>
                                        <Text ff="monospace" size="sm" className={classes.codeText}>
                                            {affiliate.code}
                                        </Text>
                                        <Button
                                            size="xs"
                                            variant="subtle"
                                            color="gray"
                                            leftSection={<IconCopy size={12}/>}
                                            onClick={() => copyToClipboard(eventHomepageUrl(event!) + `?aff=${affiliate.code}`)}
                                            className={classes.copyButton}
                                        >
                                            {t`Copy URL`}
                                        </Button>
                                    </div>
                                </div>
                            </MantineTable.Td>
                            <MantineTable.Td>
                                <div className={classes.affiliateInfo}>
                                    <Text className={classes.affiliateName} size="sm">
                                        {affiliate.name}
                                    </Text>
                                    {affiliate.email && (
                                        <Text className={classes.affiliateEmail}>
                                            {affiliate.email}
                                        </Text>
                                    )}
                                </div>
                            </MantineTable.Td>

                            <MantineTable.Td>
                                <Badge
                                    color={affiliate.status === 'ACTIVE' ? 'green' : 'gray'}
                                    variant={affiliate.status === 'ACTIVE' ? 'light' : 'outline'}
                                    size="sm"
                                    radius="md"
                                >
                                    {affiliate.status === 'ACTIVE' ? t`Active` : t`Inactive`}
                                </Badge>
                            </MantineTable.Td>

                            <MantineTable.Td>
                                <div className={classes.statsCell}>
                                    <div className={classes.statItem}>
                                        <Group gap={4} align="center">
                                            <IconUsers size={12} className={classes.statIcon}/>
                                            <Text className={classes.statValue}>
                                                {affiliate.total_sales}
                                            </Text>
                                        </Group>
                                        <Text className={classes.statLabel}>
                                            {t`Sales`}
                                        </Text>
                                    </div>

                                    <div className={classes.statItem}>
                                        <Group gap={4} align="center">
                                            <IconCurrencyDollar size={12} className={classes.statIcon}/>
                                            <Text className={classes.statValue}>
                                                ${affiliate.total_sales_gross.toFixed(2)}
                                            </Text>
                                        </Group>
                                        <Text className={classes.statLabel}>
                                            {t`Revenue`}
                                        </Text>
                                    </div>
                                </div>
                            </MantineTable.Td>

                            <MantineTable.Td>
                                <ActionMenu
                                    itemsGroups={[
                                        {
                                            label: t`Actions`,
                                            items: [
                                                {
                                                    label: t`Edit Affiliate`,
                                                    icon: <IconPencil size={14}/>,
                                                    onClick: () => {
                                                        setSelectedAffiliateId(affiliate.id);
                                                        openEditModal();
                                                    }
                                                },
                                                {
                                                    label: t`Copy Code`,
                                                    icon: <IconCopy size={14}/>,
                                                    onClick: () => copyToClipboard(affiliate.code)
                                                },
                                                {
                                                    label: t`Copy Affiliate Link`,
                                                    icon: <IconCopy size={14}/>,
                                                    onClick: () => copyToClipboard(
                                                        eventHomepageUrl(event!) + `?aff=${affiliate.code}`
                                                    )
                                                },
                                                {
                                                    label: t`Share Affiliate Link`,
                                                    icon: <IconShare size={14}/>,
                                                    onClick: () => {
                                                        setSelectedAffiliate(affiliate);
                                                        openShareModal();
                                                    }
                                                },
                                                {
                                                    label: t`Delete Affiliate`,
                                                    icon: <IconTrash size={14}/>,
                                                    color: "red",
                                                    onClick: () => confirmationDialog(
                                                        t`Are you sure you want to delete this affiliate? This action cannot be undone.`,
                                                        () => handleDeleteAffiliate(affiliate.id, eventId!)
                                                    )
                                                }
                                            ]
                                        }
                                    ]}
                                />
                            </MantineTable.Td>
                        </MantineTable.Tr>
                    ))}
                </MantineTable.Tbody>
            </Table>

            {editModalOpen && selectedAffiliateId && (
                <EditAffiliateModal
                    affiliateId={selectedAffiliateId}
                    onClose={closeEditModal}
                />
            )}

            {shareModalOpen && selectedAffiliate && event && (
                <ShareModal
                    opened={shareModalOpen}
                    onClose={closeShareModal}
                    url={eventHomepageUrl(event) + `?aff=${selectedAffiliate.code}`}
                    title={event.title}
                    modalTitle={t`Share Affiliate Link`}
                    shareText={t`Here is your affiliate link`}
                />
            )}
        </>
    );
};
