"use client";

import type { Domain } from "@domainops/shared-types";
import { App, Form, Input, Modal, Select } from "antd";
import { useState } from "react";
import { archiveDomain } from "@/lib/api/domains";
import type { ArchiveReason } from "@/lib/api/domains";
import { ApiError } from "@/lib/api/client";

export const ARCHIVE_REASON_OPTIONS: { value: ArchiveReason; label: string }[] = [
  { value: "expired", label: "Expired" },
  { value: "transferred", label: "Transferred" },
  { value: "removed", label: "Removed" },
  { value: "others", label: "Others" },
];

interface ArchiveFormValues {
  reason: ArchiveReason;
  notes: string;
}

/**
 * Archiving always records why - a reason from the fixed list plus free-text
 * notes - so the Archived Domains view can say what happened to each one.
 */
export function ArchiveDomainModal({
  domain,
  onClose,
  onArchived,
}: {
  domain: Pick<Domain, "id" | "fqdn"> | null;
  onClose: () => void;
  onArchived: () => void;
}) {
  const { message } = App.useApp();
  const [form] = Form.useForm<ArchiveFormValues>();
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(values: ArchiveFormValues) {
    if (!domain) return;
    setIsSubmitting(true);
    try {
      await archiveDomain(domain.id, values);
      message.success(`${domain.fqdn} archived.`);
      onArchived();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't archive that domain.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Modal
      title={domain ? `Archive ${domain.fqdn}` : "Archive Domain"}
      open={!!domain}
      onCancel={onClose}
      onOk={() => form.submit()}
      confirmLoading={isSubmitting}
      okText="Archive"
      destroyOnHidden
      className="dms_archive_domain_modal"
    >
      <p className="text-sm text-gray-500 mb-3">It will be hidden from Domain Inventory, not deleted, and can be restored from Archived Domains.</p>
      <Form<ArchiveFormValues> form={form} layout="vertical" onFinish={handleSubmit} className="dms_archive_domain_form">
        <Form.Item name="reason" label="Reason" rules={[{ required: true, message: "Pick a reason" }]} className="dms_archive_domain_reason_field">
          <Select options={ARCHIVE_REASON_OPTIONS} placeholder="Why is it being archived?" />
        </Form.Item>
        <Form.Item name="notes" label="Notes" rules={[{ required: true, message: "Add a note" }]} className="dms_archive_domain_notes_field">
          <Input.TextArea rows={3} maxLength={2000} placeholder="Details for whoever looks at this later" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
