"use client";

import {
  Badge,
  Button,
  Group,
  List,
  Modal,
  Radio,
  Stack,
  Text,
  Tooltip,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { IconCloud, IconMailForward } from "@tabler/icons-react";
import React, { useCallback, useEffect, useState } from "react";
import { setEDMStorageTarget } from "@/lib/features/edm/action";
import { getEDMStorageTarget } from "@/lib/features/edm/query";
import type {
  EDMStorageTarget,
  EDMStorageTargetValue,
} from "@/lib/features/edm/types";

const LABEL: Record<EDMStorageTargetValue, string> = {
  gcs: "GCS",
  sendgrid: "SendGrid",
};

/**
 * Where new EDMs are stored: shown to everyone, changeable by a super admin.
 *
 * Deliberately reads as a status first and a control second. The setting only
 * decides where the NEXT template is created — everything already in existence
 * keeps living, being edited and being deleted in the store it is already in —
 * and a bare two-option toggle would imply it moves things.
 */
export function EDMStorageTargetControl() {
  const [config, setConfig] = useState<EDMStorageTarget | null>(null);
  const [opened, setOpened] = useState(false);
  const [choice, setChoice] = useState<EDMStorageTargetValue>("gcs");
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    const res = await getEDMStorageTarget();
    if (res.success && res.data) {
      setConfig(res.data);
      setChoice(res.data.target);
    }
  }, []);

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

  if (!config) return null;

  const current = config.target;

  const save = async () => {
    if (choice === current) {
      setOpened(false);
      return;
    }
    setSaving(true);
    try {
      const res = await setEDMStorageTarget(choice);
      notifications.show({
        color: res.success ? "green" : "red",
        message:
          res.message ||
          (res.success ? "Storage updated" : "Could not change the storage setting"),
        autoClose: res.success ? 8000 : undefined,
      });
      if (res.success) {
        setOpened(false);
        await load();
      }
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Tooltip
        multiline
        w={280}
        label={
          config.canChange
            ? `New templates are created in ${LABEL[current]}. Click to change. Existing templates are not moved.`
            : `New templates are created in ${LABEL[current]}. Only a super admin can change this.`
        }
      >
        <Badge
          size="lg"
          variant="light"
          color={current === "gcs" ? "teal" : "grape"}
          leftSection={
            current === "gcs" ? <IconCloud size={13} /> : <IconMailForward size={13} />
          }
          style={{ cursor: config.canChange ? "pointer" : "default" }}
          onClick={() => config.canChange && setOpened(true)}
        >
          New EDMs → {LABEL[current]}
        </Badge>
      </Tooltip>

      <Modal
        opened={opened}
        onClose={() => setOpened(false)}
        title="Where should new EDMs be stored?"
        centered
      >
        <Stack gap="md">
          <Radio.Group
            value={choice}
            onChange={(v) => setChoice(v as EDMStorageTargetValue)}
          >
            <Stack gap="sm">
              <Radio
                value="gcs"
                label="GCS — our own storage"
                description="Templates live in our bucket and database. SendGrid still delivers the mail; it just stops holding the template. This is what the migration is for."
              />
              <Radio
                value="sendgrid"
                label="SendGrid — as before the migration"
                description="Templates are created as SendGrid dynamic templates and merged on SendGrid's servers. Subject to SendGrid's stored-template cap, which is the reason for moving off it."
              />
            </Stack>
          </Radio.Group>

          {/*
            Stated plainly because it is the part people assume wrongly: this is
            not a migration button.
          */}
          <Stack gap={4}>
            <Text size="sm" fw={600}>
              This changes new templates only.
            </Text>
            <List size="sm" spacing={2}>
              <List.Item>Nothing already created is moved or copied.</List.Item>
              <List.Item>
                A template already in GCS is still edited and deleted in GCS.
              </List.Item>
              <List.Item>
                A template that only exists in SendGrid is still edited and
                deleted in SendGrid.
              </List.Item>
            </List>
          </Stack>

          {config.source === "env" && (
            <Text size="xs" c="dimmed">
              Currently following the server default ({LABEL[config.envDefault]}).
              Saving here overrides it for everyone, without a deploy.
            </Text>
          )}

          <Group justify="flex-end">
            <Button variant="subtle" onClick={() => setOpened(false)} disabled={saving}>
              Cancel
            </Button>
            <Button onClick={save} loading={saving} disabled={choice === current}>
              Save
            </Button>
          </Group>
        </Stack>
      </Modal>
    </>
  );
}
