"use client";

import { useEffect, useState } from "react";

import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { HyperlinkIcon, Users } from "@/components/ui/icon";
import type { MeetingRequest } from "@/features/ministry/meeting-request/meeting-request-data";
import { getMeetingRequests } from "@/features/ministry/meeting-request/service/meeting-requests-service";

const POPOVER_Z_INDEX = 1700;

type LinkMeetingRequestPopoverProps = {
  open: boolean;
  selectedIds: number[];
  onClose: () => void;
  onConfirm: (requests: MeetingRequest[]) => void;
};

function MeetingRequestListItem({
  request,
  selected,
  onToggle,
}: {
  request: MeetingRequest;
  selected: boolean;
  onToggle: () => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      component="button"
      type="button"
      onClick={onToggle}
      sx={{
        width: "100%",
        display: "flex",
        alignItems: "flex-start",
        justifyContent: "space-between",
        gap: 1,
        p: "22px",
        border: "none",
        cursor: "pointer",
        textAlign: "left",
        bgcolor: selected
          ? isDark
            ? alpha("#1a64a8", 0.16)
            : "#ddedfb"
          : isDark
            ? "#101828"
            : "#ffffff",
        borderTop: selected
          ? `1px solid ${isDark ? alpha("#1a64a8", 0.4) : "#b6dbf6"}`
          : "none",
        borderBottom: `1px solid ${
          selected
            ? isDark
              ? alpha("#1a64a8", 0.4)
              : "#b6dbf6"
            : isDark
              ? alpha("#ffffff", 0.08)
              : "#e9eaeb"
        }`,
        transition: "background-color 0.15s ease",
        "&:hover": {
          bgcolor: selected
            ? isDark
              ? alpha("#1a64a8", 0.22)
              : "#d4e8fa"
            : isDark
              ? alpha("#ffffff", 0.04)
              : "#fafafa",
        },
      }}
    >
      <Box
        sx={{
          display: "flex",
          gap: "14px",
          alignItems: "flex-start",
          minWidth: 0,
        }}
      >
        <Box
          sx={{
            width: 24,
            height: 24,
            borderRadius: "4px",
            bgcolor: "#1a64a8",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
            color: "#ffffff",
          }}
        >
          <HyperlinkIcon sx={{ fontSize: 16 }} />
        </Box>

        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            gap: "15px",
            minWidth: 0,
            maxWidth: 248,
          }}
        >
          <Typography
            className="font-kh"
            sx={{
              fontSize: 12,
              fontWeight: 500,
              color: isDark ? "#f3f4f6" : "#000000",
              lineHeight: 1.4,
              wordBreak: "break-word",
            }}
          >
            {request.title}
          </Typography>

          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 1,
              minWidth: 0,
            }}
          >
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: "5px",
                flexShrink: 0,
              }}
            >
              <Users sx={{ fontSize: 20, color: "#717680" }} />
              <Typography
                sx={{
                  fontSize: 12,
                  fontWeight: 500,
                  color: "#717680",
                  whiteSpace: "nowrap",
                }}
              >
                PSWG :
              </Typography>
            </Box>

            <Typography
              noWrap
              sx={{
                fontSize: 12,
                fontWeight: 500,
                color: isDark ? "#f3f4f6" : "#181d27",
                overflow: "hidden",
                textOverflow: "ellipsis",
              }}
            >
              {request.privateSectorWG?.trim() || "-"}
            </Typography>
          </Box>
        </Box>
      </Box>

      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 1,
          flexShrink: 0,
        }}
      >
        <Typography
          sx={{
            fontSize: 12,
            fontWeight: 500,
            color: "#717680",
            whiteSpace: "nowrap",
          }}
        >
          {request.requestedDate}
        </Typography>

        <Box
          sx={{
            width: 7,
            height: 7,
            borderRadius: "50%",
            bgcolor: "#1a64a8",
            flexShrink: 0,
          }}
        />
      </Box>
    </Box>
  );
}

export function LinkMeetingRequestPopover({
  open,
  selectedIds,
  onClose,
  onConfirm,
}: LinkMeetingRequestPopoverProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      sx={{
        zIndex: POPOVER_Z_INDEX,
        "& .MuiBackdrop-root": {
          bgcolor: "rgba(0, 0, 0, 0.35)",
        },
      }}
      slotProps={{
        paper: {
          sx: {
            width: 454,
            maxWidth: "calc(100vw - 32px)",
            m: 2,
            borderRadius: "12px",
            bgcolor: isDark ? "#101828" : "#ffffff",
            border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"}`,
            boxShadow: "0px 18px 45px rgba(16, 24, 40, 0.18)",
            overflow: "hidden",
          },
        },
      }}
    >
      {open ? (
        <LinkMeetingRequestPopoverContent
          selectedIds={selectedIds}
          onClose={onClose}
          onConfirm={onConfirm}
        />
      ) : null}
    </Dialog>
  );
}

function LinkMeetingRequestPopoverContent({
  selectedIds,
  onClose,
  onConfirm,
}: Pick<
  LinkMeetingRequestPopoverProps,
  "selectedIds" | "onClose" | "onConfirm"
>) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [requests, setRequests] = useState<MeetingRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [draftIds, setDraftIds] = useState<number[]>(() => selectedIds);

  useEffect(() => {
    let cancelled = false;

    void getMeetingRequests()
      .then((data) => {
        if (!cancelled) {
          setRequests(data);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setError("Unable to load meeting requests.");
          setRequests([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, []);

  const toggleRequest = (id: number) => {
    setDraftIds((current) =>
      current.includes(id)
        ? current.filter((item) => item !== id)
        : [...current, id],
    );
  };

  const handleConfirm = () => {
    const selectedRequests = requests.filter((item) =>
      draftIds.includes(item.id),
    );

    onConfirm(selectedRequests);
    onClose();
  };

  return (
    <>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          px: "22px",
          pt: "24px",
          pb: "18px",
        }}
      >
        <Typography
          sx={{
            fontSize: 18,
            fontWeight: 500,
            color: isDark ? "#f3f4f6" : "#000000",
            letterSpacing: "-0.36px",
          }}
        >
          All Meeting Requests
        </Typography>

        <Button
          variant="contained"
          disabled={draftIds.length === 0}
          onClick={handleConfirm}
          sx={{
            minHeight: 35,
            px: 1.5,
            borderRadius: "6px",
            bgcolor: "#1a64a8",
            color: "#edf8fd",
            boxShadow: "none",
            textTransform: "none",
            fontSize: 13,
            fontWeight: 500,
            lineHeight: 1,
            "&:hover": {
              bgcolor: "#155489",
              boxShadow: "none",
            },
            "&.Mui-disabled": {
              bgcolor: alpha("#1a64a8", 0.4),
              color: alpha("#edf8fd", 0.7),
            },
          }}
        >
          Add now
        </Button>
      </Box>

      <Box
        sx={{
          borderTop: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#e9eaeb"}`,
          maxHeight: 420,
          overflowY: "auto",
        }}
      >
        {loading ? (
          <Box
            sx={{
              minHeight: 120,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: 1,
            }}
          >
            <CircularProgress size={18} />
            <Typography sx={{ fontSize: 13, color: "#717680" }}>
              Loading meeting requests...
            </Typography>
          </Box>
        ) : null}

        {!loading && error ? (
          <Typography sx={{ p: 2.75, fontSize: 13, color: "error.main" }}>
            {error}
          </Typography>
        ) : null}

        {!loading && !error && requests.length === 0 ? (
          <Typography sx={{ p: 2.75, fontSize: 13, color: "#717680" }}>
            No meeting requests available.
          </Typography>
        ) : null}

        {!loading &&
          !error &&
          requests.map((request) => (
            <MeetingRequestListItem
              key={request.id}
              request={request}
              selected={draftIds.includes(request.id)}
              onToggle={() => toggleRequest(request.id)}
            />
          ))}
      </Box>
    </>
  );
}
