import {
  Alert,
  Card,
  Group,
  Skeleton,
  Stack,
  Text,
  Button,
  Modal,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { IconAlertTriangle, IconMail } from "@tabler/icons-react";
import { useCallback, useEffect, useState } from "react";
import {
  applyAccountDeletion,
  getDeletionConfig,
  listDeletionRecords,
  listDeletionStatuses,
  reactivateAccount,
  searchAccounts,
  sendRecordMailNow,
  type AccountSearchResult,
  type DeletionConfig,
  type DeletionRecord,
  type DeletionStatus,
} from "@/lib/features/account-deletion/query";
import { listEDMTemplates } from "@/lib/features/edm/query";
import DeleteAccountModal, {
  type DeletionRequest,
  type TemplateOption,
} from "@/routes/account-deletion/_components/DeleteAccountModal";
import styles from "@/routes/promo-code-campaigns/_components/promo.module.css";
import AccountDeletionHistory from "./accountDeletionHistory";
import DeletionSettingsCard from "./deletionSettingsCard";
import {
  DeletionStatusStrip,
  RoundEmails,
  RoundFacts,
  type RoundActions,
} from "./deletionRoundView";

const MAX_RECORDS = 100;

const AccountDeletionPanel: React.FC<{ accountId: string }> = ({ accountId }) => {
  const [account, setAccount] = useState<AccountSearchResult | null>(null);
  const [records, setRecords] = useState<DeletionRecord[]>([]);
  const [templateNames, setTemplateNames] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);

  const [statuses, setStatuses] = useState<DeletionStatus[]>([]);
  const [missingStatusIDs, setMissingStatusIDs] = useState<string[]>([]);
  const [templates, setTemplates] = useState<TemplateOption[]>([]);
  const [config, setConfig] = useState<DeletionConfig | null>(null);

  const [dialogOpen, setDialogOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [sending, setSending] = useState<string | null>(null);
  const [reactivating, setReactivating] = useState<DeletionRecord | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const [
      accountResponse,
      recordResponse,
      statusResponse,
      templateResponse,
      configResponse,
    ] = await Promise.all([
      searchAccounts({ accountNumber: accountId }),
      listDeletionRecords({ page: 1, pageSize: MAX_RECORDS, search: accountId }),
      listDeletionStatuses(),
      listEDMTemplates(),
      getDeletionConfig(),
    ]);

    setAccount(
      accountResponse.success && accountResponse.data?.items.length
        ? (accountResponse.data.items[0] ?? null)
        : null,
    );

    setRecords(
      recordResponse.success && recordResponse.data
        ? recordResponse.data.items.filter(
            (item) => item.accountNumber === accountId,
          )
        : [],
    );

    if (statusResponse.success && statusResponse.data) {
      setStatuses(statusResponse.data.items);
      setMissingStatusIDs(statusResponse.data.missingExtStatusIDs ?? []);
    }
    if (templateResponse.success && Array.isArray(templateResponse.data)) {
      setTemplates(
        templateResponse.data.map((template) => ({
          id: template.id,
          name: template.name,
        })),
      );
      setTemplateNames(
        Object.fromEntries(
          templateResponse.data.map((template) => [template.id, template.name]),
        ),
      );
    }
    if (configResponse.success && configResponse.data) {
      setConfig(configResponse.data);
    }
    setLoading(false);
  }, [accountId]);

  useEffect(() => {
    void load();
  }, [load]);

  const templateLabel = useCallback(
    (id: string | null | undefined) =>
      (id ? templateNames[id] : null) ?? id ?? "—",
    [templateNames],
  );

  const confirmDeletion = useCallback(
    async (request: DeletionRequest) => {
      if (!account) return;
      setSubmitting(true);
      const response = await applyAccountDeletion({
        accountNumber: account.accountNumber,
        ...request,
      });
      setSubmitting(false);

      const partial = response.data?.localError;
      if (partial) {
        notifications.show({
          color: "orange",
          autoClose: false,
          title: "Partly applied",
          message: `Viewpoint was updated. The member database was not: ${partial}`,
        });
      } else if (!response.success) {
        notifications.show({
          color: "red",
          message: response.message || "Failed to delete the account",
        });
        return;
      } else {
        notifications.show({
          color: "green",
          message: response.data?.updatedExisting
            ? `Corrected to ${response.data?.appliedStatus.name} — existing closure updated, no new email sent`
            : `Account ${account.accountNumber} moved to ${response.data?.appliedStatus.name}`,
        });
      }

      if (response.data?.viewpointLogError) {
        notifications.show({
          color: "orange",
          autoClose: false,
          title: "Viewpoint log note not written",
          message: response.data.viewpointLogError,
        });
      }

      setDialogOpen(false);
      await load();
    },
    [account, load],
  );

  const sendNow = useCallback(
    async (record: DeletionRecord, kind: "notice" | "followup") => {
      setSending(`${record.id}:${kind}`);
      const response = await sendRecordMailNow({ recordID: record.id, kind });
      setSending(null);

      notifications.show({
        color: response.success ? "green" : "red",
        autoClose: response.success ? 10000 : false,
        message: response.success
          ? `The broker accepted it for ${response.data?.recipients.join(", ")}. Delivery is the SMTP worker's and SendGrid's from here.`
          : response.message || "Failed to queue the email",
      });
      await load();
    },
    [load],
  );

  const confirmReactivate = useCallback(async () => {
    if (!reactivating) return;
    setSubmitting(true);
    const response = await reactivateAccount(reactivating.id);
    setSubmitting(false);

    if (!response.success) {
      notifications.show({
        color: "red",
        message: response.message || "Failed to reactivate the account",
      });
      return;
    }

    notifications.show({
      color: "green",
      message: `Restored to ${response.data?.restoredStatus.name}${
        response.data?.followupCancelled
          ? " — the data-deletion email was cancelled"
          : ""
      }`,
    });
    if (response.data?.viewpointLogError) {
      notifications.show({
        color: "orange",
        autoClose: false,
        title: "Viewpoint log note not written",
        message: response.data.viewpointLogError,
      });
    }
    setReactivating(null);
    await load();
  }, [load, reactivating]);

  const actions: RoundActions = {
    onSend: (record, kind) => void sendNow(record, kind),
    onReactivate: setReactivating,
    sending,
  };

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

  const [current, ...earlier] = records;

  if (loading) {
    return (
      <Stack gap="lg" px={28}>
        <Skeleton height={160} radius="md" />
        <Skeleton height={200} radius="md" />
      </Stack>
    );
  }

  if (!account?.viewpoint.found) {
    return (
      <Alert
        color="red"
        variant="light"
        icon={<IconAlertTriangle size={18} />}
        title="Account not found"
        mx={28}
      >
        Viewpoint has no account {accountId}, or it could not be reached. Nothing can
        be applied until that is resolved.
      </Alert>
    );
  }

  return (
    <>
      <Stack gap="lg" px={28}>
        <DeletionStatusStrip
          accountName={account.viewpoint.accountName}
          accountNumber={account.accountNumber}
          currentStatus={account.viewpoint.accountStatus}
          region={current?.region ?? account.region}
          record={current ?? null}
          memberCount={account.local.members.length}
          activeSessions={account.local.activeSessions}
          chargeCentre={account.viewpoint.chargeCentreName}
          actionLabel={alreadyRetired ? "Change deletion status" : "Delete account"}
          onAction={() => setDialogOpen(true)}
          actions={actions}
        />

        {current ? (
          <Card className={styles.sectionCard} p="md">
            <Group gap={8} align="center" mb="sm">
              <span className={styles.sectionIcon}>
                <IconMail size={15} />
              </span>
              <Text fz={14} fw={600}>
                Emails for this closure
              </Text>
            </Group>
            <hr className={styles.gradientRule} />
            <Stack gap="md" mt="md">
              <RoundFacts record={current} />
              <RoundEmails
                record={current}
                templateLabel={templateLabel}
                actions={actions}
              />
            </Stack>
          </Card>
        ) : (
          <Card className={styles.sectionCard} p="md">
            <Text size="sm" c="dimmed" ta="center" py="lg">
              This account has never been retired.
            </Text>
          </Card>
        )}

        <DeletionSettingsCard
          config={config}
          accountNumber={accountId}
          accountName={account.viewpoint.accountName}
          region={account.region}
          onConfigSaved={(followupDays) =>
            setConfig((value) => (value ? { ...value, followupDays } : value))
          }
        />

        <AccountDeletionHistory
          records={earlier}
          templateLabel={templateLabel}
          actions={actions}
        />
      </Stack>

      <DeleteAccountModal
        opened={dialogOpen}
        account={account}
        statuses={statuses}
        missingStatusIDs={missingStatusIDs}
        statusesLoading={loading}
        submitting={submitting}
        templates={templates}
        templatesLoading={loading}
        config={config}
        onClose={() => setDialogOpen(false)}
        onConfirm={confirmDeletion}
      />

      <Modal
        opened={Boolean(reactivating)}
        onClose={() => setReactivating(null)}
        title={`Reactivate account ${reactivating?.accountNumber ?? ""}`}
        centered
      >
        <Stack gap="md">
          <Text size="sm">
            The account goes back to{" "}
            <strong>{reactivating?.previousStatus ?? "its previous status"}</strong> in
            Viewpoint, and the member record and sign-in are re-enabled. This writes
            to Viewpoint, the same live system the deletion did.
          </Text>
          {reactivating?.followupEdmStatus === "pending" && (
            <Text size="sm" c="dimmed">
              The data-deletion email is still pending and will be cancelled, so the
              member is not told about a closure that has been reversed.
            </Text>
          )}
          <Text size="sm" c="dimmed">
            Sessions are not restored — they were dropped at deletion, and the member
            signs in again.
          </Text>
          <Group justify="flex-end">
            <Button
              variant="default"
              onClick={() => setReactivating(null)}
              disabled={submitting}
            >
              Cancel
            </Button>
            <Button
              color="green"
              loading={submitting}
              onClick={() => void confirmReactivate()}
            >
              Reactivate
            </Button>
          </Group>
        </Stack>
      </Modal>
    </>
  );
};

export default AccountDeletionPanel;
