"use client";

import type { Brand, Region } from "@domainops/shared-types";
import { App, Form, Input, Modal, Select } from "antd";
import { useEffect, useState } from "react";
import { createBrand, listRegions, updateBrand } from "@/lib/api/domains";
import { ApiError } from "@/lib/api/client";

interface BrandFormValues {
  name: string;
  region_ids: number[];
  brands: string[];
  keywords: string[];
}

/**
 * Shared create/edit flow for Brand - the "advanced" (proper modal, not an
 * inline dropdown text box) creation flow, reused by both the Brands admin
 * page and every Select that lets an operator add a brand on the fly (Add
 * Domain, Buy Domains) so there's exactly one place this logic lives.
 */
export function BrandFormModal({
  open,
  brand,
  onClose,
  onSaved,
}: {
  open: boolean;
  brand?: Brand | null;
  onClose: () => void;
  onSaved: (brand: Brand) => void;
}) {
  const { message } = App.useApp();
  const [form] = Form.useForm<BrandFormValues>();
  const [regions, setRegions] = useState<Region[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const isEditing = !!brand;

  useEffect(() => {
    if (!open) return;
    void listRegions().then(setRegions);
  }, [open]);

  async function handleSubmit(values: BrandFormValues) {
    setIsSubmitting(true);
    try {
      const saved = isEditing ? await updateBrand(brand!.id, values) : await createBrand(values);
      message.success(isEditing ? `${saved.name} updated.` : `${saved.name} added.`);
      form.resetFields();
      onSaved(saved);
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't save that brand.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Modal
      title={isEditing ? "Edit Project" : "Create Project"}
      open={open}
      onCancel={onClose}
      onOk={() => form.submit()}
      confirmLoading={isSubmitting}
      okText={isEditing ? "Save" : "Create project"}
      destroyOnHidden
      className="dms_brand_form_modal"
    >
      <Form<BrandFormValues>
        form={form}
        layout="vertical"
        initialValues={{
          name: brand?.name ?? "",
          region_ids: brand?.regions?.map((r) => r.id) ?? [],
          brands: brand?.project_brands?.map((b) => b.name) ?? [],
          keywords: brand?.keywords?.map((k) => k.keyword) ?? [],
        }}
        onFinish={handleSubmit} className="dms_brand_form_form">
        <Form.Item
          name="name"
          label="Project name"
          rules={[{ required: true, message: "Give it a name" }]}
          className="dms_brand_form_name_field"
        >
          <Input placeholder="Acme Project" autoFocus />
        </Form.Item>
        <Form.Item
          name="region_ids"
          label="Regions"
          rules={[{ required: true, type: "array", min: 1, message: "Pick at least one region" }]}
          className="dms_brand_form_regions_field"
        >
          <Select
            mode="multiple"
            placeholder="Select at least one region"
            options={regions.map((r) => ({ value: r.id, label: `${r.name} (${r.country_code})` }))}
          />
        </Form.Item>
        <Form.Item
          name="brands"
          label="Brands"
          extra="Brands under this project. Type a name and press Enter - a domain can then be assigned one of them."
          className="dms_brand_form_brands_field"
        >
          <Select mode="tags" tokenSeparators={[","]} open={false} placeholder="e.g. Acme Casino, Acme Sports" />
        </Form.Item>
        <Form.Item
          name="keywords"
          label="Keywords"
          extra="Free tags for this project. Searching Domain Inventory also matches these."
          className="dms_brand_form_keywords_field"
        >
          <Select mode="tags" tokenSeparators={[","]} open={false} placeholder="e.g. slots, bonus" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
