"use client";

import { useState } from "react";

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

import { AppButton, AppCancelButton } from "@/components/ui/button";
import type { ParticipantGroup } from "@/features/ministry/meeting-summary/components/meeting-summary-participants-table";
import type { MeetingSummaryParticipants } from "@/features/ministry/meeting-summary/components/view-meeting-summary/view-meeting-summary-data";
import {
  getBorderColor,
  getInputSx,
} from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-styles";

type Props = {
  open: boolean;
  participants: MeetingSummaryParticipants;
  onClose: () => void;
  onSave: (participants: MeetingSummaryParticipants) => Promise<void>;
  saveError?: string | null;
  group?: ParticipantGroup | null;
};

type ParticipantField = {
  key: keyof MeetingSummaryParticipants;
  label: string;
  placeholder: string;
};

const PARTICIPANT_FIELDS: Record<ParticipantGroup, ParticipantField[]> = {
  pswg: [
    {
      key: "pswgReporter",
      label: "Reporter Name",
      placeholder: "Enter reporter name",
    },
    {
      key: "pswgReporterPosition",
      label: "Reporter Position",
      placeholder: "Enter reporter position",
    },
    {
      key: "pswgRepresentative",
      label: "Representative Name",
      placeholder: "Enter representative name",
    },
    {
      key: "pswgRepresentativePosition",
      label: "Representative Position",
      placeholder: "Enter representative position",
    },
  ],
  ministry: [
    {
      key: "ministryReporter",
      label: "Reporter Name",
      placeholder: "Enter reporter name",
    },
    {
      key: "ministryReporterPosition",
      label: "Reporter Position",
      placeholder: "Enter reporter position",
    },
    {
      key: "ministryRepresentative",
      label: "Representative Name",
      placeholder: "Enter representative name",
    },
    {
      key: "ministryRepresentativePosition",
      label: "Representative Position",
      placeholder: "Enter representative position",
    },
  ],
};

function ParticipantSection({
  group,
  participants,
  onChange,
}: {
  group: ParticipantGroup;
  participants: MeetingSummaryParticipants;
  onChange: (participants: MeetingSummaryParticipants) => void;
}) {
  const theme = useTheme();
  const title = group === "pswg" ? "PSWG Participants" : "Ministry Participants";

  function updateValue(key: keyof MeetingSummaryParticipants, value: string) {
    onChange({ ...participants, [key]: value });
  }

  return (
    <Box>
      <Typography
        sx={{
          mb: 2,
          fontSize: 16,
          fontWeight: 700,
          color: theme.palette.text.primary,
        }}
      >
        {title}
      </Typography>

      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: { xs: "1fr", sm: "repeat(2, minmax(0, 1fr))" },
          gap: 2,
        }}
      >
        {PARTICIPANT_FIELDS[group].map((field) => (
          <Box key={field.key}>
            <Typography
              component="label"
              htmlFor={field.key}
              sx={{
                display: "block",
                mb: 0.75,
                fontSize: 13,
                fontWeight: 600,
                color: theme.palette.text.primary,
              }}
            >
              {field.label}
            </Typography>
            <TextField
              id={field.key}
              fullWidth
              size="small"
              value={participants[field.key]}
              onChange={(event) => updateValue(field.key, event.target.value)}
              placeholder={field.placeholder}
              slotProps={{ htmlInput: { maxLength: 255 } }}
              sx={getInputSx(theme)}
            />
          </Box>
        ))}
      </Box>
    </Box>
  );
}

function MeetingSummaryParticipantsDialogContent({
  participants,
  onClose,
  onSave,
  saveError,
  group,
}: Omit<Props, "open">) {
  const theme = useTheme();
  const [draftParticipants, setDraftParticipants] = useState(participants);
  const [saving, setSaving] = useState(false);
  const title = group
    ? `Update ${group === "pswg" ? "PSWG" : "Ministry"} Participants`
    : "Add Participants";
  const visibleGroups: ParticipantGroup[] = group ? [group] : ["pswg", "ministry"];

  async function handleSave() {
    setSaving(true);

    try {
      await onSave(draftParticipants);
      onClose();
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <Box
        sx={{
          px: 2,
          py: 1.6,
          borderBottom: `1px solid ${getBorderColor(theme)}`,
          bgcolor: theme.palette.background.paper,
        }}
      >
        <Typography
          sx={{
            fontSize: 18,
            fontWeight: 700,
            color: theme.palette.text.primary,
          }}
        >
          {title}
        </Typography>
      </Box>

      <Box
        sx={{
          flex: 1,
          px: 2,
          py: 2,
          overflowY: "auto",
          bgcolor: theme.palette.background.paper,
        }}
      >
        {visibleGroups.map((participantGroup, index) => (
          <Box key={participantGroup} sx={{ mb: index === 0 && visibleGroups.length > 1 ? 4 : 0 }}>
            <ParticipantSection
              group={participantGroup}
              participants={draftParticipants}
              onChange={setDraftParticipants}
            />
          </Box>
        ))}
      </Box>

      <Box
        sx={{
          px: 2,
          py: 1.8,
          borderTop: `1px solid ${getBorderColor(theme)}`,
          bgcolor: theme.palette.background.paper,
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-end",
          gap: 1,
        }}
      >
        {saveError ? (
          <Typography sx={{ width: "100%", fontSize: 12, color: "#f04438" }}>
            {saveError}
          </Typography>
        ) : null}

        <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1.5 }}>
          <AppCancelButton
            disabled={saving}
            onClick={onClose}
            sx={{ minWidth: 150, width: 150 }}
          >
            Cancel
          </AppCancelButton>
          <AppButton
            disabled={saving}
            onClick={() => void handleSave()}
            sx={{ minWidth: 150, width: 150 }}
          >
            {saving ? "Saving..." : "Save"}
          </AppButton>
        </Box>
      </Box>
    </>
  );
}

export function MeetingSummaryParticipantsDialog({
  open,
  participants,
  onClose,
  onSave,
  saveError,
  group,
}: Props) {
  const theme = useTheme();

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        "& .MuiDialog-container": {
          justifyContent: "flex-end",
          alignItems: "flex-start",
        },
        "& .MuiBackdrop-root": { bgcolor: "rgba(0, 0, 0, 0.35)" },
      }}
      slotProps={{
        paper: {
          sx: {
            mt: 0,
            mr: 0,
            width: 700,
            maxWidth: "95vw",
            height: { xs: "auto", md: "calc(100dvh - 16px)" },
            maxHeight: "calc(100dvh - 16px)",
            borderRadius: "10px",
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
            backgroundImage: "none",
          },
        },
      }}
    >
      {open ? (
        <MeetingSummaryParticipantsDialogContent
          key={`${group ?? "all"}-${JSON.stringify(participants)}`}
          participants={participants}
          onClose={onClose}
          onSave={onSave}
          saveError={saveError}
          group={group}
        />
      ) : null}
    </Dialog>
  );
}
