"use client";

import { useCallback, useEffect, useState } from "react";
import { Store, CheckCircle2, XCircle, Ticket, RefreshCw, Mail, Wallet, Server, Copy, Plus, Trash2 } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Badge, Skeleton, Input } from "@/components/ui";
import { SettingsTabs } from "@/components/settings-tabs";
import { useToast } from "@/components/toast";

type Status =
  | { configured: false }
  | { configured: true; connected: boolean; shop: string; shopName?: string; error?: string };

type Ip = { id: number; ip_address: string; type: string; is_active: boolean };
type S2s = { postbackUrl: string; ips: Ip[] };

export default function IntegrationsPage() {
  const toast = useToast();
  const [status, setStatus] = useState<Status | null>(null);
  const [busy, setBusy] = useState<"push" | "sync" | null>(null);
  const [s2s, setS2s] = useState<S2s | null>(null);
  const [newIp, setNewIp] = useState("");

  const load = useCallback(async () => {
    setStatus(await api.get("/shopify/status"));
    api.get("/admin/s2s").then(setS2s).catch(() => {});
  }, []);

  const addIp = async () => {
    const ip = newIp.trim();
    if (!ip) return;
    try {
      await api.post("/admin/s2s/ip", { ip, type: ip.includes("/") ? "CIDR" : "SINGLE" });
      setNewIp("");
      setS2s(await api.get("/admin/s2s"));
      toast.success("IP added to whitelist.");
    } catch (e) {
      toast.error((e as Error).message);
    }
  };
  const removeIp = async (id: number) => {
    await api.del(`/admin/s2s/ip/${id}`);
    setS2s(await api.get("/admin/s2s"));
  };

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

  const pushCoupons = async () => {
    setBusy("push");
    try {
      const r = await api.post("/shopify/push-coupons");
      toast.success(`${r.created} discount code(s) created in Shopify${r.failed ? `, ${r.failed} failed` : ""}.`);
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setBusy(null);
    }
  };
  const syncOrders = async () => {
    setBusy("sync");
    try {
      const r = await api.post("/shopify/sync-orders");
      toast.success(`Synced ${r.fetched} orders — ${r.attributed} attributed to affiliates.`);
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="max-w-4xl">
      <PageHeader title="Settings" subtitle="Connect Shopify & other services" />
      <SettingsTabs />

      <div className="space-y-4">
        {/* Shopify — the core integration */}
        {!status ? (
          <Skeleton className="h-40" />
        ) : !status.configured ? (
          <Card title="Shopify">
            <div className="flex items-start gap-3">
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-amber-50 text-amber-600">
                <Store className="h-5 w-5" />
              </span>
              <div>
                <div className="flex items-center gap-2">
                  <h3 className="font-semibold text-gray-900">Not connected yet</h3>
                  <Badge tone="warning">Action needed</Badge>
                </div>
                <p className="mt-1 text-sm text-gray-500">
                  Add your store&apos;s custom-app token to <code className="rounded bg-gray-100 px-1">apps/api/.env</code> and restart the API.
                </p>
                <ol className="mt-4 list-decimal space-y-1.5 pl-5 text-sm text-gray-600">
                  <li>Shopify admin → <b>Settings → Apps and sales channels → Develop apps</b></li>
                  <li>Create an app → <b>Configure Admin API scopes</b>: <code className="rounded bg-gray-100 px-1">read_orders, write_discounts, read_products</code></li>
                  <li>Install the app → copy the <b>Admin API access token</b> (starts with <code>shpat_</code>)</li>
                  <li>Put your store domain + token into <code className="rounded bg-gray-100 px-1">apps/api/.env</code> and restart</li>
                </ol>
              </div>
            </div>
          </Card>
        ) : status.connected ? (
          <>
            <Card title="Shopify">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <span className="flex h-10 w-10 items-center justify-center rounded-lg bg-green-50 text-green-600">
                    <CheckCircle2 className="h-5 w-5" />
                  </span>
                  <div>
                    <h3 className="font-semibold text-gray-900">{status.shopName ?? "Connected"}</h3>
                    <p className="text-sm text-gray-500">{status.shop}</p>
                  </div>
                </div>
                <Badge tone="success">Connected</Badge>
              </div>
            </Card>

            <div className="grid gap-4 sm:grid-cols-2">
              <Card title="Discount codes" subtitle="Push affiliate coupons to Shopify">
                <p className="mb-4 text-sm text-gray-500">Creates a real, working discount code in your store for every active affiliate.</p>
                <Button icon={<Ticket className="h-4 w-4" />} loading={busy === "push"} onClick={pushCoupons}>Push coupons to Shopify</Button>
              </Card>
              <Card title="Orders" subtitle="Import & attribute real sales">
                <p className="mb-4 text-sm text-gray-500">Pulls recent orders and credits commission to affiliates whose coupon was used.</p>
                <Button variant="secondary" icon={<RefreshCw className="h-4 w-4" />} loading={busy === "sync"} onClick={syncOrders}>Sync orders now</Button>
              </Card>
            </div>
          </>
        ) : (
          <Card title="Shopify">
            <div className="flex items-start gap-3">
              <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-red-50 text-red-600">
                <XCircle className="h-5 w-5" />
              </span>
              <div>
                <h3 className="font-semibold text-gray-900">Token set, but couldn&apos;t connect</h3>
                <p className="mt-1 text-sm text-gray-500">Shop: {status.shop}</p>
                <p className="mt-1 text-sm text-red-600">{status.error}</p>
                <p className="mt-2 text-sm text-gray-500">Check the token and scopes, then restart the API.</p>
              </div>
            </div>
          </Card>
        )}

        {/* S2S postback + IP whitelist */}
        {s2s && (
          <Card title="Server-to-server (S2S) tracking" subtitle="Post conversions directly from your server + restrict by IP">
            <div className="mb-2 flex items-center gap-2 text-sm font-medium text-gray-700"><Server className="h-4 w-4" /> Postback URL</div>
            <div className="flex items-center gap-2">
              <code className="min-w-0 flex-1 truncate rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-700">{s2s.postbackUrl}</code>
              <Button size="sm" variant="secondary" icon={<Copy className="h-3.5 w-3.5" />} onClick={() => { navigator.clipboard?.writeText(s2s.postbackUrl); toast.success("Postback URL copied."); }}>Copy</Button>
            </div>
            <p className="mt-2 text-xs text-gray-400">Replace the {"{tokens}"} with your values when your server records a sale.</p>

            <div className="mt-5 mb-2 text-sm font-medium text-gray-700">Allowed IPs <span className="font-normal text-gray-400">(empty = allow all)</span></div>
            {s2s.ips.length === 0 ? (
              <p className="mb-3 rounded-lg bg-gray-50 px-3 py-2 text-xs text-gray-500">No IP restriction — conversions accepted from any server.</p>
            ) : (
              <ul className="mb-3 divide-y divide-gray-50 rounded-lg border border-gray-100">
                {s2s.ips.map((ip) => (
                  <li key={ip.id} className="flex items-center justify-between gap-2 px-3 py-2">
                    <span className="font-mono text-sm text-gray-700">{ip.ip_address} <Badge tone="neutral">{ip.type}</Badge></span>
                    <button onClick={() => removeIp(ip.id)} className="rounded-lg border border-gray-300 p-1.5 text-gray-500 hover:bg-red-50 hover:text-red-600"><Trash2 className="h-3.5 w-3.5" /></button>
                  </li>
                ))}
              </ul>
            )}
            <div className="flex items-end gap-2">
              <Input value={newIp} onChange={(e) => setNewIp(e.target.value)} placeholder="e.g. 203.0.113.10 or 203.0.113.0/24" />
              <Button icon={<Plus className="h-4 w-4" />} onClick={addIp}>Add IP</Button>
            </div>
          </Card>
        )}

        {/* Other integrations */}
        <Card title="More integrations">
          <ul className="divide-y divide-gray-50">
            <li className="flex items-center justify-between gap-4 py-3">
              <div className="flex items-center gap-3">
                <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-100 text-gray-500"><Mail className="h-5 w-5" /></span>
                <div>
                  <p className="text-sm font-medium text-gray-800">Email (SMTP)</p>
                  <p className="text-xs text-gray-500">Send real affiliate & payout emails from your own mailbox.</p>
                </div>
              </div>
              <Badge tone="neutral">Coming soon</Badge>
            </li>
            <li className="flex items-center justify-between gap-4 py-3">
              <div className="flex items-center gap-3">
                <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-100 text-gray-500"><Wallet className="h-5 w-5" /></span>
                <div>
                  <p className="text-sm font-medium text-gray-800">PayPal Payouts</p>
                  <p className="text-xs text-gray-500">Auto-pay affiliates to their PayPal — no manual transfers.</p>
                </div>
              </div>
              <Badge tone="neutral">Coming soon</Badge>
            </li>
          </ul>
        </Card>
      </div>
    </div>
  );
}
