"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
  Play, Clock, Wifi, WifiOff, HelpCircle, AlertCircle,
  Building2, Globe,
} from "lucide-react";

// ─── Cost summary stats row ───────────────────────────────────────────────────

interface CostSummary {
  totalLeads: number;
  totalCompletedAudits: number;
  last30dCompletedAudits: number;
  last30dGateHits: number;
  estimatedLast30dCost: number;
  estimatedSavedLast30d: number;
}

function PublicAuditStats() {
  const [stats, setStats] = useState<CostSummary | null>(null);
  useEffect(() => {
    fetch("/api/admin/public-audit/cost-summary")
      .then((r) => r.ok ? r.json() : null)
      .then((d) => { if (d) setStats(d as CostSummary); })
      .catch(() => {/* non-fatal */});
  }, []);

  if (!stats) return null;

  return (
    <div className="bg-white border border-slate-200 rounded-xl px-5 py-3 flex flex-wrap gap-5 text-sm">
      <span className="text-slate-500">Public audits:</span>
      <span className="font-semibold text-slate-800">{stats.last30dCompletedAudits} completed (30d)</span>
      <span className="text-slate-400">·</span>
      <span className="text-slate-600">Est. cost: <span className="font-semibold text-slate-800">${stats.estimatedLast30dCost.toFixed(2)}</span></span>
      <span className="text-slate-400">·</span>
      <span className="text-slate-600">Gate saved: <span className="font-semibold text-emerald-700">${stats.estimatedSavedLast30d.toFixed(2)}</span> ({stats.last30dGateHits} blocked)</span>
      <span className="text-slate-400">·</span>
      <span className="text-slate-500">{stats.totalLeads} total leads</span>
    </div>
  );
}

// ─── Types ────────────────────────────────────────────────────────────────────

type AuditMode = "auto" | "first-party" | "third-party";
type FormMode = "unselected" | "first-party" | "third-party";

interface BrandOption {
  id: string;
  name: string;
  domain: string | null;
  siteTagActive: boolean;
}

const MODE_LABELS: Record<AuditMode, string> = {
  auto: "Auto",
  "first-party": "1st-party",
  "third-party": "3rd-party",
};

const MODE_DESCRIPTIONS: Record<AuditMode, string> = {
  auto: "Detect Site Tag; include first-party data if installed.",
  "first-party": "Always include first-party data regardless of tag detection.",
  "third-party": "Skip first-party data even if Site Tag is installed.",
};

// ─── Shared sub-components ────────────────────────────────────────────────────

function AuditModeToggle({ value, onChange }: { value: AuditMode; onChange: (v: AuditMode) => void }) {
  return (
    <div>
      <label className="block text-sm font-medium text-slate-700 mb-2 flex items-center gap-1">
        Audit Mode
        <span title="Controls whether first-party behavioral data is included">
          <HelpCircle className="w-3.5 h-3.5 text-slate-400" />
        </span>
      </label>
      <div className="flex rounded-lg border border-slate-200 overflow-hidden">
        {(["auto", "first-party", "third-party"] as AuditMode[]).map((mode) => (
          <button
            key={mode}
            type="button"
            onClick={() => onChange(mode)}
            className={`flex-1 px-3 py-2 text-xs font-medium transition-colors border-r last:border-r-0 border-slate-200 ${
              value === mode ? "bg-slate-900 text-white" : "bg-white text-slate-600 hover:bg-slate-50"
            }`}
          >
            {MODE_LABELS[mode]}
          </button>
        ))}
      </div>
      <p className="text-xs text-slate-400 mt-1.5">{MODE_DESCRIPTIONS[value]}</p>
    </div>
  );
}

function LocalToggle({ value, onChange }: { value: boolean; onChange: (v: boolean) => void }) {
  return (
    <div className="flex items-center gap-2">
      <input
        type="checkbox"
        id="isLocal"
        checked={value}
        onChange={(e) => onChange(e.target.checked)}
        className="rounded"
      />
      <label htmlFor="isLocal" className="text-sm text-slate-700">
        Local SEO audit (location-specific signals)
      </label>
    </div>
  );
}

// ─── 1st-party form ───────────────────────────────────────────────────────────

function FirstPartyForm({
  brand,
  onSubmit,
  submitting,
  error,
}: {
  brand: BrandOption;
  onSubmit: (auditMode: AuditMode, isLocal: boolean) => void;
  submitting: boolean;
  error: string | null;
}) {
  const [auditMode, setAuditMode] = useState<AuditMode>("auto");
  const [isLocal, setIsLocal] = useState(false);

  const tagForced = auditMode === "third-party";

  return (
    <div className="rounded-xl border border-indigo-100 bg-indigo-50/40 p-5 space-y-4">
      {/* Brand summary row */}
      <div className="flex items-start gap-3">
        <div className="w-9 h-9 rounded-lg bg-indigo-100 flex items-center justify-center shrink-0">
          <Building2 className="w-4 h-4 text-indigo-600" />
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-sm font-semibold text-slate-900 leading-snug">{brand.name}</p>
          {brand.domain && (
            <p className="text-xs text-slate-500 mt-0.5 flex items-center gap-1">
              <Globe className="w-3 h-3 shrink-0" />
              {brand.domain}
            </p>
          )}
        </div>

        {/* Site Tag indicator */}
        <div className="shrink-0">
          {tagForced ? (
            <span className="inline-flex items-center gap-1 text-[11px] font-medium text-amber-700 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-full">
              <AlertCircle className="w-3 h-3" /> Forced 3rd-party
            </span>
          ) : brand.siteTagActive ? (
            <span className="inline-flex items-center gap-1 text-[11px] font-medium text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded-full">
              <Wifi className="w-3 h-3" /> Tag active
            </span>
          ) : (
            <span className="inline-flex items-center gap-1 text-[11px] font-medium text-slate-500 bg-slate-50 border border-slate-200 px-2 py-0.5 rounded-full">
              <WifiOff className="w-3 h-3" /> No Tag
            </span>
          )}
        </div>
      </div>

      <div className="border-t border-indigo-100" />

      <AuditModeToggle value={auditMode} onChange={setAuditMode} />
      <LocalToggle value={isLocal} onChange={setIsLocal} />

      {error && (
        <div className="px-3 py-2 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          {error}
        </div>
      )}

      <button
        type="button"
        disabled={submitting}
        onClick={() => onSubmit(auditMode, isLocal)}
        className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
      >
        {submitting ? (
          <><Clock className="w-4 h-4 animate-spin" /> Starting audit…</>
        ) : (
          <><Play className="w-4 h-4" /> Run Audit</>
        )}
      </button>

      <p className="text-center text-xs text-slate-500">
        Auditing <span className="font-medium">{brand.name}</span> using stored brand profile.
      </p>
    </div>
  );
}

// ─── 3rd-party form ───────────────────────────────────────────────────────────

function ThirdPartyForm({
  onSubmit,
  submitting,
  error,
}: {
  onSubmit: (fields: {
    website: string;
    brandName: string;
    services: string[];
    competitors: string[];
    locations: string[];
    auditMode: AuditMode;
    isLocal: boolean;
  }) => void;
  submitting: boolean;
  error: string | null;
}) {
  const [website, setWebsite] = useState("");
  const [brandName, setBrandName] = useState("");
  const [services, setServices] = useState("");
  const [competitors, setCompetitors] = useState("");
  const [locations, setLocations] = useState("");
  const [auditMode, setAuditMode] = useState<AuditMode>("auto");
  const [isLocal, setIsLocal] = useState(false);

  const canSubmit = website.trim().length > 0 && brandName.trim().length > 0;

  function handleSubmit() {
    if (!canSubmit) return;
    onSubmit({
      website: website.trim(),
      brandName: brandName.trim(),
      services: services.split(",").map((s) => s.trim()).filter(Boolean),
      competitors: competitors.split(",").map((s) => s.trim()).filter(Boolean),
      locations: locations.split(",").map((s) => s.trim()).filter(Boolean),
      auditMode,
      isLocal,
    });
  }

  return (
    <div className="rounded-xl border border-slate-200 bg-white p-5 space-y-4">
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          Website URL <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={website}
          onChange={(e) => setWebsite(e.target.value)}
          placeholder="prospect-site.com"
          className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          Brand / Company Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={brandName}
          onChange={(e) => setBrandName(e.target.value)}
          placeholder="Prospect Co"
          className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Services (comma-separated)</label>
        <input
          type="text"
          value={services}
          onChange={(e) => setServices(e.target.value)}
          placeholder="cardiology, echocardiography, vascular care"
          className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Competitors (comma-separated)</label>
        <input
          type="text"
          value={competitors}
          onChange={(e) => setCompetitors(e.target.value)}
          placeholder="texasheart.org, cardiology.com"
          className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">Locations (comma-separated)</label>
        <input
          type="text"
          value={locations}
          onChange={(e) => setLocations(e.target.value)}
          placeholder="Houston, TX; Sugar Land, TX"
          className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300"
        />
      </div>

      <AuditModeToggle value={auditMode} onChange={setAuditMode} />
      <LocalToggle value={isLocal} onChange={setIsLocal} />

      {error && (
        <div className="px-3 py-2 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          {error}
        </div>
      )}

      <button
        type="button"
        disabled={submitting || !canSubmit}
        onClick={handleSubmit}
        className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-slate-900 text-white text-sm font-medium rounded-lg hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
      >
        {submitting ? (
          <><Clock className="w-4 h-4 animate-spin" /> Starting audit…</>
        ) : (
          <><Play className="w-4 h-4" /> Run Audit</>
        )}
      </button>

      <p className="text-center text-xs text-slate-500">
        Auditing a prospect or unowned site. No 1st-party data will be available.
      </p>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function AdminAuditsPage() {
  const router = useRouter();

  const [brands, setBrands] = useState<BrandOption[]>([]);
  const [brandsLoading, setBrandsLoading] = useState(true);

  // Picker state: "" = unselected, "none" = 3rd-party, "<id>" = 1st-party
  const [pickerValue, setPickerValue] = useState("");
  const formMode: FormMode =
    pickerValue === "" ? "unselected"
    : pickerValue === "none" ? "third-party"
    : "first-party";

  const selectedBrand = brands.find((b) => b.id === pickerValue) ?? null;

  // Submit state (shared between both form modes)
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load brands list
  useEffect(() => {
    fetch("/api/admin/brands?limit=200&sort=createdAt")
      .then((r) => r.json())
      .then((data: { brands: BrandOption[] }) => {
        const sorted = [...(data.brands ?? [])].sort((a, b) => a.name.localeCompare(b.name));
        setBrands(sorted);
        setBrandsLoading(false);
      })
      .catch(() => setBrandsLoading(false));
  }, []);

  // Clear error on mode switch
  function handlePickerChange(value: string) {
    setPickerValue(value);
    setError(null);
  }

  async function triggerAudit(body: object) {
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch("/api/admin/audits/trigger", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error((data as { error?: string }).error ?? "Failed to trigger audit");
      }
      const { auditId } = (await res.json()) as { auditId: string };
      router.push(`/admin/audits/${auditId}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
      setSubmitting(false);
    }
  }

  function handleFirstPartySubmit(auditMode: AuditMode, isLocal: boolean) {
    if (!selectedBrand) return;
    triggerAudit({
      brandId: selectedBrand.id,
      website: selectedBrand.domain ?? "",
      brandName: selectedBrand.name,
      auditMode,
      isLocal,
    });
  }

  function handleThirdPartySubmit(fields: {
    website: string;
    brandName: string;
    services: string[];
    competitors: string[];
    locations: string[];
    auditMode: AuditMode;
    isLocal: boolean;
  }) {
    triggerAudit({
      website: fields.website,
      brandName: fields.brandName,
      services: fields.services,
      competitors: fields.competitors,
      locations: fields.locations,
      auditMode: fields.auditMode,
      isLocal: fields.isLocal,
    });
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">meSEO Audit Engine</h1>
        <p className="text-sm text-slate-500 mt-1">
          Select a brand for a 1st-party audit, or run a standalone prospect audit.
        </p>
      </div>

      <PublicAuditStats />

      <div className="space-y-3">
        {/* ── Brand picker ── */}
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <label className="block text-sm font-medium text-slate-700 mb-2">
            Select brand or audit type
          </label>
          <select
            value={pickerValue}
            onChange={(e) => handlePickerChange(e.target.value)}
            disabled={brandsLoading}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300 disabled:opacity-50 bg-white"
          >
            <option value="" disabled>— Select a brand —</option>
            {brands.map((b) => (
              <option key={b.id} value={b.id}>
                {b.name}{b.domain ? ` (${b.domain})` : ""}  ·  {b.siteTagActive ? "Tag active" : "No Tag"}
              </option>
            ))}
            {brands.length > 0 && <option disabled>──────────────────────────────</option>}
            <option value="none">— Run 3rd-party audit (no brand) —</option>
          </select>

          {formMode === "unselected" && !brandsLoading && (
            <p className="text-xs text-slate-400 mt-2">
              Choose an existing brand to include 1st-party data, or select the 3rd-party option for a standalone prospect audit.
            </p>
          )}
        </div>

        {/* ── Contextual form ── */}
        {formMode === "first-party" && selectedBrand && (
          <FirstPartyForm
            brand={selectedBrand}
            onSubmit={handleFirstPartySubmit}
            submitting={submitting}
            error={error}
          />
        )}

        {formMode === "third-party" && (
          <ThirdPartyForm
            onSubmit={handleThirdPartySubmit}
            submitting={submitting}
            error={error}
          />
        )}
      </div>

      <p className="text-xs text-slate-400 text-center">
        Audits take 3–5 minutes. You&apos;ll be redirected to the live report.
      </p>
    </div>
  );
}
