"use client";

import { useRef, useState, type ChangeEvent, type DragEvent } from "react";

import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { alpha, useTheme, type Theme } from "@mui/material/styles";
import type { SelectChangeEvent } from "@mui/material/Select";

import { AppTextEditor } from "@/components/ui/text-editor";
import { AdditionalAgencyFields } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/additional-agency-fields";
import { AgencyDisplay } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/agency-display";
import {
  getBorderColor,
  getInputSx,
  getSelectMenuProps,
  getSelectSx,
} from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-styles";
import type { UploadStatus } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-types";
import { dashboardIssueAgencies } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/dashboard-issue-agencies";
import {
  RequiredLabel,
} from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/form-label";
import { IssueAttachmentField } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/issue-attachment-field";
import { workingGroupOptions } from "@/features/ministry/dashboard/dashboard-data";
import type { MeetingRequestIssue } from "@/features/ministry/meeting-request/meeting-request-data";

const POPUP_Z_INDEX = 1700;
const SELECT_MENU_Z_INDEX = POPUP_Z_INDEX + 100;
const FIELD_HEIGHT = 50;

const categoryOptions = [
  "Human Resource",
  "Governance",
  "Policy",
  "Market",
  "Trade",
  "Legislation",
  "Procedure",
  "Finance",
  "Digital / IT",
];

export type AddMeetingIssueFormValues = {
  workingGroupName: string;
  governmentAgency: string;
  issue: string;
  category: string;
  description: string;
  recommendation: string;
  secondAgency: string;
  thirdAgency: string;
  fourthAgency: string;
  fifthAgency: string;
  attachment: File | null;
};

type AddIssuePopupProps = {
  open: boolean;
  onClose: () => void;
  onSave: (values: AddMeetingIssueFormValues) => void;
};

const emptyFormValues: AddMeetingIssueFormValues = {
  workingGroupName: workingGroupOptions[0]?.value ?? "",
  governmentAgency: "maff",
  issue: "",
  category: "",
  description: "",
  recommendation: "",
  secondAgency: "",
  thirdAgency: "",
  fourthAgency: "",
  fifthAgency: "",
  attachment: null,
};

function getFieldSx(theme: Theme) {
  return {
    ...getInputSx(theme),
    "& .MuiOutlinedInput-root": {
      ...getInputSx(theme)["& .MuiOutlinedInput-root"],
      height: FIELD_HEIGHT,
      fontSize: 13,
    },
  };
}

function getFieldSelectSx(theme: Theme) {
  return {
    ...getSelectSx(theme),
    height: FIELD_HEIGHT,
    fontSize: 13,
    "& .MuiSelect-select": {
      height: FIELD_HEIGHT,
      py: 0,
      display: "flex",
      alignItems: "center",
    },
  };
}

function getAddIssueSelectMenuProps(theme: Theme) {
  const baseMenuProps = getSelectMenuProps(theme);

  return {
    ...baseMenuProps,
    disableScrollLock: true,
    slotProps: {
      ...baseMenuProps.slotProps,
      root: {
        sx: { zIndex: SELECT_MENU_Z_INDEX },
      },
      paper: {
        ...baseMenuProps.slotProps?.paper,
        sx: {
          ...(baseMenuProps.slotProps?.paper as { sx?: object } | undefined)?.sx,
          zIndex: SELECT_MENU_Z_INDEX,
        },
      },
    },
  };
}

export function mapAddIssueFormToMeetingRequestIssue(
  values: AddMeetingIssueFormValues,
  id: number,
): MeetingRequestIssue {
  const findAgency = (agencyId: string) =>
    dashboardIssueAgencies.find((agency) => agency.id === agencyId);

  const primaryAgency = findAgency(values.governmentAgency);
  const secondAgency = findAgency(values.secondAgency);
  const thirdAgency = findAgency(values.thirdAgency);
  const fourthAgency = findAgency(values.fourthAgency);
  const fifthAgency = findAgency(values.fifthAgency);

  return {
    id,
    issue: values.issue.trim(),
    title: values.issue.trim(),
    category: values.category.trim(),
    description: values.description.trim(),
    recommendation: values.recommendation.trim(),
    primaryAgency: primaryAgency?.name ?? "-",
    primaryAgencyLogo: primaryAgency?.logo ?? null,
    secondAgency: secondAgency?.name ?? "Not Uploaded",
    secondAgencyLogo: secondAgency?.logo ?? null,
    thirdAgency: thirdAgency?.name ?? "Not Uploaded",
    thirdAgencyLogo: thirdAgency?.logo ?? null,
    fourthAgency: fourthAgency?.name ?? "Not Uploaded",
    fourthAgencyLogo: fourthAgency?.logo ?? null,
    fifthAgency: fifthAgency?.name ?? "Not Uploaded",
    fifthAgencyLogo: fifthAgency?.logo ?? null,
    status: "Not Addressed",
  };
}

export function AddIssuePopup({ open, onClose, onSave }: AddIssuePopupProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        zIndex: POPUP_Z_INDEX,
        "& .MuiBackdrop-root": {
          bgcolor: "rgba(0, 0, 0, 0.35)",
        },
      }}
      slotProps={{
        paper: {
          sx: {
            width: 795,
            maxWidth: "calc(100vw - 32px)",
            maxHeight: "calc(100dvh - 32px)",
            m: 2,
            borderRadius: "16px",
            overflow: "hidden",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
            border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#f5f5f5"}`,
            boxShadow: "0px 18px 45px rgba(16, 24, 40, 0.18)",
          },
        },
      }}
    >
      {open ? <AddIssuePopupContent onClose={onClose} onSave={onSave} /> : null}
    </Dialog>
  );
}

function AddIssuePopupContent({
  onClose,
  onSave,
}: Pick<AddIssuePopupProps, "onClose" | "onSave">) {
  const theme = useTheme();
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const [workingGroupName, setWorkingGroupName] = useState(
    emptyFormValues.workingGroupName,
  );
  const [governmentAgency, setGovernmentAgency] = useState(
    emptyFormValues.governmentAgency,
  );
  const [issue, setIssue] = useState("");
  const [category, setCategory] = useState("");
  const [description, setDescription] = useState("");
  const [recommendation, setRecommendation] = useState("");
  const [secondAgency, setSecondAgency] = useState("");
  const [thirdAgency, setThirdAgency] = useState("");
  const [fourthAgency, setFourthAgency] = useState("");
  const [fifthAgency, setFifthAgency] = useState("");
  const [attachment, setAttachment] = useState<File | null>(null);
  const [uploadStatus, setUploadStatus] = useState<UploadStatus>("idle");

  const selectedGovernmentAgency = dashboardIssueAgencies.find(
    (agency) => agency.id === governmentAgency,
  );
  const selectedWorkingGroupLabel =
    workingGroupOptions.find((option) => option.value === workingGroupName)
      ?.label ?? "";

  const isFormFilled =
    workingGroupName.trim() !== "" &&
    governmentAgency.trim() !== "" &&
    issue.trim() !== "" &&
    category.trim() !== "" &&
    description.trim() !== "" &&
    recommendation.trim() !== "";

  const fieldSx = getFieldSx(theme);
  const selectSx = getFieldSelectSx(theme);
  const selectMenuProps = getAddIssueSelectMenuProps(theme);

  function handleSelectedFile(file: File) {
    setAttachment(file);
    setUploadStatus("uploading");

    window.setTimeout(() => {
      setUploadStatus("completed");
    }, 800);
  }

  function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;

    handleSelectedFile(file);
    event.target.value = "";
  }

  function handleDrop(event: DragEvent<HTMLDivElement>) {
    event.preventDefault();

    const file = event.dataTransfer.files?.[0];
    if (!file) return;

    handleSelectedFile(file);
  }

  function handleDragOver(event: DragEvent<HTMLDivElement>) {
    event.preventDefault();
  }

  function handleUploadClick() {
    fileInputRef.current?.click();
  }

  function handleSave() {
    if (!isFormFilled) return;

    onSave({
      workingGroupName: selectedWorkingGroupLabel,
      governmentAgency,
      issue,
      category,
      description,
      recommendation,
      secondAgency,
      thirdAgency,
      fourthAgency,
      fifthAgency,
      attachment,
    });
  }

  return (
    <>
      <Box
        sx={{
          px: 3,
          py: 1.25,
          minHeight: 68,
          display: "flex",
          alignItems: "center",
          borderBottom: `1px solid ${getBorderColor(theme)}`,
        }}
      >
        <Typography
          sx={{
            fontSize: 20,
            fontWeight: 500,
            color: theme.palette.text.primary,
            letterSpacing: "-0.4px",
          }}
        >
          Add Issue
        </Typography>
      </Box>

      <Box
        sx={{
          px: 3,
          py: 2.75,
          overflowY: "auto",
          maxHeight: "calc(100dvh - 220px)",
        }}
      >
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
            gap: "22px",
            mb: "22px",
          }}
        >
          <Box>
            <RequiredLabel>Working Group Name</RequiredLabel>
            <Select
              fullWidth
              size="small"
              value={workingGroupName}
              onChange={(event: SelectChangeEvent) =>
                setWorkingGroupName(event.target.value)
              }
              sx={selectSx}
              MenuProps={selectMenuProps}
            >
              {workingGroupOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          </Box>

          <Box>
            <RequiredLabel>Government Agency</RequiredLabel>
            <Select
              fullWidth
              size="small"
              value={governmentAgency}
              onChange={(event: SelectChangeEvent) =>
                setGovernmentAgency(event.target.value)
              }
              renderValue={() => (
                <AgencyDisplay agency={selectedGovernmentAgency} />
              )}
              sx={selectSx}
              MenuProps={selectMenuProps}
            >
              {dashboardIssueAgencies.map((agency) => (
                <MenuItem key={agency.id} value={agency.id}>
                  <AgencyDisplay agency={agency} />
                </MenuItem>
              ))}
            </Select>
          </Box>
        </Box>

        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
            gap: "22px",
            mb: "22px",
          }}
        >
          <Box>
            <RequiredLabel>Issue</RequiredLabel>
            <TextField
              fullWidth
              size="small"
              value={issue}
              onChange={(event) => setIssue(event.target.value)}
              placeholder="Climate issue"
              sx={fieldSx}
            />
          </Box>

          <Box>
            <RequiredLabel>Category of Issue</RequiredLabel>
            <Select
              fullWidth
              size="small"
              displayEmpty
              value={category}
              onChange={(event: SelectChangeEvent) =>
                setCategory(event.target.value)
              }
              renderValue={(selected) =>
                selected ? (
                  selected
                ) : (
                  <Typography sx={{ fontSize: 13, color: "#a4a7ae" }}>
                    Select Category
                  </Typography>
                )
              }
              sx={selectSx}
              MenuProps={selectMenuProps}
            >
              {categoryOptions.map((option) => (
                <MenuItem key={option} value={option}>
                  {option}
                </MenuItem>
              ))}
            </Select>
          </Box>
        </Box>

        <Box sx={{ mb: "22px" }}>
          <RequiredLabel>Description of the issue</RequiredLabel>
          <AppTextEditor
            placeholder="Write description ........."
            value={description}
            onChange={setDescription}
            minRows={4}
          />
        </Box>

        <Box sx={{ mb: "22px" }}>
          <RequiredLabel>Recommendation</RequiredLabel>
          <AppTextEditor
            placeholder="Write Recommendation........."
            value={recommendation}
            onChange={setRecommendation}
            minRows={4}
          />
        </Box>

        <IssueAttachmentField
          attachment={attachment}
          fileInputRef={fileInputRef}
          uploadStatus={uploadStatus}
          onFileChange={handleFileChange}
          onUploadClick={handleUploadClick}
          onDrop={handleDrop}
          onDragOver={handleDragOver}
        />

        <Box sx={{ mt: 1.25 }}>
          <AdditionalAgencyFields
            secondAgency={secondAgency}
            onSecondAgencyChange={setSecondAgency}
            thirdAgency={thirdAgency}
            onThirdAgencyChange={setThirdAgency}
            fourthAgency={fourthAgency}
            onFourthAgencyChange={setFourthAgency}
            fifthAgency={fifthAgency}
            onFifthAgencyChange={setFifthAgency}
            selectMenuProps={selectMenuProps}
          />
        </Box>
      </Box>

      <Box
        sx={{
          px: 3,
          py: 2.5,
          minHeight: 84,
          borderTop: `1px solid ${getBorderColor(theme)}`,
          display: "flex",
          justifyContent: "flex-end",
          alignItems: "center",
          gap: "22px",
        }}
      >
        <Button
          variant="outlined"
          onClick={onClose}
          sx={{
            width: 150,
            minWidth: 150,
            height: 40,
            borderRadius: "6px",
            textTransform: "none",
            fontSize: 13,
            fontWeight: 500,
            color: "#153858",
            borderColor: "#d5d7da",
            bgcolor: theme.palette.background.paper,
            "&:hover": {
              borderColor: "#1a64a8",
              bgcolor: alpha("#1a64a8", 0.04),
            },
          }}
        >
          Cancel
        </Button>

        <Button
          variant="contained"
          disabled={!isFormFilled}
          onClick={handleSave}
          sx={{
            width: 150,
            minWidth: 150,
            height: 40,
            borderRadius: "6px",
            textTransform: "none",
            fontSize: 13,
            fontWeight: 500,
            boxShadow: "none",
            bgcolor: isFormFilled ? "#1a64a8" : "#bdbdbd",
            color: "#ffffff",
            "&:hover": {
              bgcolor: isFormFilled ? "#155489" : "#bdbdbd",
              boxShadow: "none",
            },
            "&.Mui-disabled": {
              bgcolor: "#bdbdbd",
              color: "#ffffff",
            },
          }}
        >
          Save
        </Button>
      </Box>
    </>
  );
}
