import { useEffect, useState } from "react"
import {
  ApiOutlined,
  ExperimentOutlined,
  SafetyCertificateOutlined,
  TeamOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Button,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Segmented,
  Space,
  Switch,
  Typography,
} from "antd"
import { toast } from "../../utils/toast"
import {
  createCloudServer,
  testUnsavedCloudServer,
  updateCloudServer,
  type CloudServer,
  type CloudServerCreatePayload,
} from "../api/cloud_server"

const { Text } = Typography

interface Props {
  open: boolean
  onClose: () => void
  onSaved: () => void
  initial?: CloudServer | null
}

interface FormValues {
  name: string
  server_type: "dcimcloud" | "zjmf_finance"
  account_type: "admin" | "agent" | "client" | "resource"
  hostname: string
  port: number | null
  secure: boolean
  username: string
  password?: string
  client_id: number | null
  user_prefix?: string
  remark?: string
  disabled: boolean
}

function valuesFromInitial(server: CloudServer | null | undefined): FormValues {
  return {
    name: server?.name ?? "",
    server_type: server?.server_type ?? "dcimcloud",
    account_type: server?.account_type ?? "admin",
    hostname: server?.hostname ?? "",
    port: server?.port || null,
    secure: server?.secure ?? true,
    username: server?.username ?? "",
    password: "",
    client_id: server?.client_id ?? null,
    user_prefix: server?.user_prefix ?? "",
    remark: server?.remark ?? "",
    disabled: server?.disabled ?? false,
  }
}

function normalizeEndpoint(values: FormValues) {
  const rawHostname = values.hostname.trim()
  if (values.server_type !== "zjmf_finance" || !/^https?:\/\//i.test(rawHostname)) {
    return {
      hostname: rawHostname,
      port: values.server_type === "zjmf_finance" ? 0 : values.port ?? 0,
      secure: values.secure,
    }
  }
  try {
    const url = new URL(rawHostname)
    return {
      hostname: url.host,
      port: 0,
      secure: url.protocol !== "http:",
    }
  } catch {
    return {
      hostname: rawHostname.replace(/^https?:\/\//i, "").replace(/\/+$/, ""),
      port: 0,
      secure: !rawHostname.toLowerCase().startsWith("http://"),
    }
  }
}

function toPayload(values: FormValues): CloudServerCreatePayload {
  const isZjmfFinance = values.server_type === "zjmf_finance"
  const endpoint = normalizeEndpoint(values)
  return {
    name: values.name.trim(),
    server_type: values.server_type,
    account_type: values.account_type,
    hostname: endpoint.hostname,
    port: endpoint.port,
    secure: endpoint.secure,
    username: values.username.trim(),
    password: values.password ?? "",
    client_id: isZjmfFinance ? null : values.client_id ?? null,
    user_prefix: isZjmfFinance ? null : values.user_prefix?.trim() || null,
    disabled: values.disabled,
    remark: values.remark?.trim() || null,
  }
}

export default function CloudServerFormModal({ open, onClose, onSaved, initial }: Props) {
  const [form] = Form.useForm<FormValues>()
  const [saving, setSaving] = useState(false)
  const [testing, setTesting] = useState(false)
  const isEdit = !!initial
  const serverType = Form.useWatch("server_type", form)
  const isZjmfFinance = serverType === "zjmf_finance"

  useEffect(() => {
    if (open) form.setFieldsValue(valuesFromInitial(initial))
  }, [form, initial, open])

  useEffect(() => {
    const current = form.getFieldValue("account_type")
    if (serverType === "zjmf_finance" && !["client", "resource"].includes(current)) {
      form.setFieldValue("account_type", "client")
    }
    if ((serverType ?? "dcimcloud") === "dcimcloud" && !["admin", "agent"].includes(current)) {
      form.setFieldValue("account_type", "admin")
    }
  }, [form, serverType])

  const handleTest = async () => {
    try {
      const values = await form.validateFields(["server_type", "account_type", "hostname", "port", "secure", "username", "password"])
      if (!values.password) {
        toast.error(values.server_type === "zjmf_finance" ? "测试需要填写 API 密钥" : "测试需要填写密码")
        return
      }
      setTesting(true)
      const endpoint = normalizeEndpoint(values as FormValues)
      const res = await testUnsavedCloudServer({
        server_type: values.server_type,
        account_type: values.account_type,
        hostname: endpoint.hostname,
        port: endpoint.port,
        secure: endpoint.secure,
        username: values.username.trim(),
        password: values.password,
      })
      if (res.data?.ok) toast.success(res.data.message)
      else toast.error(res.data?.message || "测试失败")
    } catch (e: unknown) {
      if ((e as { errorFields?: unknown[] })?.errorFields) return
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "测试请求失败")
    } finally {
      setTesting(false)
    }
  }

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      const payload = toPayload(values)
      if (isEdit && initial && !values.password) {
        delete (payload as { password?: string }).password
      }
      setSaving(true)
      if (isEdit && initial) {
        await updateCloudServer(initial.id, payload)
        toast.success("已保存")
      } else {
        await createCloudServer(payload)
        toast.success("已添加")
      }
      onSaved()
      onClose()
    } catch (e: unknown) {
      if ((e as { errorFields?: unknown[] })?.errorFields) return
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "保存失败")
    } finally {
      setSaving(false)
    }
  }

  const accountTypeOptions = serverType === "zjmf_finance"
    ? [
        {
          value: "client",
          label: (
            <Space orientation="vertical" size={2} style={{ padding: "6px 0" }}>
              <Space><SafetyCertificateOutlined />魔方财务客户</Space>
              <Text type="secondary" style={{ fontSize: 12 }}>登录 /zjmf_api_login</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>使用 API 账号/API 密钥</Text>
            </Space>
          ),
        },
        {
          value: "resource",
          label: (
            <Space orientation="vertical" size={2} style={{ padding: "6px 0" }}>
              <Space><TeamOutlined />魔方财务资源池</Space>
              <Text type="secondary" style={{ fontSize: 12 }}>登录 /resource_login</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>使用供应商 API 账号/API 密钥</Text>
            </Space>
          ),
        },
      ]
    : [
        {
          value: "admin",
          label: (
            <Space orientation="vertical" size={2} style={{ padding: "6px 0" }}>
              <Space><SafetyCertificateOutlined />自营（管理员）</Space>
              <Text type="secondary" style={{ fontSize: 12 }}>登录 /v1/login?a=a</Text>
            </Space>
          ),
        },
        {
          value: "agent",
          label: (
            <Space orientation="vertical" size={2} style={{ padding: "6px 0" }}>
              <Space><TeamOutlined />资源池（代理商）</Space>
              <Text type="secondary" style={{ fontSize: 12 }}>登录 /token，开通需要 rid</Text>
            </Space>
          ),
        },
      ]

  return (
    <Modal
      open={open}
      title={
        <Space>
          <ApiOutlined />
          {isEdit ? "编辑上游接口" : "添加上游接口"}
        </Space>
      }
      width={720}
      destroyOnHidden
      onCancel={onClose}
      footer={[
        <Button key="cancel" onClick={onClose} disabled={saving}>取消</Button>,
        <Button key="test" icon={<ExperimentOutlined />} loading={testing} disabled={saving} onClick={handleTest}>
          测试连通性
        </Button>,
        <Button key="submit" type="primary" loading={saving} onClick={handleSubmit}>
          {isEdit ? "保存" : "添加"}
        </Button>,
      ]}
    >
      <Alert
        type="info"
        showIcon
        title={isZjmfFinance ? "魔方财务接口" : "魔方云接口"}
        description={
          isZjmfFinance
            ? "使用魔方财务后台开启的 API 账号和 API 密钥登录，系统会换取 JWT 后再调用商品、购物车和开通接口。"
            : "按自营或资源池身份接入魔方云，产品自动开通时会使用这里配置的接口。"
        }
      />

      <Form
        form={form}
        layout="vertical"
        requiredMark="optional"
        initialValues={valuesFromInitial(initial)}
        style={{ marginTop: 20 }}
      >
        <Form.Item label="接口名称" name="name" rules={[{ required: true, message: "请填写接口名称" }]}>
          <Input placeholder="例：上海 · 自营资源" />
        </Form.Item>

        <Form.Item label="上游系统" name="server_type" rules={[{ required: true, message: "请选择上游系统" }]}>
          <Segmented
            block
            options={[
              { value: "dcimcloud", label: "魔方云" },
              { value: "zjmf_finance", label: "魔方财务" },
            ]}
          />
        </Form.Item>

        <Form.Item label="账号类型" name="account_type" rules={[{ required: true, message: "请选择账号类型" }]}>
          <Segmented block options={accountTypeOptions} />
        </Form.Item>

        <Row gutter={16}>
          <Col span={isZjmfFinance ? 18 : 14}>
            <Form.Item
              label={isZjmfFinance ? "接口地址" : "主机地址"}
              name="hostname"
              rules={[{ required: true, message: isZjmfFinance ? "请填写接口地址" : "请填写主机地址" }]}
            >
              <Input placeholder={isZjmfFinance ? "finance.example.com，非标准端口可写 finance.example.com:8080" : "cloud.example.com 或 1.2.3.4"} />
            </Form.Item>
          </Col>
          {!isZjmfFinance && (
            <Col span={5}>
              <Form.Item label="端口" name="port">
                <InputNumber min={0} precision={0} placeholder="可空" style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          )}
          <Col span={5}>
            <Form.Item label="HTTPS" name="secure" valuePropName="checked">
              <Switch checkedChildren="开启" unCheckedChildren="关闭" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={isZjmfFinance ? "API 账号" : "用户名"}
              name="username"
              rules={[{ required: true, message: isZjmfFinance ? "请填写 API 账号" : "请填写用户名" }]}
              tooltip={isZjmfFinance ? "魔方财务客户 API 登录使用的手机号/邮箱，接口参数名仍叫 username" : undefined}
            >
              <Input autoComplete="off" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={
                isZjmfFinance
                  ? (isEdit ? "API 密钥（留空表示不修改）" : "API 密钥")
                  : (isEdit ? "密码（留空表示不修改）" : "密码")
              }
              name="password"
              rules={isEdit ? [] : [{ required: true, message: isZjmfFinance ? "请填写 API 密钥" : "请填写密码" }]}
              tooltip={isZjmfFinance ? "魔方财务源码中校验的是 clients.api_password，不是普通登录密码" : undefined}
            >
              <Input.Password autoComplete="new-password" />
            </Form.Item>
          </Col>
        </Row>

        {!isZjmfFinance && (
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="魔方云客户 ID"
                name="client_id"
                tooltip="开通实例时传 client 字段，填写魔方云后台对应的用户 ID"
              >
                <InputNumber min={0} precision={0} placeholder="例：214" style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="财务标识 user_prefix" name="user_prefix" tooltip="用于多租户隔离，可留空">
                <Input placeholder="例：qycw_" />
              </Form.Item>
            </Col>
          </Row>
        )}

        <Form.Item label="备注" name="remark">
          <Input.TextArea rows={3} />
        </Form.Item>

        <Form.Item label="禁用接口" name="disabled" valuePropName="checked">
          <Switch checkedChildren="禁用" unCheckedChildren="启用" />
        </Form.Item>
      </Form>
    </Modal>
  )
}
