"use client";

import type { ServerAccount, ServerGroup, WorkloadType } from "@domainops/shared-types";
import { App, Form, Input, Modal, Select } from "antd";
import { useEffect, useState } from "react";
import { createServerAccount, listServerGroups } from "@/lib/api/servers";
import { ApiError } from "@/lib/api/client";

interface QuickServerAccountValues {
  server_group_id: number;
  username: string;
  workload_type: WorkloadType;
}

/**
 * Adds a cPanel account on an existing server without leaving the screen
 * that needs it - used by Bulk Assign so "assign these domains to a new
 * server account" is one flow, not a detour through the Servers page.
 */
export function QuickServerAccountModal({
  open,
  onClose,
  onCreated,
}: {
  open: boolean;
  onClose: () => void;
  onCreated: (account: ServerAccount) => void;
}) {
  const { message } = App.useApp();
  const [form] = Form.useForm<QuickServerAccountValues>();
  const [groups, setGroups] = useState<ServerGroup[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

  async function handleSubmit(values: QuickServerAccountValues) {
    setIsSubmitting(true);
    try {
      const account = await createServerAccount(values);
      const group = groups.find((g) => g.id === values.server_group_id);
      message.success(`${values.username} added.`);
      form.resetFields();
      onCreated({ ...account, server_group: account.server_group ?? group });
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't add that account.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Modal
      title="New Server Account"
      open={open}
      onCancel={onClose}
      onOk={() => form.submit()}
      confirmLoading={isSubmitting}
      okText="Add account"
      destroyOnHidden
      className="dms_quick_server_account_modal"
    >
      <Form<QuickServerAccountValues>
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{ workload_type: "static" }}
        className="dms_quick_server_account_form"
      >
        <Form.Item name="server_group_id" label="Server" rules={[{ required: true, message: "Pick a server" }]}>
          <Select
            showSearch
            optionFilterProp="label"
            placeholder="Which server is this account on?"
            options={groups.map((g) => ({ value: g.id, label: g.label }))}
          />
        </Form.Item>
        <Form.Item name="username" label="cPanel username" rules={[{ required: true, message: "Enter the account username" }]}>
          <Input placeholder="mega888" />
        </Form.Item>
        <Form.Item name="workload_type" label="Workload">
          <Select
            options={[
              { value: "static", label: "Static" },
              { value: "wordpress", label: "WordPress" },
            ]}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}
