"use client";

import { useState } from "react";

import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  TextField,
  Typography,
} from "@mui/material";

import type {
  MasterDataFormValue,
  MasterDataTab,
} from "../types/master-data-types";

type Props = {
  open: boolean;
  mode: "create" | "edit";
  tab: MasterDataTab;
  initialValue?: MasterDataFormValue | null;
  loading?: boolean;
  language?: "en" | "kh";
  fontFamily?: string;
  onClose: () => void;
  onSubmit: (value: MasterDataFormValue) => void;
};

type DialogFormProps = {
  mode: "create" | "edit";
  tab: MasterDataTab;
  initialValue?: MasterDataFormValue | null;
  loading: boolean;
  language: "en" | "kh";
  fontFamily?: string;
  onClose: () => void;
  onSubmit: (value: MasterDataFormValue) => void;
};

const emptyValue: MasterDataFormValue = {
  name: "",
  description: "",
};

const copy = {
  en: {
    category: "Category",
    indicator: "Indicator",
    status: "Status",
    add: "Add",
    edit: "Edit",
    name: "Name",
    description: "Description",
    cancel: "Cancel",
    create: "Create",
    save: "Save",
  },
  kh: {
    category: "ប្រភេទ",
    indicator: "សូចនាករ",
    status: "ស្ថានភាព",
    add: "បន្ថែម",
    edit: "កែប្រែ",
    name: "ឈ្មោះ",
    description: "ការពិពណ៌នា",
    cancel: "បោះបង់",
    create: "បង្កើត",
    save: "រក្សាទុក",
  },
} as const;

function MasterDataDialogForm({
  mode,
  tab,
  initialValue,
  loading,
  language,
  fontFamily,
  onClose,
  onSubmit,
}: DialogFormProps) {
  const [form, setForm] = useState<MasterDataFormValue>(() => ({
    name: initialValue?.name ?? "",
    description: initialValue?.description ?? "",
  }));

  const text = language === "kh" ? copy.kh : copy.en;

  const itemLabel =
    tab === "categories"
      ? text.category
      : tab === "indicators"
        ? text.indicator
        : text.status;

  const handleSubmit = () => {
    if (loading || !form.name.trim()) {
      return;
    }

    onSubmit({
      name: form.name.trim(),
      description: form.description.trim(),
    });
  };

  return (
    <>
      <DialogTitle sx={{ pr: 7 }}>
        <Typography
          component="div"
          sx={{
            fontFamily,
            fontSize: 20,
            fontWeight: 700,
          }}
        >
          {mode === "create"
            ? `${text.add} ${itemLabel}`
            : `${text.edit} ${itemLabel}`}
        </Typography>

        <IconButton
          size="small"
          disabled={loading}
          onClick={onClose}
          sx={{
            position: "absolute",
            right: 16,
            top: 16,
          }}
        >
          <CloseRoundedIcon />
        </IconButton>
      </DialogTitle>

      <DialogContent>
        <Box
          sx={{
            display: "grid",
            gap: 2,
            pt: 1,
          }}
        >
          <TextField
            fullWidth
            label={`${itemLabel} ${text.name}`}
            value={form.name}
            disabled={loading}
            onChange={(event) =>
              setForm((prev) => ({
                ...prev,
                name: event.target.value,
              }))
            }
            sx={{
              "& .MuiInputBase-root, & .MuiInputLabel-root": {
                fontFamily,
              },
            }}
          />

          {tab === "indicators" && (
            <TextField
              fullWidth
              multiline
              minRows={4}
              label={text.description}
              value={form.description}
              disabled={loading}
              onChange={(event) =>
                setForm((prev) => ({
                  ...prev,
                  description: event.target.value,
                }))
              }
              sx={{
                "& .MuiInputBase-root, & .MuiInputLabel-root": {
                  fontFamily,
                },
              }}
            />
          )}
        </Box>
      </DialogContent>

      <DialogActions
        sx={{
          px: 3,
          pb: 3,
        }}
      >
        <Button
          disabled={loading}
          onClick={onClose}
          variant="outlined"
          color="inherit"
          sx={{
            fontFamily,
            textTransform: "none",
          }}
        >
          {text.cancel}
        </Button>

        <Button
          disabled={loading || !form.name.trim()}
          onClick={handleSubmit}
          variant="contained"
          sx={{
            fontFamily,
            textTransform: "none",
          }}
        >
          {mode === "create" ? text.create : text.save}
        </Button>
      </DialogActions>
    </>
  );
}

export function MasterDataDialog({
  open,
  mode,
  tab,
  initialValue,
  loading = false,
  language = "en",
  fontFamily,
  onClose,
  onSubmit,
}: Props) {
  const handleClose = () => {
    if (loading) {
      return;
    }

    onClose();
  };

  // Changing this key remounts only the dialog form when:
  // - create/edit mode changes
  // - selected item changes
  // - language changes
  //
  // This avoids calling setState synchronously inside useEffect.
  const formKey = [
    mode,
    tab,
    initialValue?.name ?? "new",
    initialValue?.description ?? "",
    language,
  ].join("|");

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      fullWidth
      maxWidth="sm"
      slotProps={{
        paper: {
          sx: {
            borderRadius: 3,
            border: "1px solid",
            borderColor: "divider",
            backgroundImage: "none",
            fontFamily,
          },
        },
      }}
    >
      {open && (
        <MasterDataDialogForm
          key={formKey}
          mode={mode}
          tab={tab}
          initialValue={initialValue ?? emptyValue}
          loading={loading}
          language={language}
          fontFamily={fontFamily}
          onClose={handleClose}
          onSubmit={onSubmit}
        />
      )}
    </Dialog>
  );
}