"use client";

import type { Domain } from "@domainops/shared-types";
import { App, Checkbox, Form, Input, Modal, Select, Switch } from "antd";
import { useState } from "react";
import { mirrorRedirects } from "@/lib/api/redirects";
import type { MirrorRedirectInput } from "@/lib/api/redirects";
import { ApiError } from "@/lib/api/client";

export function MirrorRedirectsModal({
  open,
  domain,
  onClose,
  onDone,
}: {
  open: boolean;
  domain: Domain;
  onClose: () => void;
  onDone: () => void;
}) {
  const { message } = App.useApp();
  const [form] = Form.useForm<MirrorRedirectInput>();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const subdomains = domain.subdomains ?? [];

  async function handleSubmit(values: MirrorRedirectInput) {
    setIsSubmitting(true);
    try {
      const result = await mirrorRedirects(domain.id, values);
      message.success(`${result.created.length} redirect(s) created.`);
      result.skipped.forEach((row) => message.warning(`${row.fqdn}: ${row.reason}`));
      onDone();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't mirror those redirects.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Modal
      title={`Mirror subdomains - ${domain.fqdn}`}
      open={open}
      onCancel={onClose}
      onOk={() => form.submit()}
      confirmLoading={isSubmitting}
      okText="Create redirects"
      destroyOnHidden
      className="dms_mirror_redirects_modal"
    >
      <p className="text-sm text-gray-500 mb-3">
        Each subdomain is redirected to the same name on the new domain, e.g.{" "}
        <span className="font-mono">{subdomains[0]?.fqdn ?? `staging.${domain.fqdn}`}</span> {"->"}{" "}
        <span className="font-mono">{(subdomains[0]?.fqdn ?? `staging.${domain.fqdn}`).replace(`.${domain.fqdn}`, "")}.new-domain.com</span>.
        Their DNS records stay as they are, and each can be repointed on its own afterwards.
      </p>
      <Form<MirrorRedirectInput>
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{ type: "301", preserve_path: true, include_parent: true }}
        className="dms_mirror_redirects_form"
      >
        <Form.Item
          name="target_domain"
          label="New domain"
          rules={[{ required: true, message: "Enter the new domain" }]}
          className="dms_mirror_redirects_target_field"
        >
          <Input placeholder="xyz.com" />
        </Form.Item>
        <Form.Item name="type" label="Type" className="dms_mirror_redirects_type_field">
          <Select options={[{ value: "301", label: "301 (Permanent)" }, { value: "302", label: "302 (Temporary)" }]} />
        </Form.Item>
        <Form.Item name="preserve_path" label="Preserve path" valuePropName="checked" className="dms_mirror_redirects_preserve_path_field">
          <Switch />
        </Form.Item>
        <Form.Item name="include_parent" valuePropName="checked" className="dms_mirror_redirects_include_parent_field">
          <Checkbox>Also redirect {domain.fqdn} itself to the new domain</Checkbox>
        </Form.Item>
        <p className="text-sm">
          {subdomains.length} subdomain{subdomains.length === 1 ? "" : "s"} will be redirected. Any that already redirect
          somewhere are skipped.
        </p>
      </Form>
    </Modal>
  );
}
