"use client";
import { useCallback, useRef, useState } from "react";

type Verdict = "real" | "uncertain" | "slop";

interface ScanResult {
  id: string;
  fileName: string;
  previewUrl: string;
  score: number; // 0-100, chance of being AI-generated
  verdict: Verdict;
  timestamp: string;
}

const CARD = "glass rounded-3xl p-2 shadow-card sm:p-3";

const VERDICT_STYLE: Record<
  Verdict,
  { label: string; text: string; border: string; dot: string; blurb: string }
> = {
  real: {
    label: "Real",
    text: "text-seal-green",
    border: "border-seal-green",
    dot: "bg-seal-green",
    blurb: "Light, grain and edges line up with an unedited capture.",
  },
  uncertain: {
    label: "Needs a look",
    text: "text-seal-amber",
    border: "border-seal-amber",
    dot: "bg-seal-amber",
    blurb: "Mixed signals — some regions read synthetic, others don't.",
  },
  slop: {
    label: "AI Slop",
    text: "text-seal-red",
    border: "border-seal-red",
    dot: "bg-seal-red",
    blurb: "Texture and lighting patterns match generative-model output.",
  },
};

function verdictFromScore(score: number): Verdict {
  if (score < 35) return "real";
  if (score <= 65) return "uncertain";
  return "slop";
}

function seedScoreFromName(name: string): number {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = (hash * 31 + name.charCodeAt(i)) % 9973;
  }
  return hash % 100;
}

function formatTimestamp(d: Date): string {
  const day = d.getDate().toString().padStart(2, "0");
  const month = d.toLocaleString("en-US", { month: "short" });
  const year = d.getFullYear();
  const time = d.toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  });
  return `${day} ${month} ${year} · ${time}`;
}

/* ---------------------------------------------------------------- */
/*  Meter — the signature element                                    */
/* ---------------------------------------------------------------- */

function ExposureMeter({ score, size = 148 }: { score: number; size?: number }) {
  const angle = -120 + (score / 100) * 240;
  const verdict = verdictFromScore(score);

  const r = size / 2 - 14;
  const cx = size / 2;
  const cy = size / 2;

  const ticks = Array.from({ length: 13 }, (_, i) => i);
  const gradId = "slop-needle-gradient";

  return (
    <div className="relative" style={{ width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <defs>
          <linearGradient id={gradId} x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#65EEFB" />
            <stop offset="45%" stopColor="#3466CE" />
            <stop offset="100%" stopColor="#955BE4" />
          </linearGradient>
        </defs>

        <circle cx={cx} cy={cy} r={r + 10} className="fill-paper-raised/70" stroke="#dbe1ea" strokeWidth="1" />
        <path d={describeArc(cx, cy, r, -120, 120)} fill="none" stroke="#dbe1ea" strokeWidth="3" strokeLinecap="round" />
        <path d={describeArc(cx, cy, r, -120, -40)} fill="none" stroke="#1f7a4f" strokeWidth="3" strokeLinecap="round" opacity="0.55" />
        <path d={describeArc(cx, cy, r, -40, 40)} fill="none" stroke="#b3791f" strokeWidth="3" strokeLinecap="round" opacity="0.55" />
        <path d={describeArc(cx, cy, r, 40, 120)} fill="none" stroke="#bf392e" strokeWidth="3" strokeLinecap="round" opacity="0.55" />

        {ticks.map((i) => {
          const a = -120 + (i / 12) * 240;
          const p1 = polarToCartesian(cx, cy, r - 6, a);
          const p2 = polarToCartesian(cx, cy, r - 1, a);
          return (
            <line key={i} x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke="#89A9FF" strokeWidth="1" opacity="0.5" />
          );
        })}

        <g transform={`rotate(${angle} ${cx} ${cy})`} style={{ transition: "transform 700ms cubic-bezier(0.22,1,0.36,1)" }}>
          <line x1={cx} y1={cy} x2={cx} y2={cy - r + 8} stroke="#9654f4" strokeWidth="2.5" strokeLinecap="round" />
          <circle cx={cx} cy={cy} r="4" fill="#9654f4" />
        </g>
      </svg>

      <div className="absolute inset-0 flex flex-col items-center justify-center pt-16">
        <span className="font-heading text-2xl font-semibold tabular-nums text-heading leading-5">{score}%</span>
        <span className={`mt-0.5 text-[10px] font-semibold uppercase tracking-[0.18em] ${VERDICT_STYLE[verdict].text}`}>
          {verdict === "real" ? "reads real" : verdict === "slop" ? "reads slop" : "reads mixed"}
        </span>
      </div>
    </div>
  );
}

function polarToCartesian(cx: number, cy: number, r: number, angleDeg: number) {
  const a = ((angleDeg - 90) * Math.PI) / 180;
  return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) };
}

function describeArc(cx: number, cy: number, r: number, startAngle: number, endAngle: number) {
  const start = polarToCartesian(cx, cy, r, endAngle);
  const end = polarToCartesian(cx, cy, r, startAngle);
  const largeArc = endAngle - startAngle <= 180 ? 0 : 1;
  return `M ${start.x} ${start.y} A ${r} ${r} 0 ${largeArc} 0 ${end.x} ${end.y}`;
}

/* ---------------------------------------------------------------- */
/*  Verdict stamp — wax-seal styled badge, uses the seal-* palette   */
/* ---------------------------------------------------------------- */

function VerdictStamp({ verdict, small = false }: { verdict: Verdict; small?: boolean }) {
  const v = VERDICT_STYLE[verdict];
  return (
    <span
      className={[
        "inline-flex -rotate-2 select-none items-center gap-1.5 rounded-full border-2 bg-paper-raised/60 font-heading font-bold uppercase tracking-[0.12em]",
        small ? "px-2 py-0.5 text-[10px]" : "px-3 py-1 text-xs",
        v.text,
        v.border,
      ].join(" ")}
    >
      <span className={`block h-1.5 w-1.5 rounded-full ${v.dot}`} />
      {v.label}
    </span>
  );
}

/* ---------------------------------------------------------------- */
/*  Icons (inline, no dependency)                                    */
/* ---------------------------------------------------------------- */

function IconUpload(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...props}>
      <path d="M4 15.5V17a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-1.5" strokeLinecap="round" />
      <path d="M12 15V4M12 4l-4 4M12 4l4 4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function IconChevron(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...props}>
      <path d="M9 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function IconAperture(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...props}>
      <circle cx="12" cy="12" r="9.25" />
      <path d="M14.5 3.6 9 13h6.5M9.5 20.4 15 11H8.5M20.4 9.5 11 15v-6.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* ---------------------------------------------------------------- */
/*  Main panel                                                        */
/* ---------------------------------------------------------------- */

export default function DetectorPanelDemo() {
  const [view, setView] = useState<"upload" | "history">("upload");
  const [analyzing, setAnalyzing] = useState(false);
  const [results, setResults] = useState<ScanResult[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
  const [dragActive, setDragActive] = useState(false);

  const runScan = useCallback((file: File) => {
    const previewUrl = URL.createObjectURL(file);
    setAnalyzing(true);
    // Simulated inference delay — wire this up to your real detection
    // endpoint; replace seedScoreFromName() with the model's response.
    window.setTimeout(() => {
      const score = seedScoreFromName(file.name + file.size);
      const result: ScanResult = {
        id: `${Date.now()}`,
        fileName: file.name,
        previewUrl,
        score,
        verdict: verdictFromScore(score),
        timestamp: formatTimestamp(new Date()),
      };
      setResults((prev) => [result, ...prev]);
      setAnalyzing(false);
      setView("history");
    }, 1400);
  }, []);

  const onFiles = useCallback(
    (files: FileList | null) => {
      const file = files?.[0];
      if (file) runScan(file);
    },
    [runScan]
  );

  return (
      <div className="relative">
        {/* header */}
        <div className="mb-2 flex items-end justify-between">
          <div>
            <div className="mb-1.5 flex items-center gap-2">
              <IconAperture className="h-4 w-4 text-link-1" />
              <span className="font-heading text-xs font-semibold uppercase tracking-[0.22em] text-gradient">
                Authenticity meter
              </span>
            </div>
          </div>

          {/* view toggle */}
          <div className="flex rounded-full border border-border/40 bg-paper-raised/60 p-0.5 text-[11px] font-semibold uppercase tracking-wider">
            {(["upload", "history"] as const).map((v) => (
              <button
                key={v}
                onClick={() => setView(v)}
                className={[
                  "rounded-full px-3 cursor-pointer py-1.5 font-heading transition-colors",
                  view === v ? "gradient1 text-white shadow-button" : "text-text/60",
                ].join(" ")}
              >
                {v === "upload" ? "Scan" : "Log"}
              </button>
            ))}
          </div>
        </div>

        {/* ---------------- UPLOAD VIEW ---------------- */}
        {view === "upload" && (
          <div>
            {!analyzing ? (
              <label
                htmlFor="slop-score-file-input"
                onDragOver={(e) => {
                  e.preventDefault();
                  setDragActive(true);
                }}
                onDragLeave={() => setDragActive(false)}
                onDrop={(e) => {
                  e.preventDefault();
                  setDragActive(false);
                  onFiles(e.dataTransfer.files);
                }}
                className={[
                  CARD,
                  "group flex cursor-pointer flex-col border-2 border-dashed transition-colors",
                  dragActive ? "border-link-1" : "border-border/50",
                ].join(" ")}
              >
                <div className="flex flex-col items-center justify-center px-6 py-14 text-center">
                  <div className="mb-5 flex h-16 w-16 items-center justify-center rounded-full bg-badge/30 transition-transform group-hover:scale-105">
                    <IconUpload className="h-7 w-7 text-link-1" />
                  </div>
                  <p className="font-heading text-base font-semibold text-heading">Upload an image to measure it</p>
                  <p className="mt-1.5 max-w-[26ch] text-sm text-text/70">
                    Drop an image here, or choose one from your library
                  </p>
                  <span className="gradient1 mt-6 rounded-full px-5 py-2.5 text-sm font-semibold text-white shadow-button">
                    Select photo
                  </span>
                  <button
                    type="button"
                    onClick={async () => {
                      try {
                        const items = await navigator.clipboard.read();
                        for (const item of items) {
                          const type = item.types.find((t) => t.startsWith("image/"));
                          if (type) {
                            const blob = await item.getType(type);
                            runScan(new File([blob], "pasted-image.png", { type }));
                            break;
                          }
                        }
                      } catch {
                        /* clipboard access unavailable — user can still use Select photo */
                      }
                    }}
                    className="mt-3 flex items-center gap-1.5 text-xs font-medium text-link underline decoration-dotted underline-offset-4"
                  >
                    or paste image
                  </button>
                  <input
                    ref={inputRef}
                    id="slop-score-file-input"
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={(e) => onFiles(e.target.files)}
                  />
                </div>
              </label>
            ) : (
              <div className={CARD}>
                <div className="flex flex-col items-center justify-center px-6 py-14 text-center">
                  <div className="relative mb-5 h-16 w-16">
                    <span className="absolute inset-0 animate-spin rounded-full border-2 border-transparent border-t-link-1 border-r-link-1" />
                    <span className="absolute inset-3 flex items-center justify-center">
                      <IconAperture className="h-6 w-6 text-link-1" />
                    </span>
                  </div>
                  <p className="font-heading text-base font-semibold text-heading">Metering the frame…</p>
                  <p className="mt-1.5 text-sm text-text/70">
                    Checking pixels, edges and light for signs of synthesis
                  </p>
                </div>
              </div>
            )}
          </div>
        )}

        {/* ---------------- HISTORY VIEW ---------------- */}
        {view === "history" && (
          <div className="flex flex-col gap-3">
            {results.length === 0 ? (
              <div className={CARD}>
                <div className="px-6 py-12 text-center">
                  <p className="text-sm text-text/70">Nothing metered yet — scan a photo to start your log.</p>
                  <button
                    onClick={() => setView("upload")}
                    className="gradient1 mt-4 rounded-full px-5 py-2 text-sm font-semibold text-white shadow-button"
                  >
                    Scan a photo
                  </button>
                </div>
              </div>
            ) : (
                <>
                <div className={[CARD, "grid w-full divide-y divide-gray-200 transition-colors"].join(" ")}>
                    {results.map((r) => (
                        <button key={r.id} className="text-left py-3">
                        <div className="flex w-full items-center gap-3.5 px-2 py-1">
                            {/* eslint-disable-next-line @next/next/no-img-element */}
                            <img
                            src={r.previewUrl}
                            alt=""
                            className="h-14 w-14 flex-shrink-0 rounded-xl object-cover"
                            style={{ boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.6)" }}
                            />
                            <div className="min-w-0 flex-1">
                            <div className="flex items-center gap-2">
                                <span className="font-heading text-sm font-bold tabular-nums text-heading">{r.score}%</span>
                                <VerdictStamp verdict={r.verdict} small />
                            </div>
                            <p className="mt-1 truncate text-xs text-text/70">{r.fileName}</p>
                            <p className="text-[11px] text-text/50">{r.timestamp}</p>
                            </div>
                            <IconChevron className="h-4 w-4 flex-shrink-0 text-text/40" />
                        </div>
                        </button>
                    ))}
                </div>
              </>
            )}
          </div>
        )}

        {/* latest scan detail — appears once at least one scan exists */}
        {results[0] && view === "history" && (
          <div className={[CARD, "mt-6"].join(" ")}>
            <div className="flex items-center justify-between px-3 py-3">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-text/60">Latest reading</p>
                <div className="mt-2">
                  <VerdictStamp verdict={results[0].verdict} />
                </div>
                <p className="mt-3 max-w-[22ch] text-xs leading-relaxed text-text/70">
                  {VERDICT_STYLE[results[0].verdict].blurb}
                </p>
              </div>
              <ExposureMeter score={results[0].score} size={132} />
            </div>
          </div>
        )}
      </div>
  );
}