import { prisma } from "@/lib/prisma";
import { isCJConfigured } from "@/lib/cj";
import CJConnectionTest from "@/components/admin/CJConnectionTest";
import { CheckCircle2, XCircle, AlertTriangle } from "lucide-react";

export const dynamic = "force-dynamic";

function StatusPill({ ok, label }: { ok: boolean; label: string }) {
  return (
    <span
      className={`text-xs font-semibold px-2.5 py-1 rounded-full ${
        ok ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
      }`}
    >
      {label}
    </span>
  );
}

function ConfigRow({ name, ok, hint }: { name: string; ok: boolean; hint: string }) {
  return (
    <div className="flex items-start gap-3 py-2.5 border-b border-gray-50 last:border-0">
      {ok ? (
        <CheckCircle2 className="h-4 w-4 text-green-600 shrink-0 mt-0.5" />
      ) : (
        <XCircle className="h-4 w-4 text-red-500 shrink-0 mt-0.5" />
      )}
      <div className="min-w-0">
        <code className="text-xs font-mono font-semibold text-gray-800">{name}</code>
        <p className="text-xs text-gray-500 mt-0.5">{hint}</p>
      </div>
    </div>
  );
}

export default async function AdminSettingsPage() {
  const hasApiKey = Boolean(process.env.CJ_API_KEY);
  const hasStaticToken = Boolean(process.env.CJ_ACCESS_TOKEN);
  const cjReady = isCJConfigured();

  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET ?? "";
  const webhookReady = webhookSecret.startsWith("whsec_") && !webhookSecret.includes("your_webhook");

  const [linkedProducts, totalProducts, forwardedOrders, failedOrders, trackedOrders] =
    await Promise.all([
      prisma.product.count({ where: { NOT: { cjVariantId: null } } }),
      prisma.product.count(),
      prisma.order.count({ where: { NOT: { cjOrderId: null } } }),
      prisma.order.count({
        where: { cjOrderId: null, cjStatus: { in: ["FAILED", "ADDRESS_INCOMPLETE", "NOT_CONFIGURED"] } },
      }),
      prisma.order.count({ where: { NOT: { trackingNumber: null } } }),
    ]);

  const baseUrl = process.env.NEXTAUTH_URL ?? "http://localhost:3000";

  return (
    <div className="p-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">Settings</h1>
        <p className="text-gray-500 mt-1">Integration status and configuration</p>
      </div>

      <div className="space-y-8 max-w-3xl">
        {/* CJ Dropshipping Integration */}
        <div className="bg-white rounded-2xl shadow-sm p-8">
          <div className="flex items-center justify-between mb-2">
            <h2 className="text-lg font-bold text-gray-900">CJ Dropshipping Integration</h2>
            <StatusPill ok={cjReady} label={cjReady ? "Configured" : "Not configured"} />
          </div>
          <p className="text-sm text-gray-500 mb-6">
            Orders containing CJ-linked products are forwarded to CJ automatically once Stripe confirms payment.
          </p>

          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
            {[
              { label: "Products linked", value: `${linkedProducts}/${totalProducts}` },
              { label: "Orders sent to CJ", value: forwardedOrders },
              { label: "With tracking", value: trackedOrders },
              { label: "Failed", value: failedOrders },
            ].map((stat) => (
              <div key={stat.label} className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                <p className="text-xl font-bold text-gray-900">{stat.value}</p>
                <p className="text-xs text-gray-500 mt-0.5">{stat.label}</p>
              </div>
            ))}
          </div>

          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 mb-1">Environment variables</h4>
            <ConfigRow
              name="CJ_API_KEY"
              ok={hasApiKey}
              hint="Recommended. Access tokens are fetched and refreshed automatically. Get it from the CJ Developer Portal → API Key."
            />
            <ConfigRow
              name="CJ_ACCESS_TOKEN"
              ok={hasStaticToken}
              hint="Optional fallback if no API key is set. Expires after ~15 days and must be replaced by hand."
            />
            <ConfigRow
              name="CJ_DEFAULT_LOGISTIC"
              ok={Boolean(process.env.CJ_DEFAULT_LOGISTIC)}
              hint="Optional. Pins one shipping method (e.g. “CJPacket Ordinary”). When unset, the cheapest live quote is used."
            />
            <ConfigRow
              name="CRON_SECRET"
              ok={Boolean(process.env.CRON_SECRET)}
              hint={`Needed for scheduled tracking sync at ${baseUrl}/api/cron/cj-sync`}
            />
          </div>

          <CJConnectionTest />

          <div className="bg-gray-50 rounded-xl p-4 border border-gray-100 mt-6">
            <h4 className="text-sm font-semibold text-gray-700 mb-2">How it works:</h4>
            <ol className="text-xs text-gray-500 space-y-1.5 list-decimal list-inside">
              <li>Add a CJ Product ID &amp; Variant ID to products in your catalog (Products → Edit)</li>
              <li>When a customer completes checkout and payment succeeds, Stripe calls the webhook below</li>
              <li>The order — with the customer&apos;s full address — is forwarded to CJ Dropshipping</li>
              <li>CJ fulfils and ships directly to your customer</li>
              <li>Tracking info is synced back to the order (Orders → Sync CJ tracking, or the cron endpoint)</li>
            </ol>
          </div>
        </div>

        {/* Stripe Webhook */}
        <div className="bg-white rounded-2xl shadow-sm p-8">
          <div className="flex items-center justify-between mb-2">
            <h2 className="text-lg font-bold text-gray-900">Stripe Webhook</h2>
            <StatusPill ok={webhookReady} label={webhookReady ? "Configured" : "Not configured"} />
          </div>
          <p className="text-sm text-gray-500 mb-6">
            Without a valid signing secret every webhook is rejected, so orders never reach CJ.
          </p>

          {!webhookReady && (
            <div className="flex items-start gap-3 bg-amber-50 border border-amber-100 text-amber-800 rounded-xl p-4 mb-5 text-xs">
              <AlertTriangle className="h-4 w-4 shrink-0 mt-0.5" />
              <div>
                <p className="font-semibold">STRIPE_WEBHOOK_SECRET is missing or still a placeholder.</p>
                <p className="mt-1">
                  Local testing: run{" "}
                  <code className="font-mono bg-amber-100 px-1 py-0.5 rounded">
                    stripe listen --forward-to localhost:3000/api/webhooks/stripe
                  </code>{" "}
                  and copy the <code className="font-mono">whsec_…</code> it prints into{" "}
                  <code className="font-mono">.env.local</code>.
                </p>
              </div>
            </div>
          )}

          <div className="space-y-5">
            <div>
              <label className="label">Webhook Endpoint URL</label>
              <input
                type="text"
                readOnly
                value={`${baseUrl}/api/webhooks/stripe`}
                className="input-field bg-gray-50 font-mono text-xs"
              />
            </div>
            <div>
              <label className="label">Events to Listen For</label>
              <div className="text-xs text-gray-500 bg-gray-50 rounded-xl p-3 font-mono space-y-1">
                <p>checkout.session.completed</p>
                <p>customer.subscription.deleted</p>
              </div>
            </div>
          </div>
        </div>

        {/* General */}
        <div className="bg-white rounded-2xl shadow-sm p-8">
          <h2 className="text-lg font-bold text-gray-900 mb-1">General</h2>
          <p className="text-sm text-gray-500 mb-6">
            These values come from your environment file — edit <code className="font-mono">.env.local</code> and restart to change them.
          </p>
          <div className="space-y-5">
            <div>
              <label className="label">Site URL</label>
              <input type="text" readOnly value={baseUrl} className="input-field bg-gray-50" />
            </div>
            <div>
              <label className="label">Admin Email</label>
              <input
                type="email"
                readOnly
                value={process.env.ADMIN_EMAIL ?? "—"}
                className="input-field bg-gray-50"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
