"use client";

import {
    useMemo,
    useState,
    type ReactNode,
} from "react";

import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import LinearProgress from "@mui/material/LinearProgress";
import Snackbar from "@mui/material/Snackbar";
import Typography from "@mui/material/Typography";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { useCurrentUser } from "@/features/auth/hook/use-current-user";

import { useNotificationSetting } from "../hook/use-notification-setting";
import { notificationSettingTranslations } from "../notification-setting-i18n";
import { NotificationSettingCard } from "./notification-setting-card";
import { NotificationSettingIcon } from "./notification-setting-icons";
import { NotificationSettingRow } from "./notification-setting-row";

type NotificationTab = "system" | "gmail";

type SnackbarState = {
    open: boolean;
    message: string;
    severity: "success" | "error" | "info";
};

function CircleIcon({
    children,
    color = "#3478DC",
    background = "#EDF5FF",
}: {
    children: ReactNode;
    color?: string;
    background?: string;
}) {
    return (
        <Box
            sx={{
                width: 36,
                height: 36,
                flexShrink: 0,
                display: "grid",
                placeItems: "center",
                color,
                bgcolor: background,
                borderRadius: "50%",
            }}
        >
            {children}
        </Box>
    );
}

export function NotificationSettingScreen() {
    const { language } = useAppLanguage();

    const {
        user,
        isLoading: userLoading,
    } = useCurrentUser();

    const t =
        notificationSettingTranslations[language] ??
        notificationSettingTranslations.en;

    const isKhmer = language === "kh";

    const fontFamily = isKhmer
        ? '"Battambang", "Kantumruy Pro", sans-serif'
        : '"Inter", "Segoe UI", Arial, sans-serif';

    const loggedInEmail =
        user?.email?.trim().toLowerCase() ?? "";

    const {
        settings,
        loading,
        saving,
        error,
        lastUpdated,
        saveSettings,
        updateSystemEnabled,
        updateUnreadBadge,
        updateGmailEnabled,
    } = useNotificationSetting();

    const [activeTab, setActiveTab] =
        useState<NotificationTab>("system");

    const [snackbar, setSnackbar] =
        useState<SnackbarState>({
            open: false,
            message: "",
            severity: "success",
        });

    const formattedLastUpdated = useMemo(() => {
        if (!lastUpdated) {
            return "-";
        }

        const date = new Date(lastUpdated);

        if (Number.isNaN(date.getTime())) {
            return lastUpdated;
        }

        return new Intl.DateTimeFormat(
            isKhmer ? "km-KH" : "en-GB",
            {
                day: "2-digit",
                month: "2-digit",
                year: "numeric",
                hour: "2-digit",
                minute: "2-digit",
                hour12: true,
            },
        ).format(date);
    }, [isKhmer, lastUpdated]);

    const pageLoading =
        loading || userLoading;

    function showMessage(
        message: string,
        severity: SnackbarState["severity"],
    ) {
        setSnackbar({
            open: true,
            message,
            severity,
        });
    }

    function closeSnackbar() {
        setSnackbar((current) => ({
            ...current,
            open: false,
        }));
    }

    function handleTabChange(
        tab: NotificationTab,
    ) {
        setActiveTab(tab);

        window.requestAnimationFrame(() => {
            document
                .getElementById(
                    "notification-setting-cards",
                )
                ?.scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                });
        });
    }

    async function handleSaveSettings() {
        if (
            settings.gmail.enabled &&
            !loggedInEmail
        ) {
            setActiveTab("gmail");

            showMessage(
                isKhmer
                    ? "រកមិនឃើញអ៊ីមែលរបស់អ្នកប្រើប្រាស់ដែលបានចូលប្រើ។"
                    : "Logged-in user email was not found.",
                "error",
            );

            return;
        }

        const result = await saveSettings(
            loggedInEmail,
        );

        if (result.success) {
            showMessage(
                t.settingsSaved,
                "success",
            );

            return;
        }

        showMessage(
            result.message ??
            t.settingsSaveFailed,
            "error",
        );
    }

    const systemNotificationCard = (
        <Box
            key="system-notification"
            sx={{
                scrollMarginTop: 90,
            }}
        >
            <NotificationSettingCard
                title={t.systemTitle}
                description={t.systemDescription}
                disabled={pageLoading || saving}
                language={language}
                titleFontSizeOffset={2}
            >
                <Box
                    sx={{
                        p: {
                            xs: 1.5,
                            sm: 2,
                        },
                    }}
                >
                    <Box
                        sx={{
                            overflow: "hidden",
                            border: "1px solid",
                            borderColor: "divider",
                            borderRadius: 1.5,
                        }}
                    >
                        <NotificationSettingRow
                            language={language}
                            titleFontSizeOffset={1}
                            icon={
                                <CircleIcon>
                                    <NotificationSettingIcon
                                        name="bell"
                                        size={18}
                                    />
                                </CircleIcon>
                            }
                            title={t.enableSystemTitle}
                            description={
                                t.enableSystemDescription
                            }
                            checked={
                                settings.system.enabled
                            }
                            disabled={
                                pageLoading || saving
                            }
                            onChange={
                                updateSystemEnabled
                            }
                        />

                        <NotificationSettingRow
                            language={language}
                            titleFontSizeOffset={1}
                            icon={
                                <CircleIcon>
                                    <NotificationSettingIcon
                                        name="badge"
                                        size={18}
                                    />
                                </CircleIcon>
                            }
                            title={t.unreadBadgeTitle}
                            description={
                                t.unreadBadgeDescription
                            }
                            checked={
                                settings.system.unreadBadge
                            }
                            disabled={
                                pageLoading ||
                                saving ||
                                !settings.system.enabled
                            }
                            onChange={
                                updateUnreadBadge
                            }
                        />
                    </Box>
                </Box>
            </NotificationSettingCard>
        </Box>
    );

    const gmailNotificationCard = (
        <Box
            key="gmail-notification"
            sx={{
                scrollMarginTop: 90,
            }}
        >
            <NotificationSettingCard
                title={t.gmailTitle}
                description={t.gmailDescription}
                disabled={pageLoading || saving}
                language={language}
                titleFontSizeOffset={2}
            >
                <Box
                    sx={{
                        p: {
                            xs: 1.5,
                            sm: 2,
                        },
                    }}
                >
                    <Box
                        sx={{
                            overflow: "hidden",
                            border: "1px solid",
                            borderColor: "divider",
                            borderRadius: 1.5,
                        }}
                    >
                        <NotificationSettingRow
                            language={language}
                            titleFontSizeOffset={1}
                            icon={
                                <CircleIcon
                                    color="#EA4335"
                                    background="#FFF1F0"
                                >
                                    <NotificationSettingIcon
                                        name="gmail"
                                        size={18}
                                    />
                                </CircleIcon>
                            }
                            title={t.enableGmailTitle}
                            description={
                                isKhmer
                                    ? "ផ្ញើការជូនដំណឹងទៅអ៊ីមែលរបស់អ្នកប្រើប្រាស់ដែលបានចូលប្រើ។"
                                    : "Send notifications to the logged-in user's email address."
                            }
                            checked={
                                settings.gmail.enabled
                            }
                            disabled={
                                pageLoading ||
                                saving ||
                                !loggedInEmail
                            }
                            onChange={
                                updateGmailEnabled
                            }
                        />
                    </Box>

                    {!userLoading &&
                        !loggedInEmail && (
                            <Alert
                                severity="error"
                                sx={{
                                    mt: 1.5,
                                    fontFamily,
                                }}
                            >
                                {isKhmer
                                    ? "រកមិនឃើញអ៊ីមែលរបស់អ្នកប្រើប្រាស់ដែលបានចូលប្រើ។"
                                    : "Logged-in user email was not found."}
                            </Alert>
                        )}
                </Box>
            </NotificationSettingCard>
        </Box>
    );

    const orderedCards =
        activeTab === "system"
            ? [
                systemNotificationCard,
                gmailNotificationCard,
            ]
            : [
                gmailNotificationCard,
                systemNotificationCard,
            ];

    return (
        <Box
            sx={{
                width: "100%",
                px: {
                    xs: 2,
                    sm: 3,
                    lg: 3.5,
                },
                py: {
                    xs: 2.5,
                    sm: 3,
                },
                fontFamily,

                "& .MuiTypography-root": {
                    fontFamily,
                },

                "& .MuiButton-root": {
                    fontFamily,
                    textTransform: "none",
                },
            }}
        >
            {pageLoading && (
                <LinearProgress
                    sx={{
                        position: "fixed",
                        top: 0,
                        left: 0,
                        right: 0,
                        zIndex: 1600,
                    }}
                />
            )}

            {/* Breadcrumb */}
            <Box
                sx={{
                    mb: 1,
                    display: "flex",
                    alignItems: "center",
                    gap: 1,
                    flexWrap: "wrap",
                }}
            >
                <Typography
                    sx={{
                        color: "text.secondary",
                        fontSize: isKhmer
                            ? 13
                            : 12.5,
                        lineHeight: isKhmer
                            ? 1.7
                            : 1.4,
                    }}
                >
                    {t.breadcrumbDashboard}
                </Typography>

                <Typography
                    sx={{
                        color: "text.disabled",
                        fontSize: 12.5,
                    }}
                >
                    ›
                </Typography>

                <Typography
                    sx={{
                        color: "text.secondary",
                        fontSize: isKhmer
                            ? 13
                            : 12.5,
                        lineHeight: isKhmer
                            ? 1.7
                            : 1.4,
                    }}
                >
                    {t.breadcrumbNotificationSettings}
                </Typography>
            </Box>

            {/* Header */}
            <Box
                sx={{
                    mb: 2,
                    display: "flex",
                    alignItems: {
                        xs: "flex-start",
                        sm: "center",
                    },
                    justifyContent:
                        "space-between",
                    flexDirection: {
                        xs: "column",
                        sm: "row",
                    },
                    gap: 2,
                }}
            >
                <Box sx={{ minWidth: 0 }}>
                    <Typography
                        component="h1"
                        sx={{
                            color: "text.primary",
                            fontSize: isKhmer
                                ? {
                                    xs: 24,
                                    sm: 28,
                                }
                                : {
                                    xs: 27,
                                    sm: 31,
                                },
                            lineHeight: isKhmer
                                ? 1.6
                                : 1.2,
                            fontWeight: isKhmer
                                ? 600
                                : 700,
                            letterSpacing: isKhmer
                                ? 0
                                : "-0.02em",
                        }}
                    >
                        {t.pageTitle}
                    </Typography>

                    <Typography
                        sx={{
                            mt: isKhmer ? 0.2 : 0.65,
                            color: "text.secondary",
                            fontSize: isKhmer
                                ? 14
                                : 13.5,
                            lineHeight: isKhmer
                                ? 1.85
                                : 1.5,
                        }}
                    >
                        {t.pageDescription}
                    </Typography>
                </Box>

                <Button
                    variant="contained"
                    disabled={
                        pageLoading ||
                        saving ||
                        (settings.gmail.enabled &&
                            !loggedInEmail)
                    }
                    onClick={() => {
                        void handleSaveSettings();
                    }}
                    startIcon={
                        saving ? (
                            <CircularProgress
                                size={17}
                                color="inherit"
                            />
                        ) : (
                            <NotificationSettingIcon
                                name="save"
                                size={17}
                            />
                        )
                    }
                    sx={{
                        minHeight: isKhmer
                            ? 44
                            : 40,
                        px: 2,
                        borderRadius: 1.25,
                        fontSize: isKhmer
                            ? 13.5
                            : 13,
                        fontWeight: 600,
                        boxShadow: "none",
                        whiteSpace: "nowrap",
                    }}
                >
                    {saving
                        ? t.saving
                        : t.saveChanges}
                </Button>
            </Box>

            {/* API Loading Error */}
            {error && (
                <Alert
                    severity="error"
                    sx={{
                        mb: 2,
                        fontFamily,
                    }}
                >
                    {error}
                </Alert>
            )}

            {/* Tabs */}
            <Box
                role="tablist"
                sx={{
                    mb: 2,
                    display: "flex",
                    alignItems: "center",
                    overflowX: "auto",
                    borderBottom: "1px solid",
                    borderColor: "divider",
                }}
            >
                {(
                    [
                        "system",
                        "gmail",
                    ] as const
                ).map((tab) => {
                    const active =
                        activeTab === tab;

                    const label =
                        tab === "system"
                            ? t.systemTab
                            : t.gmailTab;

                    const icon =
                        tab === "system"
                            ? "bell"
                            : "gmail";

                    return (
                        <Box
                            key={tab}
                            component="button"
                            type="button"
                            role="tab"
                            aria-selected={active}
                            onClick={() =>
                                handleTabChange(tab)
                            }
                            sx={{
                                minHeight: isKhmer
                                    ? 54
                                    : 48,
                                px: 2,
                                display: "flex",
                                alignItems: "center",
                                gap: 1,
                                cursor: "pointer",
                                border: 0,
                                bgcolor: active
                                    ? "action.selected"
                                    : "transparent",
                                color: active
                                    ? "primary.main"
                                    : "text.secondary",
                                borderBottom: "2px solid",
                                borderBottomColor: active
                                    ? "primary.main"
                                    : "transparent",
                                fontFamily,
                                fontSize: isKhmer
                                    ? 15.5
                                    : 15,
                                fontWeight: active
                                    ? 700
                                    : 500,
                                whiteSpace: "nowrap",
                                transition:
                                    "background-color 0.2s ease, color 0.2s ease",

                                "&:hover": {
                                    bgcolor:
                                        "action.hover",
                                },

                                "&:focus-visible": {
                                    outline:
                                        "2px solid",
                                    outlineColor:
                                        "primary.main",
                                    outlineOffset: -2,
                                },
                            }}
                        >
                            <NotificationSettingIcon
                                name={icon}
                                size={18}
                            />

                            {label}
                        </Box>
                    );
                })}
            </Box>

            {/* Notification Cards */}
            <Box
                id="notification-setting-cards"
                sx={{
                    display: "flex",
                    flexDirection: "column",
                    gap: 2,
                    scrollMarginTop: 80,
                }}
            >
                {orderedCards}
            </Box>

            <Typography
                sx={{
                    mt: 1.5,
                    color: "text.secondary",
                    fontSize: isKhmer
                        ? 12
                        : 11.5,
                }}
            >
                {t.lastUpdated}:{" "}
                {formattedLastUpdated}
            </Typography>

            <Snackbar
                open={snackbar.open}
                autoHideDuration={3500}
                anchorOrigin={{
                    vertical: "bottom",
                    horizontal: "right",
                }}
                onClose={closeSnackbar}
            >
                <Alert
                    severity={snackbar.severity}
                    variant="filled"
                    onClose={closeSnackbar}
                    sx={{
                        width: "100%",
                        fontFamily,
                    }}
                >
                    {snackbar.message}
                </Alert>
            </Snackbar>
        </Box>
    );
}