import {
  Alert,
  Badge,
  Button,
  Divider,
  Group,
  List,
  Modal,
  Select,
  Stack,
  TagsInput,
  Text,
  Textarea,
} from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useEffect, useMemo, useState } from "react";
import { ARCHIVE_CC_ADDRESS } from "@/lib/features/account-deletion/query";
import type {
  AccountSearchResult,
  DeletionConfig,
  DeletionRegion,
  DeletionStatus,
} from "@/lib/features/account-deletion/query";

export interface DeletionRequest {
  statusID: string;
  reason: string;
  killLogin: boolean;
  revokeSessions: boolean;
  softDelete: boolean;
  region: DeletionRegion;
  ccRecipients: string[];
  noticeTemplateID: string;
  followupTemplateID: string;
}

export interface TemplateOption {
  id: string;
  name: string;
}

interface Props {
  opened: boolean;
  account: AccountSearchResult | null;
  statuses: DeletionStatus[];
  missingStatusIDs: string[];
  statusesLoading: boolean;
  submitting: boolean;
  templates: TemplateOption[];
  templatesLoading: boolean;
  config: DeletionConfig | null;
  onClose: () => void;
  onConfirm: (request: DeletionRequest) => void;
}

const MIN_REASON = 10;

const DEFAULT_VALUE = "";

const REGION_OPTIONS: Array<{ value: DeletionRegion; label: string }> = [
  { value: "europe", label: "Europe" },
  { value: "india", label: "India" },
  { value: "indonesia", label: "Indonesia" },
  { value: "uk", label: "United Kingdom" },
  { value: "others", label: "Rest of world" },
];

const templateOptions = (
  templates: TemplateOption[],
  regionalDefault: { id: string; name: string } | undefined,
) => [
    {
      value: DEFAULT_VALUE,
      label: regionalDefault
        ? `Regional letter — ${regionalDefault.name}`
        : "Regional letter for this region",
    },
    ...templates
      .filter((template) => template.id !== regionalDefault?.id)
      .map((template) => ({ value: template.id, label: template.name })),
  ];

const DeleteAccountModal: React.FC<Props> = ({
  opened,
  account,
  statuses,
  missingStatusIDs,
  statusesLoading,
  submitting,
  templates,
  templatesLoading,
  config,
  onClose,
  onConfirm,
}) => {
  const [statusID, setStatusID] = useState<string | null>(null);
  const [reason, setReason] = useState("");
  const [noticeTemplate, setNoticeTemplate] = useState("");
  const [followupTemplate, setFollowupTemplate] = useState("");
  const [region, setRegion] = useState<DeletionRegion>("others");
  const [ccRecipients, setCcRecipients] = useState<string[]>([
    ARCHIVE_CC_ADDRESS,
  ]);

  useEffect(() => {
    setStatusID(null);
    setReason("");
    setNoticeTemplate("");
    setFollowupTemplate("");
    setCcRecipients([ARCHIVE_CC_ADDRESS]);
    setRegion(account?.region ?? "others");
  }, [account?.accountNumber, account?.region, opened]);

  const options = useMemo(
    () =>
      statuses.map((status) => ({
        value: status.id,
        label: status.applicable
          ? status.name
          : `${status.name} — no Viewpoint id mapped`,
        disabled: !status.applicable,
      })),
    [statuses],
  );

  const selected = statuses.find((status) => status.id === statusID) ?? null;

  const invalidCc = ccRecipients.filter(
    (address) => !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(address),
  );

  const regionEntry =
    config?.regions.find((entry) => entry.region === region) ?? null;

  const regionUndetected =
    region === "others" && account?.regionSource === "fallback";

  const isCorrection = statuses.some(
    (status) =>
      status.extAccountStatusID != null &&
      Number(status.extAccountStatusID) === account?.viewpoint.accountStatusID,
  );

  const alreadyInStatus =
    selected?.extAccountStatusID != null &&
    account?.viewpoint.accountStatusID != null &&
    Number(selected.extAccountStatusID) === account.viewpoint.accountStatusID;

  const canSubmit =
    Boolean(account) &&
    Boolean(selected?.applicable) &&
    !alreadyInStatus &&
    invalidCc.length === 0 &&
    ccRecipients.length > 0 &&
    reason.trim().length >= MIN_REASON &&
    !submitting;

  if (!account) return null;

  const memberCount = account.local.members.length;
  const localStatuses = [
    ...new Set(account.local.members.map((member) => member.accountStatusName)),
  ];

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title={`Delete account ${account.accountNumber}`}
      size="lg"
      centered
    >
      <Stack gap="md">
        <Stack gap={6}>
          <Text size="sm" c="dimmed">
            Account
          </Text>
          <Group gap="xs">
            <Text fw={600}>{account.viewpoint.accountName ?? "—"}</Text>
            <Badge variant="light">{account.accountNumber}</Badge>
          </Group>
          <Group gap="xs">
            <Text size="sm" c="dimmed">
              Viewpoint:
            </Text>
            <Badge variant="light" color="gray">
              {account.viewpoint.accountStatus ?? "—"}
            </Badge>
            <Text size="sm" c="dimmed">
              Core:
            </Text>
            {localStatuses.length > 0 ? (
              localStatuses.map((status) => (
                <Badge key={status} variant="light" color="gray">
                  {status}
                </Badge>
              ))
            ) : (
              <Badge variant="light" color="gray">
                no member record
              </Badge>
            )}
          </Group>
        </Stack>

        <Divider label="Emails to the member" labelPosition="left" />

        <Select
          label="Region"
          description={
            account.regionSource === "charge-centre"
              ? `From the charge centre: ${account.viewpoint.chargeCentreName}`
              : account.regionSource === "country"
                ? `From the billing country: ${account.viewpoint.country}`
                : "Neither the charge centre nor a country identified a region — correct this if the member is in a named region."
          }
          data={REGION_OPTIONS}
          value={region}
          onChange={(value) => {
            setRegion((value as DeletionRegion) ?? "others");
            setNoticeTemplate(DEFAULT_VALUE);
            setFollowupTemplate(DEFAULT_VALUE);
          }}
          withAsterisk
        />

        <Select
          label="Email sent now"
          description="The acknowledgement the member receives when the account is retired."
          data={templateOptions(templates, regionEntry?.acknowledgement)}
          value={noticeTemplate}
          onChange={(value) => setNoticeTemplate(value ?? DEFAULT_VALUE)}
          disabled={templatesLoading}
          searchable
          allowDeselect={false}
        />

        <Select
          label={`Email sent after ${config?.followupDays ?? 30} days`}
          description={`The data-deletion confirmation, sent ${config?.followupDays ?? 30} days after retirement unless the account is reactivated first.`}
          data={templateOptions(templates, regionEntry?.confirmation)}
          value={followupTemplate}
          onChange={(value) => setFollowupTemplate(value ?? DEFAULT_VALUE)}
          disabled={templatesLoading}
          searchable
          allowDeselect={false}
        />

        <TagsInput
          label="Copy these people"
          description="Copied on both emails. Press Enter after each. At least one is required."
          placeholder={
            ccRecipients.length === 0 ? "colleague@karmagroup.com" : ""
          }
          value={ccRecipients}
          onChange={setCcRecipients}
          splitChars={[",", ";", " "]}
          clearable
          withAsterisk
          error={
            invalidCc.length
              ? `Not an email address: ${invalidCc.join(", ")}`
              : ccRecipients.length === 0
                ? "Copy at least one address — a deletion nobody is copied on leaves no trace outside this console."
                : null
          }
        />

        <Divider label="Status" labelPosition="left" />

        {missingStatusIDs.length > 0 && (
          <Alert color="yellow" variant="light">
            <Text size="sm">
              The member database has no status mapped to Viewpoint id{" "}
              {missingStatusIDs.join(" or ")}, so it is not in the list below. Check
              `member_account_statuses` — a short list is not the same as a complete
              one.
            </Text>
          </Alert>
        )}

        <Select
          label="Account status"
          placeholder={statusesLoading ? "Loading statuses…" : "Select a status"}
          description="Invalid, or the expiry / cancellation status for Subito — whichever your process calls for."
          data={options}
          value={statusID}
          onChange={setStatusID}
          disabled={statusesLoading}
          searchable
          withAsterisk
          error={
            alreadyInStatus
              ? `This account is already ${selected?.name}. Pick the other status, or close this dialog.`
              : null
          }
        />

        <Textarea
          label="Reason"
          description="Stored with the activity log entry for this action."
          placeholder="Why is this account being retired?"
          minRows={3}
          autosize
          value={reason}
          onChange={(event) => setReason(event.currentTarget.value)}
          error={
            reason.length > 0 && reason.trim().length < MIN_REASON
              ? `At least ${MIN_REASON} characters`
              : null
          }
          withAsterisk
        />

        <Text size="sm" c="dimmed">
          Retiring this account also disables Subito sign-in for{" "}
          {memberCount === 1 ? "the member" : `all ${memberCount} members`} on it
          {account.local.activeSessions > 0
            ? ` and drops ${account.local.activeSessions} live session${account.local.activeSessions === 1 ? "" : "s"} immediately`
            : ""}
          . The member records stay in the console and keep their bookings.
        </Text>

        {memberCount > 1 && (
          <Alert color="orange" variant="light">
            <Text size="sm">
              This membership carries {memberCount} member records. All of them are
              retired together, because the account is the unit being retired:
            </Text>
            <List size="sm" mt={6}>
              {account.local.members.map((member) => (
                <List.Item key={member.memberID}>
                  {[member.firstName, member.lastName].filter(Boolean).join(" ") ||
                    member.memberNumber}
                  {member.email ? ` — ${member.email}` : ""}
                </List.Item>
              ))}
            </List>
          </Alert>
        )}

        <Group justify="flex-end" mt="xs">
          <Button variant="default" onClick={onClose} disabled={submitting}>
            Cancel
          </Button>
          <Button
            color="red"
            loading={submitting}
            disabled={!canSubmit}
            onClick={() =>
              onConfirm({
                statusID: statusID!,
                reason: reason.trim(),
                killLogin: true,
                revokeSessions: true,
                softDelete: false,
                region,
                ccRecipients,
                noticeTemplateID: noticeTemplate,
                followupTemplateID: followupTemplate,
              })
            }
          >
            Delete account
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
};

export default DeleteAccountModal;
