"use client";

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

import Box from "@mui/material/Box";
import Dialog from "@mui/material/Dialog";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";

import { getFormBorderColor } from "@/components/ui/form";
import { AdditionalAgencyFields } from "@/features/pswg/plenary/components/add-issue-dialog/additional-agency-fields";
import type {
  AddIssueDialogProps,
  UploadStatus,
} from "@/features/pswg/plenary/components/add-issue-dialog/add-issue-dialog-types";
import { DialogFooter } from "@/features/pswg/plenary/components/add-issue-dialog/dialog-footer";
import { IssueAttachmentField } from "@/features/pswg/plenary/components/add-issue-dialog/issue-attachment-field";
import { PlenaryIssueMainFields } from "@/features/pswg/plenary/components/add-issue-dialog/plenary-issue-main-fields";

export default function AddIssueDialog({ open, onClose }: AddIssueDialogProps) {
  const theme = useTheme();

  const [workingGroupName, setWorkingGroupName] = useState(
    "Agriculture and Agro-Industry",
  );
  const [governmentAgency, setGovernmentAgency] = useState("maff");
  const [issue, setIssue] = 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 fileInputRef = useRef<HTMLInputElement | null>(null);

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

  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();
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        "& .MuiDialog-container": {
          justifyContent: "flex-end",
          alignItems: "flex-start",
        },
      }}
      slotProps={{
        paper: {
          sx: {
            mt: 0,
            mr: 0,
            width: 700,
            maxWidth: "95vw",
            maxHeight: "calc(100vh - 16px)",
            borderRadius: "10px",
            overflow: "hidden",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
          },
        },
      }}
    >
      <Box
        sx={{
          px: 2,
          py: 1.6,
          borderBottom: `1px solid ${getFormBorderColor(theme)}`,
          bgcolor: theme.palette.background.paper,
        }}
      >
        <Typography
          sx={{
            fontSize: 18,
            fontWeight: 700,
            color: theme.palette.text.primary,
          }}
        >
          Add Issue
        </Typography>
      </Box>

      <Box
        sx={{
          px: 2,
          py: 1.8,
          overflowY: "auto",
          maxHeight: "calc(100vh - 150px)",
          bgcolor: theme.palette.background.paper,
        }}
      >
        <PlenaryIssueMainFields
          workingGroupName={workingGroupName}
          onWorkingGroupNameChange={setWorkingGroupName}
          governmentAgency={governmentAgency}
          onGovernmentAgencyChange={setGovernmentAgency}
          issue={issue}
          onIssueChange={setIssue}
          description={description}
          onDescriptionChange={setDescription}
          recommendation={recommendation}
          onRecommendationChange={setRecommendation}
        />

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

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

      <DialogFooter isFormFilled={isFormFilled} onClose={onClose} />
    </Dialog>
  );
}
