"use client";

import type {
  Dispatch,
  FormEvent,
  SetStateAction,
} from "react";

import {
  Alert,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  FormControl,
  FormControlLabel,
  MenuItem,
  Paper,
  Select,
  Switch,
  TextField,
  useTheme,
} from "@mui/material";

import {
  TRANSLATION_MODULES,
  getTranslationModuleLabel,
} from "../constants/translation-modules";

import type {
  Translation,
  TranslationFormData,
  TranslationModule,
} from "../types/translation-types";

type UiLocale =
  | "en"
  | "km";

type PageText = {
  page: string;
  createPage: string;
  createSubPage: string;
  createPageSubtitle: string;
  createLabel: string;
  createLabelSubtitle: string;
  editLabel: string;
  editLabelSubtitle: string;
  pageEnglishName: string;
  pageKhmerName: string;
  pageTitleKey: string;
  translationKey: string;
  englishText: string;
  khmerText: string;
};

type UiText = {
  module: string;
  active: string;
  cancel: string;
  saving: string;
  update: string;
};

type Props = {
  open: boolean;
  saving: boolean;
  appFontFamily: string;
  locale: UiLocale;
  selectedLabel: Translation | null;
  pageLocked: boolean;
  pageText: PageText;
  text: UiText;
  dialogError: string;
  form: TranslationFormData;
  setForm: Dispatch<
    SetStateAction<TranslationFormData>
  >;
  onClose: () => void;
  onSubmit: (
    event: FormEvent<HTMLFormElement>,
  ) => void;
};

function sanitizePageInput(
  value: string,
): string {
  return value
    .toLowerCase()
    .replace(/\s+/g, "_")
    .replace(
      /[^a-z0-9_-]/g,
      "",
    )
    .replace(/_{2,}/g, "_")
    .replace(/-{2,}/g, "-");
}

function sanitizeTranslationKeyInput(
  value: string,
): string {
  return value
    .toLowerCase()
    .replace(/\s+/g, ".")
    .replace(
      /[^a-z0-9._-]/g,
      "",
    )
    .replace(/\.{2,}/g, ".");
}

export default function TranslationManagementFormDialog({
  open,
  saving,
  appFontFamily,
  locale,
  selectedLabel,
  pageLocked,
  pageText,
  text,
  dialogError,
  form,
  setForm,
  onClose,
  onSubmit,
}: Props) {
  const theme = useTheme();

  const isDark =
    theme.palette.mode === "dark";

  const isCreatePage =
    !pageLocked &&
    !selectedLabel;

  const isCreateSubPage =
    isCreatePage &&
    form.parentId !== null;

  const dialogBackground =
    isDark
      ? "#0F172A"
      : "#FFFFFF";

  const fieldBackground =
    isDark
      ? "#111C2F"
      : "#FFFFFF";

  const footerBackground =
    isDark
      ? "#0B1220"
      : "#FFFFFF";

  const borderColor =
    isDark
      ? "rgba(148, 163, 184, 0.34)"
      : "rgba(15, 23, 42, 0.18)";

  const mutedBackground =
    isDark
      ? "rgba(148, 163, 184, 0.08)"
      : "rgba(15, 23, 42, 0.035)";

  const fieldSx = {
    "& .MuiOutlinedInput-root": {
      bgcolor:
        fieldBackground,
      color: "text.primary",
      borderRadius: 2,
      "& fieldset": {
        borderColor,
      },
      "&:hover fieldset": {
        borderColor:
          isDark
            ? "rgba(148, 163, 184, 0.55)"
            : "rgba(15, 23, 42, 0.30)",
      },
      "&.Mui-focused fieldset": {
        borderColor:
          "primary.main",
      },
      "&.Mui-disabled": {
        bgcolor:
          isDark
            ? "rgba(15, 23, 42, 0.7)"
            : "rgba(15, 23, 42, 0.04)",
      },
    },

    "& .MuiInputBase-input.Mui-disabled":
      {
        WebkitTextFillColor:
          isDark
            ? "rgba(226,232,240,.72)"
            : "rgba(15,23,42,.55)",
      },

    "& .MuiFormHelperText-root": {
      color:
        "text.secondary",
      ml: 0,
    },
  } as const;

  const labelSx = {
    display: "block",
    mb: 0.75,
    fontSize: 14,
    fontWeight: 700,
    color: "text.primary",
  } as const;

  const requiredMark = (
    <Box
      component="span"
      sx={{
        ml: 0.5,
        color:
          "error.main",
      }}
    >
      *
    </Box>
  );

  return (
    <Dialog
      open={open}
      onClose={
        saving
          ? undefined
          : onClose
      }
      fullWidth
      maxWidth="sm"
      slotProps={{
        paper: {
          sx: {
            position: "fixed",
            top: 0,
            right: 0,
            left: {
              xs: 0,
              sm: "auto",
            },
            bottom: "auto",
            m: 0,
            width: {
              xs: "100%",
              sm: 700,
            },
            maxWidth: {
              xs: "100%",
              sm: 700,
            },
            height: "100vh",
            maxHeight: "100vh",
            borderRadius: {
              xs: 0,
              sm: "0 0 0 16px",
            },
            overflow: "hidden",
            fontFamily:
              appFontFamily,

            // FIX: use application dark background,
            // not the gray drawer background.
            bgcolor:
              dialogBackground,
            color:
              "text.primary",

            borderLeft:
              isDark
                ? "1px solid rgba(148,163,184,.16)"
                : "1px solid rgba(15,23,42,.08)",

            boxShadow: 24,
          },
        },

        backdrop: {
          sx: {
            bgcolor:
              isDark
                ? "rgba(0, 0, 0, 0.62)"
                : "rgba(0, 0, 0, 0.46)",
          },
        },
      }}
    >
      <Box
        component="form"
        onSubmit={onSubmit}
        sx={{
          display: "flex",
          flexDirection: "column",
          height: "100%",
          bgcolor:
            dialogBackground,
        }}
      >
        <DialogTitle
          sx={{
            px: 3,
            pt: 2.5,
            pb: 1.75,
            bgcolor:
              dialogBackground,
            color:
              "text.primary",
            fontFamily:
              appFontFamily,
            flexShrink: 0,
          }}
        >
          <Box
            sx={{
              fontWeight: 800,
              fontSize: 28,
              lineHeight:
                locale === "km"
                  ? 1.65
                  : 1.25,
            }}
          >
            {selectedLabel
              ? pageText.editLabel
              : pageLocked
                ? pageText.createLabel
                : isCreateSubPage
                  ? pageText.createSubPage
                  : pageText.createPage}
          </Box>

          <Box
            component="p"
            sx={{
              mt: 0.75,
              mb: 0,
              color:
                "text.secondary",
              fontSize: 15,
              fontWeight: 400,
              lineHeight:
                locale === "km"
                  ? 1.9
                  : 1.55,
            }}
          >
            {selectedLabel
              ? pageText.editLabelSubtitle
              : pageLocked
                ? pageText.createLabelSubtitle
                : isCreateSubPage
                  ? locale === "km"
                    ? "បង្កើត Sub Page ថ្មីនៅក្នុង Page ដែលបានជ្រើសរើស"
                    : "Create a new sub page inside the selected page"
                  : pageText.createPageSubtitle}
          </Box>
        </DialogTitle>

        <Divider />

        <DialogContent
          sx={{
            px: 3,
            py: 2.5,
            flex: 1,
            overflowY: "auto",
            bgcolor:
              dialogBackground,

            scrollbarColor:
              isDark
                ? "rgba(148,163,184,.42) transparent"
                : "rgba(15,23,42,.25) transparent",

            "&::-webkit-scrollbar": {
              width: 8,
            },

            "&::-webkit-scrollbar-thumb":
              {
                borderRadius: 999,
                bgcolor:
                  isDark
                    ? "rgba(148,163,184,.38)"
                    : "rgba(15,23,42,.22)",
              },
          }}
        >
          <Box
            sx={{
              display: "flex",
              flexDirection:
                "column",
              gap: 2.25,
            }}
          >
            {dialogError ? (
              <Alert severity="error">
                {dialogError}
              </Alert>
            ) : null}

            {isCreatePage ? (
              <>
                {/* MODULE */}
                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {text.module}
                    {requiredMark}
                  </Box>

                  <FormControl
                    required
                    fullWidth
                    sx={fieldSx}
                  >
                    <Select
                      value={
                        form.module
                      }

                      // Sub Page keeps the parent's module.
                      disabled={
                        isCreateSubPage
                      }

                      onChange={(
                        event,
                      ) =>
                        setForm(
                          (
                            current,
                          ) => ({
                            ...current,
                            module:
                              event.target
                                .value as TranslationModule,
                          }),
                        )
                      }

                      MenuProps={{
                        slotProps: {
                          paper: {
                            sx: {
                              bgcolor:
                                dialogBackground,
                              color:
                                "text.primary",
                              border:
                                "1px solid",
                              borderColor,
                            },
                          },
                        },
                      }}
                    >
                      {TRANSLATION_MODULES.map(
                        (
                          module,
                        ) => (
                          <MenuItem
                            key={
                              module.value
                            }
                            value={
                              module.value
                            }
                          >
                            {
                              module.label
                            }
                          </MenuItem>
                        ),
                      )}
                    </Select>
                  </FormControl>
                </Box>

                {/* PAGE */}
                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {pageText.page}
                    {requiredMark}
                  </Box>

                  <TextField
                    required
                    fullWidth

                    // FIX:
                    // no "meeting_requests" default/sample placeholder.
                    placeholder=""

                    value={form.page}
                    onChange={(
                      event,
                    ) =>
                      setForm(
                        (
                          current,
                        ) => ({
                          ...current,
                          page:
                            sanitizePageInput(
                              event.target
                                .value,
                            ),
                        }),
                      )
                    }
                    sx={fieldSx}
                  />
                </Box>

                {/* PAGE ENGLISH NAME */}
                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {
                      pageText.pageEnglishName
                    }
                    {requiredMark}
                  </Box>

                  <TextField
                    required
                    fullWidth

                    // FIX:
                    // no "Meeting Requests" placeholder.
                    placeholder=""

                    value={
                      form.englishText
                    }
                    onChange={(
                      event,
                    ) =>
                      setForm(
                        (
                          current,
                        ) => ({
                          ...current,
                          englishText:
                            event.target
                              .value,
                        }),
                      )
                    }
                    sx={fieldSx}
                  />
                </Box>

                {/* PAGE KHMER NAME */}
                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {
                      pageText.pageKhmerName
                    }
                    {requiredMark}
                  </Box>

                  <TextField
                    required
                    fullWidth

                    // FIX:
                    // no meeting-request Khmer placeholder.
                    placeholder=""

                    value={
                      form.khmerText
                    }
                    onChange={(
                      event,
                    ) =>
                      setForm(
                        (
                          current,
                        ) => ({
                          ...current,
                          khmerText:
                            event.target
                              .value,
                        }),
                      )
                    }
                    sx={fieldSx}
                  />
                </Box>

                {/* PAGE TITLE KEY */}
                <Box>
                  <Box
                    sx={labelSx}
                  >
                    {
                      pageText.pageTitleKey
                    }
                  </Box>

                  <Paper
                    variant="outlined"
                    sx={{
                      px: 1.75,
                      py: 1.5,
                      borderRadius: 2,
                      bgcolor:
                        mutedBackground,
                      borderColor,
                    }}
                  >
                    <Box
                      sx={{
                        fontFamily:
                          "monospace",
                        fontWeight: 700,
                        color:
                          "text.primary",
                      }}
                    >
                      title
                    </Box>
                  </Paper>
                </Box>
              </>
            ) : (
              <>
                {/* CREATE / EDIT LABEL */}
                <Box
                  sx={{
                    display: "grid",
                    gridTemplateColumns: {
                      xs: "1fr",
                      sm: "1fr 1fr",
                    },
                    gap: 2,
                  }}
                >
                  <Box>
                    <Box
                      component="label"
                      sx={labelSx}
                    >
                      {text.module}
                      {requiredMark}
                    </Box>

                    <TextField
                      fullWidth
                      disabled
                      value={getTranslationModuleLabel(
                        form.module,
                      )}
                      sx={fieldSx}
                    />
                  </Box>

                  <Box>
                    <Box
                      component="label"
                      sx={labelSx}
                    >
                      {
                        pageText.page
                      }
                      {requiredMark}
                    </Box>

                    <TextField
                      fullWidth
                      disabled
                      value={
                        form.page
                      }
                      sx={fieldSx}
                    />
                  </Box>
                </Box>

                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {
                      pageText.translationKey
                    }
                    {requiredMark}
                  </Box>

                  <TextField
                    required
                    fullWidth
                    placeholder=""
                    value={
                      form.translationKey
                    }
                    onChange={(
                      event,
                    ) =>
                      setForm(
                        (
                          current,
                        ) => ({
                          ...current,
                          translationKey:
                            sanitizeTranslationKeyInput(
                              event.target
                                .value,
                            ),
                        }),
                      )
                    }
                    sx={fieldSx}
                  />
                </Box>

                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {
                      pageText.englishText
                    }
                    {requiredMark}
                  </Box>

                  <TextField
                    required
                    fullWidth
                    multiline
                    minRows={3}
                    placeholder=""
                    value={
                      form.englishText
                    }
                    onChange={(
                      event,
                    ) =>
                      setForm(
                        (
                          current,
                        ) => ({
                          ...current,
                          englishText:
                            event.target
                              .value,
                        }),
                      )
                    }
                    sx={fieldSx}
                  />
                </Box>

                <Box>
                  <Box
                    component="label"
                    sx={labelSx}
                  >
                    {
                      pageText.khmerText
                    }
                    {requiredMark}
                  </Box>

                  <TextField
                    required
                    fullWidth
                    multiline
                    minRows={3}
                    placeholder=""
                    value={
                      form.khmerText
                    }
                    onChange={(
                      event,
                    ) =>
                      setForm(
                        (
                          current,
                        ) => ({
                          ...current,
                          khmerText:
                            event.target
                              .value,
                        }),
                      )
                    }
                    sx={fieldSx}
                  />
                </Box>
              </>
            )}

            <FormControlLabel
              control={
                <Switch
                  checked={
                    form.isActive
                  }
                  onChange={(
                    event,
                  ) =>
                    setForm(
                      (
                        current,
                      ) => ({
                        ...current,
                        isActive:
                          event.target
                            .checked,
                      }),
                    )
                  }
                />
              }
              label={text.active}
              sx={{
                color:
                  "text.primary",
              }}
            />
          </Box>
        </DialogContent>

        <DialogActions
          sx={{
            px: 3,
            py: 2,
            gap: 1.25,
            flexShrink: 0,
            bgcolor:
              footerBackground,
            borderTop: "1px solid",
            borderColor,
            justifyContent:
              "flex-end",
          }}
        >
          <Button
            type="button"
            variant="outlined"
            disabled={saving}
            onClick={onClose}
            sx={{
              minWidth: 110,
              minHeight: 44,
              borderRadius: 2,
              textTransform:
                "none",
              fontWeight: 700,
            }}
          >
            {text.cancel}
          </Button>

          <Button
            type="submit"
            variant="contained"
            disabled={saving}
            sx={{
              minWidth: 138,
              minHeight: 44,
              borderRadius: 2,
              textTransform:
                "none",
              fontWeight: 700,
            }}
          >
            {saving
              ? text.saving
              : selectedLabel
                ? text.update
                : pageLocked
                  ? pageText.createLabel
                  : isCreateSubPage
                    ? pageText.createSubPage
                    : pageText.createPage}
          </Button>
        </DialogActions>
      </Box>
    </Dialog>
  );
}