// @File: src/pages/admin/cms/shipping/CmsDhlSettings.tsx
// @Desc: Admin CMS page for configuring the DHL shipping integration:
//        credentials, environment toggle, and a live connection test.
import { useCallback, useEffect, useState } from "react";
import {
  CheckCircle2,
  KeyRound,
  Loader2,
  Save,
  Truck,
  XCircle,
} from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "../CmsLayout";
import { Field, PageHeader, SectionCard, TextInput } from "../ui";
import {
  adminGetDhlSettings,
  adminSaveDhlSettings,
  adminTestDhlConnection,
  type DhlSettings,
  type DhlTestResult,
} from "@/lib/dhlApi";

export default function CmsDhlSettings() {
  const [settings, setSettings] = useState<DhlSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [lastTest, setLastTest] = useState<DhlTestResult | null>(null);

  const [apiKey, setApiKey] = useState("");
  const [apiSecret, setApiSecret] = useState("");
  const [accountNumber, setAccountNumber] = useState("");
  const [environment, setEnvironment] = useState<"sandbox" | "production">("sandbox");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const s = await adminGetDhlSettings();
      setSettings(s);
      setAccountNumber(s.account_number || "");
      setEnvironment((s.environment === "production" ? "production" : "sandbox") as
        | "sandbox"
        | "production");
    } catch (e) {
      toast.error(`Load failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const save = async () => {
    setSaving(true);
    try {
      const s = await adminSaveDhlSettings({
        // Send key/secret only if the admin typed a new value. ``null`` / omit
        // means "leave unchanged" on the backend.
        api_key: apiKey.trim() ? apiKey.trim() : null,
        api_secret: apiSecret.trim() ? apiSecret.trim() : null,
        account_number: accountNumber.trim(),
        environment,
      });
      setSettings(s);
      setApiKey("");
      setApiSecret("");
      toast.success("DHL settings saved (secrets encrypted at rest).");
    } catch (e) {
      toast.error(`Save failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setSaving(false);
    }
  };

  const test = async () => {
    setTesting(true);
    setLastTest(null);
    try {
      const result = await adminTestDhlConnection();
      setLastTest(result);
      if (result.ok) {
        toast.success(result.message);
      } else {
        toast.error(result.message);
      }
    } catch (e) {
      toast.error(`Test failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setTesting(false);
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<Truck className="w-6 h-6" />}
        title="DHL Shipping"
        description="Configure DHL MyDHL API credentials so the shop can create shipments and track deliveries."
      />

      <SectionCard
        icon={<KeyRound className="w-5 h-5" />}
        title="DHL credentials"
        description="Secrets are encrypted with the project's Fernet key before being stored. Leave the key/secret blank to keep the existing value."
      >
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : (
          <div className="grid md:grid-cols-2 gap-4">
            <Field label="API key">
              <TextInput
                value={apiKey}
                onChange={(v) => setApiKey(v)}
                placeholder={settings?.api_key ? `Current: ${settings.api_key}` : "Enter DHL API key"}
              />
            </Field>
            <Field label="API secret">
              <TextInput
                type="password"
                value={apiSecret}
                onChange={(v) => setApiSecret(v)}
                placeholder={
                  settings?.api_secret ? `Current: ${settings.api_secret}` : "Enter DHL API secret"
                }
              />
            </Field>
            <Field label="Account number">
              <TextInput
                value={accountNumber}
                onChange={(v) => setAccountNumber(v)}
                placeholder="DHL shipper account number"
              />
            </Field>
            <Field label="Environment">
              <select
                value={environment}
                onChange={(e) => setEnvironment(e.target.value as "sandbox" | "production")}
                className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 focus:border-[#0b6e3e] focus:outline-none focus:ring-2 focus:ring-[#0b6e3e]/20"
              >
                <option value="sandbox">Sandbox (test)</option>
                <option value="production">Production</option>
              </select>
            </Field>

            <div className="md:col-span-2 flex flex-wrap items-center gap-3 pt-2">
              <button
                type="button"
                onClick={save}
                disabled={saving}
                className="inline-flex items-center gap-2 rounded-lg bg-[#0b6e3e] px-4 py-2 text-sm font-semibold text-white hover:bg-[#0a5f36] disabled:opacity-60"
              >
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                Save settings
              </button>
              <button
                type="button"
                onClick={test}
                disabled={testing}
                className="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-60"
              >
                {testing ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle2 className="w-4 h-4" />}
                Test connection
              </button>
              <span className="text-xs text-slate-500">
                {settings?.configured
                  ? "Credentials are configured."
                  : "No credentials yet — the module runs in demo mode (simulated tracking numbers)."}
              </span>
            </div>

            {lastTest && (
              <div
                className={`md:col-span-2 rounded-lg border p-3 text-sm flex items-start gap-2 ${
                  lastTest.ok
                    ? "border-emerald-200 bg-emerald-50 text-emerald-800"
                    : "border-rose-200 bg-rose-50 text-rose-800"
                }`}
              >
                {lastTest.ok ? (
                  <CheckCircle2 className="w-4 h-4 mt-0.5" />
                ) : (
                  <XCircle className="w-4 h-4 mt-0.5" />
                )}
                <span>
                  {lastTest.message}
                  {lastTest.stub && " (demo mode)"}
                </span>
              </div>
            )}
          </div>
        )}
      </SectionCard>

      <SectionCard
        icon={<Truck className="w-5 h-5" />}
        title="How it works"
        description="Once credentials are saved, the shop's admin order page exposes a 'Create DHL shipment' action that books a shipment and stores the tracking number on the order."
      >
        <ul className="text-sm text-slate-700 leading-relaxed list-disc pl-5 space-y-1">
          <li>
            Customers can track their parcels at{" "}
            <code className="px-1 py-0.5 bg-slate-100 rounded">/shop/track/&lt;tracking-number&gt;</code>.
          </li>
          <li>
            All DHL API calls are recorded in the admin audit log
            (<code className="px-1 py-0.5 bg-slate-100 rounded">admin.dhl.*</code> actions).
          </li>
          <li>
            If DHL is unreachable, the module gracefully falls back to a deterministic demo
            tracking number so orders can still be fulfilled.
          </li>
        </ul>
      </SectionCard>
    </CmsLayout>
  );
}