import { FC, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { CodeEditor } from "@/components/CodeEditor";
import { CODE_LANG } from "@/components/CodeEditor/CodeMirror/extensions/interface";
import { VALIDATION_TYPES } from "@/utils/validationFactory";
import { RecordEditorProps } from "./interface";
import {
  applyRecordEditorContainerStyle,
  recordEditorLabelStyle,
  recordEditorStyle,
  recordKeyStyle,
  recordStyle,
  subLabelStyle,
} from "./style";
import Button from "@mui/material/Button";
import Input from "@mui/material/Input";
import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/Delete";
import { useTheme } from "@mui/material";

export const RecordEditor: FC<RecordEditorProps> = (props) => {
  const {
    fillOnly,
    name,
    records,
    customRender,
    label,
    subLabel,
    onSubLabelClick,
    onDelete,
    onAdd,
    withoutCodeMirror,
    onChangeKey,
    onChangeValue,
    valueInputType,
  } = props;

  const { t } = useTranslation();
  const theme = useTheme()
  const valueExpectedType = useMemo(
    () =>
      valueInputType
        ? valueInputType === VALIDATION_TYPES.ANY
          ? undefined
          : valueInputType
        : VALIDATION_TYPES.STRING,
    [valueInputType]
  );

  const recordList = useMemo(() => {
    return (
      <>
        {records?.map((record, index) => {
          if (customRender) {
            return (
              <div css={recordStyle} key={index}>
                {customRender(record, index, fillOnly)}
                <Button
                  type="button"
                  variant="outlined"
                  onClick={() => {
                    onDelete?.(index, record, name);
                  }}
                  endIcon={<DeleteIcon />}
                />
              </div>
            );
          }
          return (
            <div css={recordStyle} key={index}>
              {withoutCodeMirror ? (
                <Input
                  sx={{
                    height: "32px",
                    minW: "160px",
                    bdRadius: "8px 0 0 8px",
                    width: "0",
                  }}
                  placeholder="key"
                  value={record.key}
                  readOnly={fillOnly}
                  onChange={(e) => {
                    onChangeKey?.(
                      index,
                      e.target.value.trim(),
                      record.value,
                      name
                    );
                  }}
                />
              ) : (
                <CodeEditor
                  scopeOfAutoComplete="page"
                wrapperCss={recordKeyStyle}
                  // height="32px"
                  maxHeight="208px"
                  maxWidth="100%"
                  editable={!fillOnly}
                  value={record.key}
                  lang={CODE_LANG.JAVASCRIPT}
                  placeholder="key"
                  expectValueType={VALIDATION_TYPES.STRING}
                  onChange={(value) => {
                    onChangeKey?.(index, value.trim(), record.value, name);
                  }}
                  singleLine
                />
              )}
              {withoutCodeMirror ? (
                <Input
                  sx={{
                    height: "32px",
                    minW: "160px",
                    bdRadius: fillOnly ? "0 8px 8px 0" : "0",
                    width: "0",
                    color: "techPurple",
                  }}
                  placeholder="value"
                  value={record.value}
                  onChange={(e) => {
                    onChangeValue?.(
                      index,
                      record.key,
                      e.target.value.trim(),
                      name
                    );
                  }}
                />
              ) : (
                <CodeEditor
                scopeOfAutoComplete="page"
                // wrapperCss={recordKeyStyle}
                // height="32px"
                maxHeight="208px"
                maxWidth="100%"
                  lang={CODE_LANG.JAVASCRIPT}
                  placeholder="value"
                  value={record.value}
                  expectValueType={valueExpectedType}
                  singleLine
                  onChange={(value) => {
                    onChangeValue?.(index, record.key, value.trim(), name);
                  }}
                />
              )}
              {!fillOnly && (
                <Button
                  type="button"
                  sx={{ bdRadius: "0 8px 8px 0", color: "grayBlue" }}
                  variant="outlined"
                  onClick={() => {
                    onDelete?.(index, record, name);
                  }}
                  endIcon={<DeleteIcon />}
                />
              )}
            </div>
          );
        })}
      </>
    );
  }, [
    customRender,
    fillOnly,
    name,
    onChangeKey,
    onChangeValue,
    onDelete,
    records,
    valueExpectedType,
    withoutCodeMirror,
  ]);

  return (
    <div css={applyRecordEditorContainerStyle(label)}>
      {label != "" && (
        <span css={recordEditorLabelStyle(theme)}>
          <span>{label}</span>
          {subLabel && (
            <span css={subLabelStyle(theme)} onClick={onSubLabelClick}>
              {subLabel}
            </span>
          )}
        </span>
      )}

      <div css={recordEditorStyle}>
        {recordList}
        {!fillOnly && (
          <span>
            <Button
              sx={{ mb: "8px", pd: "1px 8px", color: "techPurple" }}
              type="button"
              size="medium"
              variant="text"
              onClick={() => {
                onAdd?.(name);
              }}
              startIcon={
                <AddIcon color="primary" />
              }
            >
              {t("editor.action.panel.btn.new")}
            </Button>
          </span>
        )}
      </div>
    </div>
  );
};

RecordEditor.displayName = "RecordEditor";
