"use client";

import { useMemo, useState, type ReactNode } from "react";

import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import FormControlLabel from "@mui/material/FormControlLabel";
import IconButton from "@mui/material/IconButton";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import CloseIcon from "@mui/icons-material/Close";

import { AppButton, AppSecondaryButton } from "@/components/ui/button";
import { EditorBox } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/editor-box";

const DRAWER_Z_INDEX = 1750;

export type EvaluationResolvedStatus = "RESOLVED" | "NOT_RESOLVED";

export type ProgressReportEvaluationItem = {
  id: number;
  title: string;
  resolvedStatus: EvaluationResolvedStatus | "";
  feedback: string;
};

export type ProgressReportEvaluationSubmitPayload = {
  issues: ProgressReportEvaluationItem[];
  decisions: ProgressReportEvaluationItem[];
};

// Static Figma evaluation form copy (node 38607:369136).
const STATIC_EVALUATION_ISSUES = [
  "Import of frozen meat and offal",
  "Climate issue",
  "Joint inspection",
] as const;

const STATIC_EVALUATION_DECISIONS = [
  "Organizing agricultural communities.",
  "Law on Contract Farming & Agricultural Production.",
  "Implement the letter of the Committee of Economic and Financial Policy No. 11033 MEF.SEC",
] as const;

type Props = {
  open: boolean;
  onClose: () => void;
  onSubmit?: (
    payload: ProgressReportEvaluationSubmitPayload,
  ) => void | Promise<void>;
};

function RequiredFieldLabel({ children }: { children: ReactNode }) {
  return (
    <Typography
      sx={{
        fontSize: 13,
        fontWeight: 500,
        color: "#414651",
        mb: "14px",
        lineHeight: 1.4,
      }}
    >
      {children}
      <Typography component="span" sx={{ color: "#f04438" }}>
        *
      </Typography>
    </Typography>
  );
}

function hasFeedbackContent(value: string) {
  return value
    .replace(/<[^>]*>/g, " ")
    .replace(/&nbsp;/g, " ")
    .replace(/\s+/g, " ")
    .trim().length > 0;
}

function createStaticItems(titles: readonly string[]): ProgressReportEvaluationItem[] {
  return titles.map((title, index) => ({
    id: index + 1,
    title,
    resolvedStatus: "",
    feedback: "",
  }));
}

function EvaluationItemCard({
  index,
  item,
  onChange,
}: {
  index: number;
  item: ProgressReportEvaluationItem;
  onChange: (next: ProgressReportEvaluationItem) => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: "16px" }}>
      <Typography
        sx={{
          fontSize: 14,
          fontWeight: 600,
          color: isDark ? "#f9fafb" : "#181d27",
          lineHeight: "20px",
        }}
      >
        Issue {index + 1}: {item.title}
      </Typography>

      <Box>
        <RequiredFieldLabel>
          តើបញ្ហានេះបានដោះស្រាយមែនឬទេ?{" "}
        </RequiredFieldLabel>

        <RadioGroup
          value={item.resolvedStatus}
          onChange={(event) =>
            onChange({
              ...item,
              resolvedStatus: event.target.value as EvaluationResolvedStatus,
            })
          }
          sx={{ gap: 0.5 }}
        >
          <FormControlLabel
            value="RESOLVED"
            control={
              <Radio
                size="small"
                sx={{
                  color: "#1a64a8",
                  "&.Mui-checked": { color: "#1a64a8" },
                }}
              />
            }
            label="បានដោះស្រាយ"
            sx={{
              m: 0,
              "& .MuiFormControlLabel-label": {
                fontSize: 13,
                fontWeight: 500,
                color: isDark ? "#d0d5dd" : "#252b37",
              },
            }}
          />
          <FormControlLabel
            value="NOT_RESOLVED"
            control={
              <Radio
                size="small"
                sx={{
                  color: "#1a64a8",
                  "&.Mui-checked": { color: "#1a64a8" },
                }}
              />
            }
            label="មិនទាន់បានដោះស្រាយ"
            sx={{
              m: 0,
              "& .MuiFormControlLabel-label": {
                fontSize: 13,
                fontWeight: 500,
                color: isDark ? "#d0d5dd" : "#252b37",
              },
            }}
          />
        </RadioGroup>
      </Box>

      <Box>
        <RequiredFieldLabel>Any Feedback</RequiredFieldLabel>
        <Box
          sx={{
            "& > div": {
              minHeight: 220,
              borderWidth: "1.5px",
              borderRadius: "8px",
            },
            "& textarea": {
              fontSize: "13px !important",
            },
            "& textarea::placeholder": {
              color: "#9f9f9f !important",
            },
          }}
        >
          <EditorBox
            placeholder="Write description ........."
            value={item.feedback}
            onChange={(feedback) => onChange({ ...item, feedback })}
          />
        </Box>
      </Box>
    </Box>
  );
}

function EvaluationSection({
  title,
  items,
  onChangeItem,
}: {
  title: string;
  items: ProgressReportEvaluationItem[];
  onChangeItem: (id: number, next: ProgressReportEvaluationItem) => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: "22px" }}>
      <Typography
        sx={{
          fontSize: 18,
          fontWeight: 600,
          color: isDark ? "#f9fafb" : "#181d27",
          lineHeight: "22px",
        }}
      >
        {title}
      </Typography>

      <Box sx={{ display: "flex", flexDirection: "column", gap: "16px" }}>
        {items.map((item, index) => (
          <EvaluationItemCard
            key={`${title}-${item.id}`}
            index={index}
            item={item}
            onChange={(next) => onChangeItem(item.id, next)}
          />
        ))}
      </Box>
    </Box>
  );
}

function ProgressReportEvaluationDrawerContent({
  onClose,
  onSubmit,
}: {
  onClose: () => void;
  onSubmit?: (
    payload: ProgressReportEvaluationSubmitPayload,
  ) => void | Promise<void>;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [issueItems, setIssueItems] = useState(() =>
    createStaticItems(STATIC_EVALUATION_ISSUES),
  );
  const [decisionItems, setDecisionItems] = useState(() =>
    createStaticItems(STATIC_EVALUATION_DECISIONS),
  );
  const [submitting, setSubmitting] = useState(false);

  const canSubmit = useMemo(() => {
    const allItems = [...issueItems, ...decisionItems];

    return allItems.every(
      (item) =>
        Boolean(item.resolvedStatus) && hasFeedbackContent(item.feedback),
    );
  }, [decisionItems, issueItems]);

  async function handleSubmit() {
    if (!canSubmit) return;

    setSubmitting(true);

    try {
      await onSubmit?.({
        issues: issueItems,
        decisions: decisionItems,
      });
      onClose();
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        minHeight: 0,
      }}
    >
      <Box
        sx={{
          height: 67,
          px: "22px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          borderBottom: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"}`,
          flexShrink: 0,
        }}
      >
        <Typography
          sx={{
            fontSize: 20,
            fontWeight: 500,
            color: isDark ? "#f9fafb" : "#0a0a0a",
            letterSpacing: "-0.4px",
            lineHeight: 1.2,
          }}
        >
          Evaluation Form
        </Typography>

        <IconButton onClick={onClose} size="small" sx={{ color: "#717680" }}>
          <CloseIcon sx={{ fontSize: 24 }} />
        </IconButton>
      </Box>

      <Box
        sx={{
          px: 4,
          py: "22px",
          overflowY: "auto",
          flex: 1,
          minHeight: 0,
        }}
      >
        <Box sx={{ display: "flex", flexDirection: "column", gap: 4 }}>
          <EvaluationSection
            title="Issues"
            items={issueItems}
            onChangeItem={(id, next) =>
              setIssueItems((current) =>
                current.map((item) => (item.id === id ? next : item)),
              )
            }
          />

          <EvaluationSection
            title="RGC Decision"
            items={decisionItems}
            onChangeItem={(id, next) =>
              setDecisionItems((current) =>
                current.map((item) => (item.id === id ? next : item)),
              )
            }
          />
        </Box>
      </Box>

      <Box
        sx={{
          height: 84,
          px: "22px",
          display: "flex",
          alignItems: "center",
          justifyContent: "flex-end",
          gap: "22px",
          borderTop: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#f5f5f5"}`,
          flexShrink: 0,
          bgcolor: isDark ? "#101828" : "#ffffff",
        }}
      >
        <AppSecondaryButton
          onClick={onClose}
          sx={{
            minWidth: 150,
            width: 150,
            height: 40,
            borderColor: "#d5d7da",
            color: "#153858",
          }}
        >
          Cancel
        </AppSecondaryButton>

        <AppButton
          disabled={!canSubmit || submitting}
          onClick={() => void handleSubmit()}
          sx={{
            minWidth: 150,
            width: 150,
            height: 40,
            bgcolor: canSubmit ? "#1a64a8" : "#717680",
            "&:hover": {
              bgcolor: canSubmit ? "#155a96" : "#717680",
            },
            "&.Mui-disabled": {
              bgcolor: "#717680",
              color: "#ffffff",
            },
          }}
        >
          {submitting ? "Submitting..." : "Submit"}
        </AppButton>
      </Box>
    </Box>
  );
}

export function ProgressReportEvaluationDrawer({
  open,
  onClose,
  onSubmit,
}: Props) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      sx={{
        zIndex: DRAWER_Z_INDEX,
        "& .MuiBackdrop-root": { bgcolor: "rgba(0, 0, 0, 0.35)" },
        "& .MuiDrawer-paper": {
          width: { xs: "100vw", sm: 795 },
          maxWidth: "100vw",
          bgcolor: isDark ? "#101828" : "#ffffff",
          borderTopLeftRadius: { xs: 0, sm: 16 },
          borderBottomLeftRadius: { xs: 0, sm: 12 },
          boxShadow: "none",
        },
      }}
    >
      {open ? (
        <ProgressReportEvaluationDrawerContent
          key="static-evaluation-form"
          onClose={onClose}
          onSubmit={onSubmit}
        />
      ) : null}
    </Drawer>
  );
}
