"use client";

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

interface FlagFormValues {
  notes: string;
}

/**
 * Raises a concern on a domain - the note is required and shows under the
 * domain's name in Domain Inventory, where flagged rows sort to the top.
 */
export function FlagDomainModal({
  domain,
  onClose,
  onFlagged,
}: {
  domain: Domain | null;
  onClose: () => void;
  onFlagged: (domain: Domain) => void;
}) {
  const { message } = App.useApp();
  const [form] = Form.useForm<FlagFormValues>();
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(values: FlagFormValues) {
    if (!domain) return;
    setIsSubmitting(true);
    try {
      const updated = await flagDomain(domain.id, values.notes);
      message.success(`${domain.fqdn} flagged.`);
      onFlagged({ ...domain, ...updated });
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't flag that domain.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Modal
      title={domain ? `Flag ${domain.fqdn}` : "Flag Domain"}
      open={!!domain}
      onCancel={onClose}
      onOk={() => form.submit()}
      confirmLoading={isSubmitting}
      okText="Flag"
      destroyOnHidden
      className="dms_flag_domain_modal"
    >
      <Form<FlagFormValues>
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{ notes: domain?.flag_notes ?? "" }}
        className="dms_flag_domain_form"
      >
        <Form.Item name="notes" label="What is the concern?" rules={[{ required: true, message: "Add a note" }]} className="dms_flag_domain_notes_field">
          <Input.TextArea rows={3} maxLength={1000} placeholder="Shown under the domain name until the flag is cleared" autoFocus />
        </Form.Item>
      </Form>
    </Modal>
  );
}
