"use client";

import { useState } from "react";

import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import LinkRoundedIcon from "@mui/icons-material/LinkRounded";

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

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

import type {
    CreateCdcRgcDecisionInput,
    IndicatorOption,
    PlenaryOption,
} 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[];
    lookupsLoading?: boolean;
    submitting?: boolean;
};

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

    return (
        <Typography
            sx={{
                mb: 0.75,
                color: theme.palette.text.primary,
                fontSize: 12,
                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,
        },
    };
}

function ToolbarIcon({ children }: { children: string }) {
    const theme = useTheme();

    return (
        <Box
            sx={{
                width: 14,
                height: 18,
                display: "grid",
                placeItems: "center",
                color:
                    children === "■"
                        ? theme.palette.text.primary
                        : theme.palette.text.secondary,
                fontSize: children === "■" ? 10 : 9,
                fontWeight: children === "B" ? 800 : 600,
                lineHeight: 1,
                flexShrink: 0,
            }}
        >
            {children}
        </Box>
    );
}

function EditorToolbar() {
    const theme = useTheme();
    const icons = [
        "↶",
        "↷",
        "≡",
        "▾",
        "■",
        "B",
        "I",
        "U",
        "S",
        "‹›",
        "⌘",
        "≡",
        "↗",
        "❝",
        "—",
    ];

    return (
        <Stack
            direction="row"
            spacing={0.45}
            sx={{
                height: 30,
                px: 1.2,
                alignItems: "center",
                overflow: "hidden",
                borderBottom: `1px solid ${theme.palette.divider}`,
                bgcolor: theme.palette.background.paper,
            }}
        >
            {icons.map((item, index) => (
                <ToolbarIcon key={`${item}-${index}`}>
                    {item}
                </ToolbarIcon>
            ))}
        </Stack>
    );
}

function RichTextInput({
    value,
    onChange,
    placeholder,
}: {
    value: string;
    onChange: (value: string) => void;
    placeholder: string;
}) {
    const theme = useTheme();

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

                "&:focus-within": {
                    borderColor: theme.palette.primary.main,
                },
            }}
        >
            <EditorToolbar />

            <TextField
                value={value}
                onChange={(event) => onChange(event.target.value)}
                placeholder={placeholder}
                fullWidth
                multiline
                minRows={4}
                variant="standard"
                slotProps={{
                    input: {
                        disableUnderline: true,
                    },
                }}
                sx={{
                    "& .MuiInputBase-root": {
                        px: 1.4,
                        py: 1,
                        color: theme.palette.text.primary,
                        fontSize: 13,
                        fontWeight: 500,
                        lineHeight: "20px",
                    },

                    "& textarea::placeholder": {
                        color: theme.palette.text.secondary,
                        opacity: 1,
                    },
                }}
            />
        </Box>
    );
}

export function CreateRgcDecisionDialog({
    open,
    onClose,
    onSubmit,
    ministries = [],
    plenaries = [],
    categories = [],
    indicators = [],
    lookupsLoading = false,
    submitting = false,
}: CreateRgcDecisionDialogProps) {
    const theme = useTheme();
    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 [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("");
        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 () => {
        if (
            !canSubmit ||
            !selectedMinistry ||
            !selectedPlenary ||
            !selectedCategory ||
            !selectedIndicator
        ) {
            setFormError("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(),
            });

            resetForm();
            onClose();
        } catch (requestError) {
            setFormError(
                requestError instanceof Error
                    ? requestError.message
                    : "Unable to create 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: 880,
                            lg: 880,
                        },
                        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",
                    }}
                >
                    Create RGC Decision
                </Typography>

                <Stack
                    direction="row"
                    spacing={1.5}
                    sx={{
                        alignItems: "center",
                        flexShrink: 0,
                        whiteSpace: "nowrap",
                    }}
                >
                    <Button
                        variant="contained"
                        disabled
                        startIcon={<LinkRoundedIcon sx={{ fontSize: 18 }} />}
                        sx={{
                            width: 138,
                            minWidth: 138,
                            height: 44,
                            px: 1.5,
                            borderRadius: "6px",
                            textTransform: "none",
                            bgcolor: `${theme.palette.action.disabledBackground} !important`,
                            color: `${theme.palette.action.disabled} !important`,
                            fontSize: 13,
                            fontWeight: 700,
                            boxShadow: "none",
                        }}
                    >
                        Save Draft
                    </Button>

                    <Button
                        variant="contained"
                        disabled={submitting || lookupsLoading || !canSubmit}
                        startIcon={
                            submitting ? (
                                <CircularProgress size={16} color="inherit" />
                            ) : (
                                <CheckRoundedIcon sx={{ fontSize: 18 }} />
                            )
                        }
                        onClick={() => void handleSubmit()}
                        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 ? "Sending..." : "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="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
                                                ? "Loading Ministries..."
                                                : "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>

                    <Box>
                        <RequiredLabel label="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
                                                ? "Loading Plenaries..."
                                                : "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="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="Meeting Date" />
                            <TextField
                                type="date"
                                value={meetingDate}
                                onChange={(event) =>
                                    setMeetingDate(event.target.value)
                                }
                                fullWidth
                                sx={inputSx}
                            />
                        </Box>

                        <Box>
                            <RequiredLabel label="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
                                                    ? "Loading Categories..."
                                                    : "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="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
                                                    ? "Loading Indicators..."
                                                    : "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="Focal Person (H.E)" />
                            <TextField
                                value={focalPerson}
                                onChange={(event) =>
                                    setFocalPerson(event.target.value)
                                }
                                placeholder="Enter Focal Person..."
                                fullWidth
                                sx={inputSx}
                            />
                        </Box>

                        <Box
                            sx={{
                                gridColumn: {
                                    xs: "1",
                                    md: "1 / -1",
                                },
                            }}
                        >
                            <OptionalLabel label="Link to Verification Source" />
                            <TextField
                                value={verificationLink}
                                onChange={(event) =>
                                    setVerificationLink(event.target.value)
                                }
                                placeholder="https://..."
                                fullWidth
                                sx={inputSx}
                            />
                        </Box>
                    </Box>

                    <Box>
                        <RequiredLabel label="RGC Decision" />
                        <RichTextInput
                            value={decision}
                            onChange={setDecision}
                            placeholder="Enter RGC Decision..."
                        />
                    </Box>

                    <Box>
                        <RequiredLabel label="Source of Verification" />
                        <RichTextInput
                            value={sourceOfVerification}
                            onChange={setSourceOfVerification}
                            placeholder="Enter Source of Verification..."
                        />
                    </Box>
                </Stack>
            </DialogContent>
        </Dialog>
    );
}

export default CreateRgcDecisionDialog;