import React, {
    createRef,
    forwardRef,
    useEffect,
    useImperativeHandle,
    useState,
} from 'react';

import { XIcon } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
    MobileBlock,
    MobileButton,
    MobileLink,
    MobileList,
    MobileSheet,
    MobileToolbar,
    MobileToolbarPane,
} from '@/components/ui/mobile';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import { confirmAlertRef } from '@/componentsRoot/ConfirmAlert';
import { toast } from '@/componentsRoot/ToastRoot';
import { useProfileSocials } from '@/hooks/useProfileSocials';
import { Lang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';
import { useMainPage } from '@/stores/mainPage';
import {
    findSocialByType,
    getSocialDisplayLabel,
    linkSocialAccount,
    SOCIAL_NETWORK_TYPES,
    type SocialNetworkType,
    unlinkSocialAccount,
} from '@/utils/socialAuth';

import LinkedSocialNetworkRow from './components/LinkedSocialNetworkRow';

type LinkedSocialNetworksDialogRefProps = {
    open: () => void;
    close: () => void;
};

export const linkedSocialNetworksDialogRef = createRef<LinkedSocialNetworksDialogRefProps>();

const LinkedSocialNetworksDialog = forwardRef<LinkedSocialNetworksDialogRefProps>((_, ref) => {
    const { isMobile } = useAppConfigStore();
    const { loadProfile } = useMainPage();
    const [open, setOpen] = useState(false);
    const { socials, reloadSocials } = useProfileSocials();

    useImperativeHandle(ref, () => ({
        open: () => setOpen(true),
        close: () => setOpen(false),
    }));

    useEffect(() => {
        if (open) {
            reloadSocials();
        }
    }, [open, reloadSocials]);

    const handleLinkSocial = async (type: SocialNetworkType) => {
        setOpen(false);
        const success = await linkSocialAccount(type);
        if (success) {
            toast.success(Lang.key('social_linked_successfully'));
            await reloadSocials();
            loadProfile();
        }
    };

    const confirmUnlinkSocial = (type: SocialNetworkType) => {
        const social = findSocialByType(socials, type);
        if (!social?._id) return;

        const networkName = Lang.key('social_' + type);
        const email = getSocialDisplayLabel(social);

        confirmAlertRef.current?.open({
            title: Lang.key('unlink_social_title'),
            description: Lang.key('unlink_social_description')
                .replace('{network}', networkName)
                .replace('{email}', email),
            buttons: [
                { label: Lang.key('cancel'), onClick: () => { } },
                {
                    label: Lang.key('yes'),
                    onClick: async () => {
                        const success = await unlinkSocialAccount(String(social._id));
                        if (success) {
                            toast.success(Lang.key('social_unlinked_successfully'));
                            await reloadSocials();
                            loadProfile();
                        }
                    },
                },
            ],
        });
    };

    const list = SOCIAL_NETWORK_TYPES.map((type) => (
        <LinkedSocialNetworkRow
            key={type}
            type={type}
            social={findSocialByType(socials, type)}
            isMobile={isMobile}
            onLink={() => handleLinkSocial(type)}
            onUnlink={() => confirmUnlinkSocial(type)}
        />
    ));

    if (isMobile) {
        return (
            <MobileSheet opened={open} onBackdropClick={() => setOpen(false)}>
                <div className="max-h-[80vh] overflow-y-auto pb-safe">
                    <MobileToolbar top className="justify-between ios:pt-4 sticky top-0 z-10 bg-background">
                        <span className="text-base font-medium px-4">
                            {Lang.key('linked_social_media_accounts')}
                        </span>
                        <MobileToolbarPane>
                            <MobileLink iconOnly onClick={() => setOpen(false)}>
                                <XIcon />
                            </MobileLink>
                        </MobileToolbarPane>
                    </MobileToolbar>
                    <MobileList outline className="my-2">
                        {list}
                    </MobileList>
                    <MobileBlock outline>
                        <MobileButton onClick={() => setOpen(false)}>
                            {Lang.key('close')}
                        </MobileButton>
                    </MobileBlock>
                </div>
            </MobileSheet>
        );
    }

    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={Lang.key('linked_social_media_accounts')}
            width={448}
            height="auto"
            footer={
                <Button onClick={() => setOpen(false)} variant="outline">
                    {Lang.key('close')}
                </Button>
            }
        >

            <div className="divide-y">{list}</div>
        </SystemWindowDialog>
    );
});

export default LinkedSocialNetworksDialog;
