"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 "./additional-agency-fields";
import type {
  AddIssueDialogProps,
  UploadStatus,
} from "./add-issue-dialog-types";
import { DialogFooter } from "./dialog-footer";
import { IssueAttachmentField } from "./issue-attachment-field";
import { PlenaryIssueMainFields } from "./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 resetForm() {
    setWorkingGroupName("Agriculture and Agro-Industry");
    setGovernmentAgency("maff");
    setIssue("");
    setDescription("");
    setRecommendation("");

    setSecondAgency("");
    setThirdAgency("");
    setFourthAgency("");
    setFifthAgency("");

    setAttachment(null);
    setUploadStatus("idle");
  }

  function handleClose() {
    resetForm();
    onClose();
  }

  function handleSelectedFile(file: File) {
    const allowedTypes = [
      "application/pdf",
      "image/jpeg",
      "image/png",
      "image/webp",
    ];

    const maxFileSize = 1024 * 1024;

    if (!allowedTypes.includes(file.type)) {
      window.alert(
        "Only PDF, JPG, PNG, and WEBP files are allowed."
      );
      return;
    }

    if (file.size > maxFileSize) {
      window.alert("File size must not exceed 1 MB.");
      return;
    }

    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) {
      window.alert("Please complete all required fields.");
      return;
    }

    const selectedAgencies = [
      governmentAgency,
      secondAgency,
      thirdAgency,
      fourthAgency,
      fifthAgency,
    ].filter(Boolean);

    const uniqueAgencies = new Set(selectedAgencies);

    if (uniqueAgencies.size !== selectedAgencies.length) {
      window.alert(
        "The same agency cannot be selected more than once."
      );
      return;
    }

    console.log({
      workingGroupName,
      governmentAgency,
      issue,
      description,
      recommendation,
      secondAgency,
      thirdAgency,
      fourthAgency,
      fifthAgency,
      attachment,
    });

    handleClose();
  }

  function handleDraft() {
    console.log({
      status: "draft",
      workingGroupName,
      governmentAgency,
      issue,
      description,
      recommendation,
      secondAgency,
      thirdAgency,
      fourthAgency,
      fifthAgency,
      attachment,
    });

    handleClose();
  }

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        "& .MuiDialog-container": {
          justifyContent: "flex-end",
          alignItems: "flex-start",
        },
      }}
      slotProps={{
        backdrop: {
          sx: {
            backgroundColor:
              theme.palette.mode === "dark"
                ? "rgba(0, 0, 0, 0.6)"
                : "rgba(15, 23, 42, 0.28)",
          },
        },
        paper: {
          sx: {
            mt: 0,
            mr: 0,
            width: {
              xs: "100%",
              sm: 700,
            },
            maxWidth: "100vw",
            height: {
              xs: "100dvh",
              sm: "auto",
            },
            maxHeight: {
              xs: "100dvh",
              sm: "calc(100vh - 16px)",
            },
            borderRadius: {
              xs: 0,
              sm: "10px",
            },
            overflow: "hidden",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
            backgroundImage: "none",
          },
        },
      }}
    >
      <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={{
          flex: 1,
          px: 2,
          py: 1.8,
          overflowY: "auto",
          maxHeight: {
            xs: "calc(100dvh - 125px)",
            sm: "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={handleClose}
        onDraft={handleDraft}
        onSave={handleSave}
      />
    </Dialog>
  );
}