"use client";

import type { CloudflareAccount, CloudflareZone } from "@domainops/shared-types";
import { App, Button, Card, Form, Input, Select, Typography } from "antd";
import { SafetyOutlined } from "@ant-design/icons";
import { useCallback, useEffect, useState } from "react";
import { listCloudflareZones } from "@/lib/api/cloudflare";
import { getDmsCloudflareAccount, getGlobalSettings, saveDmsCloudflareAccount, updateGlobalSettings } from "@/lib/api/settings";
import type { DmsCloudflareAccountInput } from "@/lib/api/settings";
import { ApiError } from "@/lib/api/client";
import { ZoneSecurityModal } from "../cloudflare/ZoneSecurityModal";

/**
 * The Cloudflare account protecting this DMS app's own domain - a
 * separate, dev-team-hosted account, deliberately not one of the
 * brand/client accounts on the main Cloudflare > Accounts listing (see
 * DmsCloudflareAccountController's docblock). Reuses ZoneSecurityModal
 * (the same zone-by-zone_id management used elsewhere) once connected.
 */
export function ProtectAppCard() {
  const { message } = App.useApp();
  const [form] = Form.useForm<DmsCloudflareAccountInput>();
  const [account, setAccount] = useState<CloudflareAccount | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [isSavingAccount, setIsSavingAccount] = useState(false);
  const [zones, setZones] = useState<CloudflareZone[]>([]);
  const [zoneId, setZoneId] = useState<string | undefined>();
  const [isLoadingZones, setIsLoadingZones] = useState(false);
  const [isSavingZone, setIsSavingZone] = useState(false);
  const [isManageOpen, setIsManageOpen] = useState(false);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const [dmsAccount, settings] = await Promise.all([getDmsCloudflareAccount(), getGlobalSettings()]);
      setAccount(dmsAccount);
      setZoneId(settings.dms_cloudflare_zone_id ?? undefined);
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load this setting.");
    } finally {
      setIsLoading(false);
    }
  }, [message]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  useEffect(() => {
    if (!account) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setZones([]);
      return;
    }
    setIsLoadingZones(true);
    listCloudflareZones(account.id)
      .then(setZones)
      .catch((err) => message.error(err instanceof ApiError ? err.message : "Couldn't load zones."))
      .finally(() => setIsLoadingZones(false));
  }, [account, message]);

  async function handleSaveAccount(values: DmsCloudflareAccountInput) {
    setIsSavingAccount(true);
    try {
      const saved = await saveDmsCloudflareAccount(values);
      setAccount(saved);
      setIsFormOpen(false);
      form.resetFields();
      message.success("Connection saved.");
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't save that connection.");
    } finally {
      setIsSavingAccount(false);
    }
  }

  async function handleSaveZone() {
    setIsSavingZone(true);
    try {
      await updateGlobalSettings({ dms_cloudflare_zone_id: zoneId ?? null });
      message.success("Protection zone saved.");
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't save that.");
    } finally {
      setIsSavingZone(false);
    }
  }

  return (
    <Card
      loading={isLoading}
      title="Protect This App"
      className="dms_settings_security_protect_app_card"
      extra={<SafetyOutlined />}
    >
      <Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
        This is a separate Cloudflare account the dev team hosts for this DMS app&apos;s own domain - not one of
        the brand/client accounts under Cloudflare &gt; Accounts. Connect it here, then manage its IP allow/block
        rules, page rules, and DNS records.
      </Typography.Paragraph>

      {!account && !isFormOpen && (
        <Button
          type="primary"
          icon={<SafetyOutlined />}
          onClick={() => setIsFormOpen(true)}
          className="dms_settings_security_protect_app_connect_btn"
        >
          Connect Cloudflare Account
        </Button>
      )}

      {isFormOpen && (
        <Form<DmsCloudflareAccountInput>
          form={form}
          layout="vertical"
          onFinish={handleSaveAccount}
          initialValues={account ? { label: account.label, account_id: account.account_id, cf_email: account.cf_email ?? undefined } : undefined}
          className="dms_settings_security_protect_app_form"
        >
          <Form.Item name="label" label="Label" rules={[{ required: true, message: "Give it a label" }]}>
            <Input placeholder="Dev Team - DMS Protection" />
          </Form.Item>
          <Form.Item name="account_id" label="Cloudflare account ID" rules={[{ required: true, message: "Required" }]}>
            <Input placeholder="the account's own tenant id in Cloudflare" />
          </Form.Item>
          <Form.Item name="cf_email" label="Cloudflare email (optional)">
            <Input placeholder="devteam@example.com" />
          </Form.Item>
          <Form.Item name="api_token" label="API token" rules={[{ required: true, message: "Required" }]}>
            <Input.Password placeholder="Scoped API token this app authenticates with" />
          </Form.Item>
          <div className="flex gap-2">
            <Button type="primary" htmlType="submit" loading={isSavingAccount} className="dms_settings_security_protect_app_save_account_btn">
              Save
            </Button>
            <Button onClick={() => setIsFormOpen(false)} className="dms_settings_security_protect_app_cancel_btn">
              Cancel
            </Button>
          </div>
        </Form>
      )}

      {account && !isFormOpen && (
        <div className="flex flex-col gap-4">
          <div className="flex items-center justify-between">
            <div>
              <Typography.Text strong>{account.label}</Typography.Text>
              {account.cf_email && (
                <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  {account.cf_email}
                </Typography.Paragraph>
              )}
            </div>
            <Button size="small" onClick={() => setIsFormOpen(true)} className="dms_settings_security_protect_app_edit_btn">
              Edit Credentials
            </Button>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            <Select
              placeholder="Zone"
              style={{ width: 260 }}
              value={zoneId}
              allowClear
              loading={isLoadingZones}
              options={zones.map((z) => ({ value: z.id, label: z.name }))}
              onChange={setZoneId}
              className="dms_settings_security_protect_app_zone_select"
            />
            <Button
              type="primary"
              onClick={handleSaveZone}
              loading={isSavingZone}
              className="dms_settings_security_protect_app_save_zone_btn"
            >
              Save
            </Button>
          </div>

          {zoneId && (
            <Button
              icon={<SafetyOutlined />}
              onClick={() => setIsManageOpen(true)}
              className="dms_settings_security_protect_app_manage_btn"
            >
              Manage DNS, Page & Security Rules
            </Button>
          )}
        </div>
      )}

      <ZoneSecurityModal
        open={isManageOpen}
        account={account}
        initialZoneId={zoneId}
        onClose={() => setIsManageOpen(false)}
      />
    </Card>
  );
}
