"use client";

import { useEffect, useRef, useState } from "react";

import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import LinkRoundedIcon from "@mui/icons-material/LinkRounded";
import FormatAlignLeftRoundedIcon from "@mui/icons-material/FormatAlignLeftRounded";
import FormatBoldRoundedIcon from "@mui/icons-material/FormatBoldRounded";
import FormatClearRoundedIcon from "@mui/icons-material/FormatClearRounded";
import FormatColorFillRoundedIcon from "@mui/icons-material/FormatColorFillRounded";
import FormatItalicRoundedIcon from "@mui/icons-material/FormatItalicRounded";
import FormatListBulletedRoundedIcon from "@mui/icons-material/FormatListBulletedRounded";
import FormatListNumberedRoundedIcon from "@mui/icons-material/FormatListNumberedRounded";
import FormatQuoteRoundedIcon from "@mui/icons-material/FormatQuoteRounded";
import FormatStrikethroughRoundedIcon from "@mui/icons-material/FormatStrikethroughRounded";
import FormatUnderlinedRoundedIcon from "@mui/icons-material/FormatUnderlinedRounded";
import HorizontalRuleRoundedIcon from "@mui/icons-material/HorizontalRuleRounded";
import LinkRoundedToolbarIcon from "@mui/icons-material/LinkRounded";
import RedoRoundedIcon from "@mui/icons-material/RedoRounded";
import UndoRoundedIcon from "@mui/icons-material/UndoRounded";

import {
    Alert,
    Box,
    Button,
    CircularProgress,
    Dialog,
    DialogContent,
    MenuItem,
    Select,
    Stack,
    TextField,
    Typography,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";

import {
    STATUS_OPTIONS,
    type CategoryOption,
    type MinistryOption,
    type RgcDecisionStatus,
} from "../rgc-decision-data";

import type {
    CreateCdcRgcDecisionInput,
    IndicatorOption,
    PlenaryOption,
    IssueOption,
} from "../service/rgc-decision-service";

import { RgcDecisionStatusChip } from "./rgc-decision-status-chip";


type CreateRgcDecisionDialogProps = {
    open: boolean;
    onClose: () => void;
    onSubmit: (
        input: CreateCdcRgcDecisionInput,
    ) => Promise<void> | void;
    ministries?: MinistryOption[];
    plenaries?: PlenaryOption[];
    categories?: CategoryOption[];
    indicators?: IndicatorOption[];
    issues?: IssueOption[]; // 🔥 ទទួលយក Issues Props
    lookupsLoading?: boolean;
    submitting?: boolean;
};

function RequiredLabel({ label }: { label: string }) {
    const theme = useTheme();

    return (
        <Typography
            sx={{
                mb: 0.75,
                color: theme.palette.text.primary,
                fontSize: 14,
                fontWeight: 600,
                lineHeight: "18px",
            }}
        >
            {label}
            <Box
                component="span"
                sx={{
                    ml: 0.3,
                    color: theme.palette.error.main,
                }}
            >
                *
            </Box>
        </Typography>
    );
}

function OptionalLabel({ label }: { label: string }) {
    const theme = useTheme();

    return (
        <Typography
            sx={{
                mb: 0.75,
                color: theme.palette.text.primary,
                fontSize: 12,
                fontWeight: 600,
                lineHeight: "18px",
            }}
        >
            {label}
        </Typography>
    );
}

function useInputSx() {
    const theme = useTheme();

    return {
        "& .MuiOutlinedInput-root": {
            minHeight: 48,
            borderRadius: "6px",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
            fontSize: 13,
            fontWeight: 500,

            "& fieldset": {
                borderColor: theme.palette.divider,
            },

            "&:hover fieldset": {
                borderColor: theme.palette.text.secondary,
            },

            "&.Mui-focused fieldset": {
                borderColor: theme.palette.primary.main,
                borderWidth: "1px",
            },
        },

        "& .MuiInputBase-input": {
            px: 1.6,
            py: 1.3,
            color: theme.palette.text.primary,
            fontSize: 13,
            fontWeight: 500,
        },

        "& .MuiInputBase-input::placeholder": {
            color: theme.palette.text.secondary,
            opacity: 1,
        },
    };
}

type EditorCommand =
    | "undo"
    | "redo"
    | "formatBlock"
    | "bold"
    | "italic"
    | "underline"
    | "strikeThrough"
    | "insertUnorderedList"
    | "insertOrderedList"
    | "createLink"
    | "formatCode"
    | "formatQuote"
    | "removeFormat"
    | "insertHorizontalRule";

type ToolbarButtonProps = {
    label: string;
    active?: boolean;
    onClick: () => void;
    children: React.ReactNode;
};

function ToolbarButton({
    label,
    active = false,
    onClick,
    children,
}: ToolbarButtonProps) {
    const theme = useTheme();
    const isDark =
        theme.palette.mode === "dark";

    return (
        <Button
            type="button"
            title={label}
            aria-label={label}
            onMouseDown={(event) => {
                event.preventDefault();
            }}
            onClick={onClick}
            sx={{
                minWidth: 24,
                width: 24,
                height: 24,
                p: 0,
                borderRadius: "4px",

                color: active
                    ? theme.palette.primary.main
                    : theme.palette.text.secondary,

                bgcolor: active
                    ? alpha(
                        theme.palette.primary.main,
                        isDark ? 0.18 : 0.1,
                    )
                    : "transparent",

                fontSize: 12,
                fontWeight: 700,
                lineHeight: 1,
                textTransform: "none",

                "& svg": {
                    fontSize: 16,
                },

                "&:hover": {
                    color:
                        theme.palette.primary.main,

                    bgcolor: alpha(
                        theme.palette.primary.main,
                        isDark ? 0.16 : 0.08,
                    ),
                },
            }}
        >
            {children}
        </Button>
    );
}

function RichTextInput({
    value,
    onChange,
    placeholder,
}: {
    value: string;
    onChange: (value: string) => void;
    placeholder: string;
}) {
    const theme = useTheme();
    const editorRef =
        useRef<HTMLDivElement | null>(null);

    const [activeFormats, setActiveFormats] =
        useState<Record<string, boolean>>(
            {},
        );

    useEffect(() => {
        const editor =
            editorRef.current;

        if (!editor) {
            return;
        }

        const currentValue =
            editor.innerHTML.trim();

        const nextValue =
            value?.trim() ?? "";

        if (currentValue !== nextValue) {
            editor.innerHTML =
                nextValue;
        }
    }, [value]);

    const updateValue = () => {
        const editor =
            editorRef.current;

        if (!editor) {
            return;
        }

        const html =
            editor.innerHTML.trim();

        const plainText =
            editor.innerText.trim();

        onChange(
            plainText ? html : "",
        );
    };

    const refreshActiveFormats = () => {
        if (
            typeof document ===
            "undefined"
        ) {
            return;
        }

        setActiveFormats({
            bold:
                document.queryCommandState(
                    "bold",
                ),
            italic:
                document.queryCommandState(
                    "italic",
                ),
            underline:
                document.queryCommandState(
                    "underline",
                ),
            strikeThrough:
                document.queryCommandState(
                    "strikeThrough",
                ),
            insertUnorderedList:
                document.queryCommandState(
                    "insertUnorderedList",
                ),
            insertOrderedList:
                document.queryCommandState(
                    "insertOrderedList",
                ),
        });
    };

    const focusEditor = () => {
        editorRef.current?.focus();
    };

    const runCommand = (
        command: EditorCommand,
        commandValue?: string,
    ) => {
        if (
            typeof document ===
            "undefined"
        ) {
            return;
        }

        focusEditor();

        if (
            command === "createLink"
        ) {
            const url =
                window.prompt(
                    "Enter URL",
                    "https://",
                );

            if (!url) {
                return;
            }

            document.execCommand(
                "createLink",
                false,
                url,
            );
        } else if (
            command === "formatCode"
        ) {
            document.execCommand(
                "formatBlock",
                false,
                "pre",
            );
        } else if (
            command === "formatQuote"
        ) {
            document.execCommand(
                "formatBlock",
                false,
                "blockquote",
            );
        } else {
            document.execCommand(
                command,
                false,
                commandValue,
            );
        }

        updateValue();
        refreshActiveFormats();
    };

    return (
        <Box
            sx={{
                position: "relative",
                overflow: "hidden",
                border: `1px solid ${theme.palette.divider}`,
                borderRadius: "6px",
                bgcolor:
                    theme.palette.background.paper,

                "&:focus-within": {
                    borderColor:
                        theme.palette.primary.main,
                },
            }}
        >
            <Stack
                direction="row"
                spacing={0.35}
                sx={{
                    minHeight: 42,
                    px: 1,
                    py: 0.65,

                    alignItems: "center",
                    flexWrap: "nowrap",

                    overflowX: "auto",

                    borderBottom: `1px solid ${theme.palette.divider}`,

                    bgcolor:
                        theme.palette.background.paper,

                    "&::-webkit-scrollbar": {
                        height: 4,
                    },

                    "&::-webkit-scrollbar-thumb": {
                        bgcolor:
                            theme.palette.divider,
                        borderRadius: 99,
                    },
                }}
            >
                <ToolbarButton
                    label="Undo"
                    onClick={() =>
                        runCommand("undo")
                    }
                >
                    <UndoRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Redo"
                    onClick={() =>
                        runCommand("redo")
                    }
                >
                    <RedoRoundedIcon />
                </ToolbarButton>

                <Box
                    sx={{
                        width: "1px",
                        minWidth: "1px",
                        height: 24,
                        mx: 0.3,
                        bgcolor:
                            theme.palette.divider,
                        flexShrink: 0,
                    }}
                />

                <ToolbarButton
                    label="Paragraph"
                    onClick={() =>
                        runCommand(
                            "formatBlock",
                            "p",
                        )
                    }
                >
                    <FormatAlignLeftRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Heading"
                    onClick={() =>
                        runCommand(
                            "formatBlock",
                            "h2",
                        )
                    }
                >
                    H
                </ToolbarButton>

                <ToolbarButton
                    label="Text color"
                    onClick={() => {
                        const color =
                            window.prompt(
                                "Enter text color",
                                "#000000",
                            );

                        if (
                            color &&
                            typeof document !==
                            "undefined"
                        ) {
                            focusEditor();

                            document.execCommand(
                                "foreColor",
                                false,
                                color,
                            );

                            updateValue();
                        }
                    }}
                >
                    <Box
                        sx={{
                            width: 20,
                            height: 20,
                            borderRadius: "4px",
                            bgcolor:
                                theme.palette.text.primary,
                        }}
                    />
                </ToolbarButton>

                <ToolbarButton
                    label="Highlight"
                    onClick={() => {
                        const color =
                            window.prompt(
                                "Enter highlight color",
                                "#FFF3A3",
                            );

                        if (
                            color &&
                            typeof document !==
                            "undefined"
                        ) {
                            focusEditor();

                            document.execCommand(
                                "hiliteColor",
                                false,
                                color,
                            );

                            updateValue();
                        }
                    }}
                >
                    <FormatColorFillRoundedIcon />
                </ToolbarButton>

                <Box
                    sx={{
                        width: "1px",
                        minWidth: "1px",
                        height: 24,
                        mx: 0.3,
                        bgcolor:
                            theme.palette.divider,
                        flexShrink: 0,
                    }}
                />

                <ToolbarButton
                    label="Bold"
                    active={
                        activeFormats.bold
                    }
                    onClick={() =>
                        runCommand("bold")
                    }
                >
                    <FormatBoldRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Italic"
                    active={
                        activeFormats.italic
                    }
                    onClick={() =>
                        runCommand("italic")
                    }
                >
                    <FormatItalicRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Underline"
                    active={
                        activeFormats.underline
                    }
                    onClick={() =>
                        runCommand(
                            "underline",
                        )
                    }
                >
                    <FormatUnderlinedRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Strike"
                    active={
                        activeFormats
                            .strikeThrough
                    }
                    onClick={() =>
                        runCommand(
                            "strikeThrough",
                        )
                    }
                >
                    <FormatStrikethroughRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Clear format"
                    onClick={() =>
                        runCommand(
                            "removeFormat",
                        )
                    }
                >
                    <FormatClearRoundedIcon />
                </ToolbarButton>

                <Box
                    sx={{
                        width: "1px",
                        minWidth: "1px",
                        height: 24,
                        mx: 0.3,
                        bgcolor:
                            theme.palette.divider,
                        flexShrink: 0,
                    }}
                />

                <ToolbarButton
                    label="Bullet list"
                    active={
                        activeFormats
                            .insertUnorderedList
                    }
                    onClick={() =>
                        runCommand(
                            "insertUnorderedList",
                        )
                    }
                >
                    <FormatListBulletedRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Ordered list"
                    active={
                        activeFormats
                            .insertOrderedList
                    }
                    onClick={() =>
                        runCommand(
                            "insertOrderedList",
                        )
                    }
                >
                    <FormatListNumberedRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Link"
                    onClick={() =>
                        runCommand(
                            "createLink",
                        )
                    }
                >
                    <LinkRoundedToolbarIcon />
                </ToolbarButton>

                <Box
                    sx={{
                        width: "1px",
                        minWidth: "1px",
                        height: 24,
                        mx: 0.3,
                        bgcolor:
                            theme.palette.divider,
                        flexShrink: 0,
                    }}
                />

                <ToolbarButton
                    label="Code block"
                    onClick={() =>
                        runCommand(
                            "formatCode",
                        )
                    }
                >
                    {"</>"}
                </ToolbarButton>

                <ToolbarButton
                    label="Quote"
                    onClick={() =>
                        runCommand(
                            "formatQuote",
                        )
                    }
                >
                    <FormatQuoteRoundedIcon />
                </ToolbarButton>

                <ToolbarButton
                    label="Horizontal line"
                    onClick={() =>
                        runCommand(
                            "insertHorizontalRule",
                        )
                    }
                >
                    <HorizontalRuleRoundedIcon />
                </ToolbarButton>
            </Stack>

            {!value ? (
                <Typography
                    aria-hidden
                    sx={{
                        position: "absolute",
                        top: 47,
                        left: 14,
                        zIndex: 0,
                        pointerEvents: "none",
                        color:
                            theme.palette.text.secondary,
                        fontSize: 13,
                        opacity: 0.8,
                    }}
                >
                    {placeholder}
                </Typography>
            ) : null}

            <Box
                ref={editorRef}
                contentEditable
                suppressContentEditableWarning
                role="textbox"
                aria-multiline="true"
                tabIndex={0}
                onInput={updateValue}
                onKeyUp={
                    refreshActiveFormats
                }
                onMouseUp={
                    refreshActiveFormats
                }
                sx={{
                    position: "relative",
                    zIndex: 1,
                    minHeight: 128,
                    px: 1.5,
                    py: 1.25,
                    color:
                        theme.palette.text.primary,
                    fontSize: 13,
                    fontWeight: 400,
                    lineHeight: 1.6,
                    outline: "none",
                    overflowWrap: "anywhere",

                    "& p": {
                        my: 0.5,
                    },

                    "& h1": {
                        my: 0.75,
                        fontSize: 22,
                        lineHeight: 1.35,
                    },

                    "& h2": {
                        my: 0.75,
                        fontSize: 18,
                        lineHeight: 1.4,
                    },

                    "& ul, & ol": {
                        my: 0.75,
                        pl: 3,
                    },

                    "& pre": {
                        my: 0.75,
                        p: 1,
                        borderRadius: "4px",
                        bgcolor:
                            theme.palette.action.hover,
                        whiteSpace: "pre-wrap",
                    },

                    "& blockquote": {
                        my: 0.75,
                        mx: 0,
                        pl: 1.5,
                        borderLeft: `3px solid ${theme.palette.divider}`,
                        color:
                            theme.palette.text.secondary,
                    },

                    "& a": {
                        color:
                            theme.palette.primary.main,
                        textDecoration:
                            "underline",
                    },
                }}
            />
        </Box>
    );
}

export function CreateRgcDecisionDialog({
    open,
    onClose,
    onSubmit,
    ministries = [],
    plenaries = [],
    categories = [],
    indicators = [],
    issues = [], // 🔥 ទទួលយក Issues Props យ៉ាងត្រឹមត្រូវ
    lookupsLoading = false,
    submitting = false,
}: CreateRgcDecisionDialogProps) {
    const theme = useTheme();
    const { language } = useAppLanguage();
    const isKhmer = language === "kh";
    const isDark = theme.palette.mode === "dark";
    const inputSx = useInputSx();

    const [stakeholderId, setStakeholderId] = useState("");
    const [plenaryId, setPlenaryId] = useState("");
    const [categoryId, setCategoryId] = useState("");
    const [indicatorId, setIndicatorId] = useState("");
    const [selectedIssueIds, setSelectedIssueIds] = useState<number[]>([]); // 🔥 State សម្រាប់ Issue IDs

    const [status, setStatus] =
        useState<RgcDecisionStatus>("Not Addressed");
    const [meetingDate, setMeetingDate] = useState("");
    const [focalPerson, setFocalPerson] = useState("");
    const [verificationLink, setVerificationLink] = useState("");
    const [decision, setDecision] = useState("");
    const [sourceOfVerification, setSourceOfVerification] = useState("");
    const [formError, setFormError] = useState<string | null>(null);

    const resetForm = () => {
        setStakeholderId("");
        setPlenaryId("");
        setCategoryId("");
        setIndicatorId("");
        setSelectedIssueIds([]); // 🔥 Reset Issues
        setStatus("Not Addressed");
        setMeetingDate("");
        setFocalPerson("");
        setVerificationLink("");
        setDecision("");
        setSourceOfVerification("");
        setFormError(null);
    };

    const handleClose = () => {
        if (submitting) return;
        resetForm();
        onClose();
    };

    const selectedMinistry = ministries.find(
        (item) => String(item.id) === stakeholderId,
    );
    const selectedPlenary = plenaries.find(
        (item) => String(item.id) === plenaryId,
    );
    const selectedCategory = categories.find(
        (item) => String(item.id) === categoryId,
    );
    const selectedIndicator = indicators.find(
        (item) => String(item.id) === indicatorId,
    );

    const canSubmit = Boolean(
        stakeholderId &&
        plenaryId &&
        categoryId &&
        indicatorId &&
        status &&
        meetingDate.trim() &&
        focalPerson.trim() &&
        decision.trim() &&
        sourceOfVerification.trim(),
    );

    const handleSubmit = async (
        saveAsDraft: boolean,
    ) => {
        if (
            !canSubmit ||
            !selectedMinistry ||
            !selectedPlenary ||
            !selectedCategory ||
            !selectedIndicator
        ) {
            setFormError(
                isKhmer
                    ? "សូមបំពេញព័ត៌មានដែលត្រូវការទាំងអស់។"
                    : "Please complete all required fields.",
            );
            return;
        }

        try {
            setFormError(null);

            await onSubmit({
                stakeholderId: Number(
                    selectedMinistry.id,
                ),
                ministry:
                    selectedMinistry.name,

                plenaryId: Number(
                    selectedPlenary.id,
                ),
                plenary:
                    selectedPlenary.name,

                categoryId: Number(
                    selectedCategory.id,
                ),
                category:
                    selectedCategory.name,

                indicatorId: Number(
                    selectedIndicator.id,
                ),
                indicator:
                    selectedIndicator.name,

                status,
                meetingDate,

                focalPerson:
                    focalPerson.trim(),

                verificationLink:
                    verificationLink.trim(),

                decision:
                    decision.trim(),

                sourceOfVerification:
                    sourceOfVerification.trim(),

                issueIds: selectedIssueIds, // 🔥 បញ្ជូន Issue IDs ទៅ Back-end
                saveAsDraft,
            });

            resetForm();
            onClose();
        } catch (requestError) {
            setFormError(
                requestError instanceof Error
                    ? requestError.message
                    : saveAsDraft
                        ? isKhmer
                            ? "មិនអាចរក្សាទុកសេចក្តីព្រាងបានទេ។"
                            : "Unable to save draft."
                        : isKhmer
                            ? "មិនអាចផ្ញើសេចក្តីសម្រេចបានទេ។"
                            : "Unable to send RGC Decision.",
            );
        }
    };

    const selectSx = {
        height: 48,
        borderRadius: "6px",
        bgcolor: theme.palette.background.paper,
        color: theme.palette.text.primary,
        fontSize: 13,
        fontWeight: 500,

        "& fieldset": {
            borderColor: theme.palette.divider,
        },
        "&:hover fieldset": {
            borderColor: theme.palette.text.secondary,
        },
        "&.Mui-focused fieldset": {
            borderColor: theme.palette.primary.main,
            borderWidth: "1px",
        },
        "& .MuiSelect-select": {
            display: "flex",
            alignItems: "center",
            px: 1.6,
            py: 1.3,
        },
        "& .MuiSvgIcon-root": {
            color: theme.palette.text.secondary,
        },
    };

    const selectMenuProps = {
        disablePortal: true,
        marginThreshold: 8,
        anchorOrigin: {
            vertical: "bottom" as const,
            horizontal: "left" as const,
        },
        transformOrigin: {
            vertical: "top" as const,
            horizontal: "left" as const,
        },
        slotProps: {
            paper: {
                sx: {
                    mt: 0.5,
                    maxHeight: 240,
                    overflowY: "auto",
                    borderRadius: "6px",
                    border: `1px solid ${theme.palette.divider}`,
                    bgcolor: theme.palette.background.paper,
                    boxShadow: isDark
                        ? "0 12px 30px rgba(0, 0, 0, 0.55)"
                        : "0 12px 30px rgba(16, 24, 40, 0.16)",
                    "& .MuiMenu-list": {
                        py: 0.5,
                    },
                    "&::-webkit-scrollbar": {
                        width: 7,
                    },
                    "&::-webkit-scrollbar-track": {
                        bgcolor: isDark
                            ? alpha("#FFFFFF", 0.06)
                            : "#F2F4F7",
                    },
                    "&::-webkit-scrollbar-thumb": {
                        bgcolor: isDark
                            ? alpha("#FFFFFF", 0.25)
                            : "#98A2B3",
                        borderRadius: 99,
                    },
                },
            },
        },
    };

    const optionSx = {
        minHeight: 42,
        px: 1.6,
        py: 1,
        fontSize: 13,
        color: theme.palette.text.primary,
        "&.Mui-selected": {
            bgcolor: alpha(theme.palette.primary.main, 0.1),
        },
        "&.Mui-selected:hover": {
            bgcolor: alpha(theme.palette.primary.main, 0.14),
        },
    };

    return (
        <Dialog
            open={open}
            onClose={handleClose}
            maxWidth={false}
            scroll="paper"
            sx={{
                "& .MuiDialog-container": {
                    display: "flex",
                    alignItems: "stretch",
                    justifyContent: "flex-end",
                    padding: 0,
                },
            }}
            slotProps={{
                backdrop: {
                    sx: {
                        bgcolor: isDark
                            ? "rgba(0, 0, 0, 0.72)"
                            : "rgba(16, 24, 40, 0.62)",
                    },
                },
                paper: {
                    sx: {
                        m: 0,
                        position: "fixed",
                        top: 0,
                        right: 0,
                        bottom: 0,
                        width: {
                            xs: "calc(100vw - 24px)",
                            md: 780,
                            lg: 780,
                        },
                        maxWidth: "calc(100vw - 24px)",
                        height: "100vh",
                        maxHeight: "100vh",
                        borderRadius: "8px 0 0 8px",
                        bgcolor: theme.palette.background.paper,
                        color: theme.palette.text.primary,
                        boxShadow: isDark
                            ? "0 24px 64px rgba(0, 0, 0, 0.65)"
                            : "0 24px 64px rgba(16, 24, 40, 0.24)",
                        overflow: "hidden",
                        display: "flex",
                        flexDirection: "column",
                    },
                },
            }}
        >
            <Box
                sx={{
                    minHeight: 72,
                    px: 2.4,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    gap: 2,
                    borderBottom: `1px solid ${theme.palette.divider}`,
                    flexShrink: 0,
                    bgcolor: theme.palette.background.paper,
                }}
            >
                <Typography
                    sx={{
                        minWidth: 0,
                        color: theme.palette.text.primary,
                        fontSize: 18,
                        fontWeight: 800,
                        lineHeight: "28px",
                        whiteSpace: "nowrap",
                    }}
                >
                    {isKhmer
                        ? "បង្កើតសេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល"
                        : "Create RGC Decision"}
                </Typography>

                <Stack
                    direction="row"
                    spacing={1.5}
                    sx={{
                        alignItems: "center",
                        flexShrink: 0,
                        whiteSpace: "nowrap",
                    }}
                >
                    <Button
                        variant="contained"
                        disabled={
                            submitting ||
                            lookupsLoading ||
                            !canSubmit
                        }
                        startIcon={
                            submitting ? (
                                <CircularProgress
                                    size={16}
                                    color="inherit"
                                />
                            ) : (
                                <LinkRoundedIcon
                                    sx={{
                                        fontSize: 18,
                                    }}
                                />
                            )
                        }
                        onClick={() =>
                            void handleSubmit(true)
                        }
                        sx={{
                            width: 138,
                            minWidth: 138,
                            height: 44,
                            px: 1.5,
                            borderRadius: "6px",
                            textTransform: "none",
                            bgcolor:
                                theme.palette.primary.main,
                            color:
                                theme.palette.primary.contrastText,
                            fontSize: 13,
                            fontWeight: 700,
                            boxShadow: "none",

                            "&:hover": {
                                bgcolor:
                                    theme.palette.primary.dark,
                                boxShadow: "none",
                            },

                            "&.Mui-disabled": {
                                bgcolor:
                                    theme.palette.action
                                        .disabledBackground,
                                color:
                                    theme.palette.action.disabled,
                            },
                        }}
                    >
                        {submitting
                            ? isKhmer
                                ? "កំពុងរក្សាទុក..."
                                : "Saving..."
                            : isKhmer
                                ? "រក្សាទុកសេចក្តីព្រាង"
                                : "Save Draft"}
                    </Button>

                    <Button
                        variant="contained"
                        disabled={submitting || lookupsLoading || !canSubmit}
                        startIcon={
                            submitting ? (
                                <CircularProgress size={16} color="inherit" />
                            ) : (
                                <CheckRoundedIcon sx={{ fontSize: 18 }} />
                            )
                        }
                        onClick={() =>
                            void handleSubmit(false)
                        }
                        sx={{
                            width: 180,
                            minWidth: 180,
                            height: 44,
                            px: 1.5,
                            borderRadius: "6px",
                            textTransform: "none",
                            bgcolor: theme.palette.primary.main,
                            color: theme.palette.primary.contrastText,
                            fontSize: 13,
                            fontWeight: 700,
                            boxShadow: "none",
                            "&:hover": {
                                bgcolor: theme.palette.primary.dark,
                                boxShadow: "none",
                            },
                            "&.Mui-disabled": {
                                bgcolor: theme.palette.action.disabledBackground,
                                color: theme.palette.action.disabled,
                            },
                        }}
                    >
                        {submitting ? (isKhmer ? "កំពុងផ្ញើ..." : "Sending...") : (isKhmer ? "ផ្ញើការជូនដំណឹង" : "Send notification")}
                    </Button>
                </Stack>
            </Box>

            <DialogContent
                sx={{
                    px: 2.4,
                    py: 2.2,
                    overflowY: "auto",
                    flex: 1,
                    bgcolor: theme.palette.background.paper,
                    "&::-webkit-scrollbar": {
                        width: 8,
                    },
                    "&::-webkit-scrollbar-track": {
                        bgcolor: isDark
                            ? alpha("#FFFFFF", 0.08)
                            : "#F2F4F7",
                    },
                    "&::-webkit-scrollbar-thumb": {
                        bgcolor: isDark
                            ? alpha("#FFFFFF", 0.28)
                            : "#98A2B3",
                        borderRadius: 99,
                    },
                }}
            >
                <Stack spacing={2.2}>
                    {formError ? (
                        <Alert severity="error">{formError}</Alert>
                    ) : null}

                    <Box>
                        <RequiredLabel label={isKhmer ? "ក្រសួង/ស្ថាប័ន" : "Ministry"} />
                        <Select
                            value={stakeholderId}
                            displayEmpty
                            fullWidth
                            disabled={lookupsLoading}
                            MenuProps={selectMenuProps}
                            onChange={(event) => {
                                setStakeholderId(String(event.target.value));
                                setFormError(null);
                            }}
                            renderValue={(selected) => {
                                const value = String(selected ?? "");
                                if (!value) {
                                    return (
                                        <Typography
                                            component="span"
                                            sx={{
                                                color: theme.palette.text.secondary,
                                                fontSize: 13,
                                            }}
                                        >
                                            {lookupsLoading
                                                ? (isKhmer ? "កំពុងផ្ទុកក្រសួង/ស្ថាប័ន..." : "Loading Ministries...")
                                                : (isKhmer ? "ជ្រើសរើសក្រសួង/ស្ថាប័ន" : "Select Ministry")}
                                        </Typography>
                                    );
                                }

                                return (
                                    ministries.find(
                                        (item) => String(item.id) === value,
                                    )?.name ?? "Selected Ministry"
                                );
                            }}
                            sx={selectSx}
                        >
                            <MenuItem value="" disabled sx={optionSx}>
                                Select Ministry
                            </MenuItem>
                            {ministries.length === 0 && !lookupsLoading ? (
                                <MenuItem disabled sx={optionSx}>
                                    No ministries found
                                </MenuItem>
                            ) : (
                                ministries.map((item) => (
                                    <MenuItem
                                        key={item.id}
                                        value={String(item.id)}
                                        sx={optionSx}
                                    >
                                        {item.name}
                                    </MenuItem>
                                ))
                            )}
                        </Select>
                    </Box>

                    {/* 🔥 ដាក់បញ្ចូល Select Linked Issues នៅក្រោម Ministry យ៉ាងត្រឹមត្រូវ */}
                    <Box>
                        <OptionalLabel label={isKhmer ? "តភ្ជាប់បញ្ហា (Linked Issues)" : "Linked Issues"} />
                        <Select
                            multiple
                            value={selectedIssueIds}
                            displayEmpty
                            fullWidth
                            disabled={lookupsLoading}
                            MenuProps={selectMenuProps}
                            onChange={(event) => {
                                setSelectedIssueIds(event.target.value as number[]);
                                setFormError(null);
                            }}
                            renderValue={(selected) => {
                                const ids = selected as number[];
                                if (ids.length === 0) {
                                    return (
                                        <Typography
                                            component="span"
                                            sx={{
                                                color: theme.palette.text.secondary,
                                                fontSize: 13,
                                            }}
                                        >
                                            {isKhmer ? "ជ្រើសរើសបញ្ហា (ជាជម្រើស)" : "Select issues (optional)"}
                                        </Typography>
                                    );
                                }
                                return ids
                                    .map((id) => issues.find((i) => i.id === id)?.title)
                                    .filter(Boolean)
                                    .join(", ");
                            }}
                            sx={selectSx}
                        >
                            {issues.length === 0 ? (
                                <MenuItem disabled sx={optionSx}>
                                    No issues found
                                </MenuItem>
                            ) : (
                                issues.map((issue) => (
                                    <MenuItem
                                        key={issue.id}
                                        value={issue.id}
                                        sx={optionSx}
                                    >
                                        {issue.title}
                                    </MenuItem>
                                ))
                            )}
                        </Select>
                    </Box>

                    <Box>
                        <RequiredLabel label={isKhmer ? "កិច្ចប្រជុំពេញអង្គ" : "Plenary"} />
                        <Select
                            value={plenaryId}
                            displayEmpty
                            fullWidth
                            disabled={lookupsLoading}
                            MenuProps={selectMenuProps}
                            onChange={(event) => {
                                setPlenaryId(String(event.target.value));
                                setFormError(null);
                            }}
                            renderValue={(selected) => {
                                const value = String(selected ?? "");
                                if (!value) {
                                    return (
                                        <Typography
                                            component="span"
                                            sx={{
                                                color: theme.palette.text.secondary,
                                                fontSize: 13,
                                            }}
                                        >
                                            {lookupsLoading
                                                ? (isKhmer ? "កំពុងផ្ទុកកិច្ចប្រជុំពេញអង្គ..." : "Loading Plenaries...")
                                                : (isKhmer ? "ជ្រើសរើសកិច្ចប្រជុំពេញអង្គ" : "Select Plenary")}
                                        </Typography>
                                    );
                                }

                                return (
                                    plenaries.find(
                                        (item) => String(item.id) === value,
                                    )?.name ?? "Selected Plenary"
                                );
                            }}
                            sx={selectSx}
                        >
                            <MenuItem value="" disabled sx={optionSx}>
                                Select Plenary
                            </MenuItem>
                            {plenaries.length === 0 && !lookupsLoading ? (
                                <MenuItem disabled sx={optionSx}>
                                    No plenaries found
                                </MenuItem>
                            ) : (
                                plenaries.map((item) => (
                                    <MenuItem
                                        key={item.id}
                                        value={String(item.id)}
                                        sx={optionSx}
                                    >
                                        {item.name}
                                    </MenuItem>
                                ))
                            )}
                        </Select>
                    </Box>

                    <Box>
                        <RequiredLabel label={isKhmer ? "ស្ថានភាព" : "Status"} />
                        <Select
                            value={status}
                            fullWidth
                            MenuProps={selectMenuProps}
                            onChange={(event) => {
                                setStatus(
                                    event.target.value as RgcDecisionStatus,
                                );
                                setFormError(null);
                            }}
                            renderValue={(selected) => (
                                <RgcDecisionStatusChip
                                    status={selected as RgcDecisionStatus}
                                />
                            )}
                            sx={selectSx}
                        >
                            {STATUS_OPTIONS.map((item) => (
                                <MenuItem
                                    key={item}
                                    value={item}
                                    sx={optionSx}
                                >
                                    <RgcDecisionStatusChip status={item} />
                                </MenuItem>
                            ))}
                        </Select>
                    </Box>

                    <Box
                        sx={{
                            display: "grid",
                            gridTemplateColumns: {
                                xs: "1fr",
                                md: "1fr 1fr",
                            },
                            gap: 2,
                        }}
                    >
                        <Box>
                            <RequiredLabel label={isKhmer ? "កាលបរិច្ឆេទប្រជុំ" : "Meeting Date"} />
                            <TextField
                                type="date"
                                value={meetingDate}
                                onChange={(event) =>
                                    setMeetingDate(event.target.value)
                                }
                                fullWidth
                                sx={inputSx}
                            />
                        </Box>

                        <Box>
                            <RequiredLabel label={isKhmer ? "ប្រភេទ" : "Category"} />
                            <Select
                                value={categoryId}
                                displayEmpty
                                fullWidth
                                disabled={lookupsLoading}
                                MenuProps={selectMenuProps}
                                onChange={(event) => {
                                    setCategoryId(String(event.target.value));
                                    setFormError(null);
                                }}
                                renderValue={(selected) => {
                                    const value = String(selected ?? "");
                                    if (!value) {
                                        return (
                                            <Typography
                                                component="span"
                                                sx={{
                                                    color: theme.palette.text.secondary,
                                                    fontSize: 13,
                                                }}
                                            >
                                                {lookupsLoading
                                                    ? (isKhmer ? "កំពុងផ្ទុកប្រភេទ..." : "Loading Categories...")
                                                    : (isKhmer ? "ជ្រើសរើសប្រភេទ" : "Select Category")}
                                            </Typography>
                                        );
                                    }

                                    return (
                                        categories.find(
                                            (item) =>
                                                String(item.id) === value,
                                        )?.name ?? "Selected Category"
                                    );
                                }}
                                sx={selectSx}
                            >
                                <MenuItem value="" disabled sx={optionSx}>
                                    Select Category
                                </MenuItem>
                                {categories.length === 0 && !lookupsLoading ? (
                                    <MenuItem disabled sx={optionSx}>
                                        No categories found
                                    </MenuItem>
                                ) : (
                                    categories.map((item) => (
                                        <MenuItem
                                            key={item.id}
                                            value={String(item.id)}
                                            sx={optionSx}
                                        >
                                            {item.name}
                                        </MenuItem>
                                    ))
                                )}
                            </Select>
                        </Box>

                        <Box>
                            <RequiredLabel label={isKhmer ? "សូចនាករ" : "Indicator"} />
                            <Select
                                value={indicatorId}
                                displayEmpty
                                fullWidth
                                disabled={lookupsLoading}
                                MenuProps={selectMenuProps}
                                onChange={(event) => {
                                    setIndicatorId(String(event.target.value));
                                    setFormError(null);
                                }}
                                renderValue={(selected) => {
                                    const value = String(selected ?? "");
                                    if (!value) {
                                        return (
                                            <Typography
                                                component="span"
                                                sx={{
                                                    color: theme.palette.text.secondary,
                                                    fontSize: 13,
                                                }}
                                            >
                                                {lookupsLoading
                                                    ? (isKhmer ? "កំពុងផ្ទុកសូចនាករ..." : "Loading Indicators...")
                                                    : (isKhmer ? "ជ្រើសរើសសូចនាករ" : "Select Indicator")}
                                            </Typography>
                                        );
                                    }

                                    return (
                                        indicators.find(
                                            (item) =>
                                                String(item.id) === value,
                                        )?.name ?? "Selected Indicator"
                                    );
                                }}
                                sx={selectSx}
                            >
                                <MenuItem value="" disabled sx={optionSx}>
                                    Select Indicator
                                </MenuItem>
                                {indicators.length === 0 && !lookupsLoading ? (
                                    <MenuItem disabled sx={optionSx}>
                                        No indicators found
                                    </MenuItem>
                                ) : (
                                    indicators.map((item) => (
                                        <MenuItem
                                            key={item.id}
                                            value={String(item.id)}
                                            sx={{
                                                ...optionSx,
                                                display: "block",
                                            }}
                                        >
                                            <Typography
                                                sx={{
                                                    fontSize: 13,
                                                    fontWeight: 600,
                                                }}
                                            >
                                                {item.name}
                                            </Typography>
                                            {item.description ? (
                                                <Typography
                                                    sx={{
                                                        mt: 0.25,
                                                        color: theme.palette.text.secondary,
                                                        fontSize: 11,
                                                        lineHeight: 1.45,
                                                        whiteSpace: "normal",
                                                    }}
                                                >
                                                    {item.description}
                                                </Typography>
                                            ) : null}
                                        </MenuItem>
                                    ))
                                )}
                            </Select>
                        </Box>

                        <Box>
                            <RequiredLabel label={isKhmer ? "មន្ត្រីបង្គោល (ឯកឧត្តម)" : "Focal Person (H.E)"} />
                            <TextField
                                value={focalPerson}
                                onChange={(event) =>
                                    setFocalPerson(event.target.value)
                                }
                                placeholder={isKhmer ? "បញ្ចូលមន្ត្រីបង្គោល..." : "Enter Focal Person..."}
                                fullWidth
                                sx={inputSx}
                            />
                        </Box>

                        <Box
                            sx={{
                                gridColumn: {
                                    xs: "1",
                                    md: "1 / -1",
                                },
                            }}
                        >
                            <OptionalLabel label={isKhmer ? "តំណភ្ជាប់ប្រភពផ្ទៀងផ្ទាត់" : "Link to Verification Source"} />
                            <TextField
                                value={verificationLink}
                                onChange={(event) =>
                                    setVerificationLink(event.target.value)
                                }
                                placeholder="https://..."
                                fullWidth
                                sx={inputSx}
                            />
                        </Box>
                    </Box>

                    <Box>
                        <RequiredLabel label={isKhmer ? "សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល" : "RGC Decision"} />
                        <RichTextInput
                            value={decision}
                            onChange={setDecision}
                            placeholder={isKhmer ? "បញ្ចូលសេចក្តីសម្រេច..." : "Enter RGC Decision..."}
                        />
                    </Box>

                    <Box>
                        <RequiredLabel label={isKhmer ? "ប្រភពនៃការផ្ទៀងផ្ទាត់" : "Source of Verification"} />
                        <RichTextInput
                            value={sourceOfVerification}
                            onChange={setSourceOfVerification}
                            placeholder={isKhmer ? "បញ្ចូលប្រភពនៃការផ្ទៀងផ្ទាត់..." : "Enter Source of Verification..."}
                        />
                    </Box>
                </Stack>
            </DialogContent>
        </Dialog>
    );
}

export default CreateRgcDecisionDialog;