"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Image from "next/image";
import Markdown from "react-markdown";

export default function FiberSettingDetailPage() {
  const { id } = useParams();
  const [setting, setSetting] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  // claim UI state
  const [claimBusy, setClaimBusy] = useState(false);
  const [claimMsg, setClaimMsg] = useState<string | null>(null);
  const [claimErr, setClaimErr] = useState<string | null>(null);

  useEffect(() => {
    const url =
    `${process.env.NEXT_PUBLIC_API_BASE_URL}/items/settings_fiber/${id}` +
    `?fields=` +
    [
      "submission_id",
      "setting_title",
      "uploader",
      "owner.id",
      "owner.first_name",
      "owner.last_name",
      "owner.email",
      "setting_notes",
      "photo.filename_disk",
      "photo.title",
      "screen.filename_disk",
      "screen.title",
      "mat.name",
      "mat_coat.name",
      "mat_color.name",
      "mat_opacity.opacity",
      "mat_thickness",
      "source.make",
      "source.model",
      "lens.field_size",
      "lens.focal_length",
      "focus",
      "laser_soft.name",
      "repeat_all",
      "fill_settings",
      "line_settings",
      "raster_settings",
    ].join(",");

    fetch(url, { cache: "no-store" })
    .then((res) => {
      if (!res.ok) throw new Error("Failed to load");
      return res.json();
    })
    .then((data) => setSetting(data.data))
    .catch(() => setSetting(null))
    .finally(() => setLoading(false));
  }, [id]);

  if (loading) return <p className="p-6">Loading setting...</p>;
  if (!setting) return <p className="p-6">Setting not found.</p>;

  const ownerName = (row: any) => {
    const o = row?.owner;
    if (!o) return null;
    const name = [o.first_name, o.last_name].filter(Boolean).join(" ").trim();
    return name || o.email || null;
  };

  const formatBoolean = (val: any) =>
  val ? "Enabled" : val === false ? "Disabled" : "—";

  const renderRepeaterCard = (title: string, fields: any[], items: any[]) => {
    const filtered = (items || []).filter((item) =>
    Object.values(item).some((v) => v !== null && v !== "")
    );
    if (filtered.length === 0) return null;
    return (
      <div className="mt-6">
      <h2 className="text-2xl font-semibold mb-2">{title}</h2>
      <div className="grid gap-4 grid-cols-1 md:grid-cols-2">
      {filtered.map((item, i) => (
        <div key={i} className="border border-border rounded-lg p-4 bg-card">
        {fields.map(({ key, label, condition }: any) => {
          const value = item[key];
          if (condition && !condition(item)) return null;
          return (
            <p key={key} className="text-sm">
            <strong>{label}:</strong>{" "}
            {typeof value === "boolean"
              ? formatBoolean(value)
              : value || "—"}
              </p>
          );
        })}
        </div>
      ))}
      </div>
      </div>
    );
  };

  const openSearchInNewTab = (value: string) => {
    const url = new URL("/fiber-settings", window.location.origin);
    url.searchParams.set("query", value);
    const a = document.createElement("a");
    a.href = url.toString();
    a.target = "_blank";
    a.rel = "noopener noreferrer";
    a.click();
  };

  const onClaim = async () => {
    setClaimBusy(true);
    setClaimErr(null);
    setClaimMsg(null);
    try {
      const r = await fetch("/api/claims", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          target_collection: "settings_fiber",
          target_id: id,
        }),
        cache: "no-store",
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) {
        throw new Error(
          data?.error || data?.errors?.[0]?.message || "Failed to submit claim"
        );
      }
      setClaimMsg("Claim request submitted for review.");
    } catch (e: any) {
      setClaimErr(e?.message || "Failed to submit claim");
    } finally {
      setClaimBusy(false);
    }
  };

  const owner = ownerName(setting);

  return (
    <div className="p-6 max-w-7xl mx-auto">
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
    {/* Title / Meta / Ownership */}
    <div className="card bg-card p-4 flex flex-col justify-between">
    <div>
    <h1 className="text-3xl font-bold mb-1">{setting.setting_title}</h1>

    <div className="space-y-1 text-sm text-muted-foreground mb-3">
    <p>
    <strong>Owner:</strong>{" "}
    {owner ? <span>{owner}</span> : <span>—</span>}
    </p>
    <p>
    <strong>Uploader:</strong> {setting.uploader || "—"}
    </p>
    </div>

    {!owner && (
      <div className="flex items-center gap-2">
      <button
      onClick={onClaim}
      disabled={claimBusy}
      className="px-3 py-1.5 rounded bg-accent text-background text-sm disabled:opacity-60"
      >
      {claimBusy ? "Submitting…" : "Claim this setting"}
      </button>
      {claimMsg && (
        <span className="text-green-500 text-sm">{claimMsg}</span>
      )}
      {claimErr && (
        <span className="text-red-500 text-sm">{claimErr}</span>
      )}
      </div>
    )}
    </div>

    <a
    href="/fiber-settings"
    className="inline-block mt-2 px-4 py-2 bg-accent text-background rounded-md text-sm self-start"
    >
    ← Back to Fiber Settings
    </a>
    </div>

    {/* Result Photo + Material */}
    <div className="card bg-card p-4 grid grid-cols-1 md:grid-cols-2 gap-4 items-start">
    <div className="flex justify-center">
    {setting.photo?.filename_disk && (
      <a
      href={`https://forms.lasereverything.net/assets/${setting.photo.filename_disk}`}
      target="_blank"
      rel="noopener noreferrer"
      >
      <Image
      src={`https://forms.lasereverything.net/assets/${setting.photo.filename_disk}`}
      alt={setting.photo?.title || "Laser preview"}
      width={250}
      height={250}
      className="rounded object-contain max-w-[250px] max-h-[250px]"
      />
      </a>
    )}
    </div>

    <div>
    <h2 className="text-xl font-semibold mb-2">Material</h2>
    <p>
    <strong>Material:</strong>{" "}
    <span
    className="cursor-pointer underline hover:text-accent"
    onClick={() => openSearchInNewTab(setting.mat?.name)}
    >
    {setting.mat?.name || "—"}
    </span>
    </p>
    <p>
    <strong>Coating:</strong>{" "}
    <span
    className="cursor-pointer underline hover:text-accent"
    onClick={() => openSearchInNewTab(setting.mat_coat?.name)}
    >
    {setting.mat_coat?.name || "—"}
    </span>
    </p>
    <p>
    <strong>Color:</strong> {setting.mat_color?.name || "—"}
    </p>
    <p>
    <strong>Opacity:</strong> {setting.mat_opacity?.opacity || "—"}
    </p>
    <p>
    <strong>Thickness:</strong>{" "}
    {setting.mat_thickness ? `${setting.mat_thickness} mm` : "Not Applicable"}
    </p>
    </div>
    </div>

    {/* Setup */}
    <div className="card bg-card p-4">
    <h2 className="text-xl font-semibold mb-2">Setup</h2>
    <p>
    <strong>Software:</strong> {setting.laser_soft?.name || "—"}
    </p>
    <p>
    <strong>Repeat All (global):</strong> {setting.repeat_all ?? "—"}
    </p>
    <p className="mt-4">
    <strong>Focus:</strong> {setting.focus ?? "—"} mm
    </p>
    <small>-Values Focus Closer | +Values Focus Further</small>
    </div>

    {/* Laser (heading above specs; screen image same size as result) */}
    <div className="card bg-card p-4">
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start">
    {/* Screen image */}
    <div className="flex justify-center">
    {setting.screen?.filename_disk ? (
      <a
      href={`https://forms.lasereverything.net/assets/${setting.screen.filename_disk}`}
      target="_blank"
      rel="noopener noreferrer"
      title={setting.screen?.title || "Screenshot"}
      >
      <Image
      src={`https://forms.lasereverything.net/assets/${setting.screen.filename_disk}`}
      alt={setting.screen?.title || "Screenshot"}
      width={250}
      height={250}
      className="rounded object-contain max-w-[250px] max-h-[250px]"
      />
      </a>
    ) : (
      <div className="text-sm text-muted-foreground">No screenshot</div>
    )}
    </div>

    {/* Specs + heading */}
    <div>
    <h2 className="text-xl font-semibold mb-2">Laser</h2>
    <p>
    <strong>Source Make:</strong> {setting.source?.make || "—"}
    </p>
    <p>
    <strong>Source Model:</strong>{" "}
    <span
    className="cursor-pointer underline hover:text-accent"
    onClick={() => openSearchInNewTab(setting.source?.model)}
    >
    {setting.source?.model || "—"}
    </span>
    </p>
    <p>
    <strong>Lens:</strong>{" "}
    <span
    className="cursor-pointer underline hover:text-accent"
    onClick={() => openSearchInNewTab(setting.lens?.field_size)}
    >
    {setting.lens?.field_size || "—"}
    </span>{" "}
    mm | {setting.lens?.focal_length || "—"}
    </p>
    </div>
    </div>
    </div>
    </div>

    {/* Notes */}
    {setting.setting_notes && (
      <div className="prose dark:prose-invert mt-6">
      <h2>Notes</h2>
      <Markdown>{setting.setting_notes}</Markdown>
      </div>
    )}

    <hr className="my-6 border-muted" />

    {/* Fill / Line / Raster */}
    {renderRepeaterCard(
      "Fill Settings",
      [
        { key: "fill_name", label: "Fill Name" },
        { key: "power", label: "Power (%)" },
                        { key: "speed", label: "Speed (mm/s)" },
                        { key: "frequency", label: "Frequency (kHz)" },
                        { key: "pulse", label: "Pulse Width (ns)" },
                        { key: "interval", label: "Interval (mm)" },
                        { key: "pass", label: "Passes" },
                        { key: "type", label: "Type" },
                        { key: "angle", label: "Angle (°)" },
                        { key: "auto", label: "Auto-Rotate" },
                        { key: "increment", label: "Increment (°)", condition: (e: any) => e.auto },
                        { key: "cross", label: "Crosshatch" },
                        { key: "flood", label: "Flood Fill" },
                        { key: "air", label: "Air Assist" },
      ],
      setting.fill_settings
    )}

    {renderRepeaterCard(
      "Line Settings",
      [
        { key: "name", label: "Line Name" },
        { key: "power", label: "Power (%)" },
                        { key: "speed", label: "Speed (mm/s)" },
                        { key: "frequency", label: "Frequency (kHz)" },
                        { key: "pulse", label: "Pulse Width (ns)" },
                        { key: "perf", label: "Perforation Mode" },
                        { key: "cut", label: "Cut (mm)", condition: (e: any) => e.perf },
                        { key: "skip", label: "Skip (mm)", condition: (e: any) => e.perf },
                        { key: "wobble", label: "Wobble Mode" },
                        { key: "step", label: "Step (mm)", condition: (e: any) => e.wobble },
                        { key: "size", label: "Size (mm)", condition: (e: any) => e.wobble },
                        { key: "pass", label: "Passes" },
                        { key: "air", label: "Air Assist" },
      ],
      setting.line_settings
    )}

    {renderRepeaterCard(
      "Raster Settings",
      [
        { key: "name", label: "Raster Name" },
        { key: "power", label: "Power (%)" },
                        { key: "speed", label: "Speed (mm/s)" },
                        { key: "frequency", label: "Frequency (kHz)" },
                        { key: "pulse", label: "Pulse Width (ns)" },
                        { key: "type", label: "Type" },
                        { key: "dither", label: "Dither" },
                        {
                          key: "halftone_cell",
                          label: "Cell Size (mm)",
                        condition: (e: any) => e.dither === "halftone",
                        },
                        {
                          key: "halftone_angle",
                          label: "Halftone Angle",
                          condition: (e: any) => e.dither === "halftone",
                        },
                        { key: "inversion", label: "Image Inverted" },
                        { key: "interval", label: "Interval (mm)" },
                        { key: "dot", label: "Dot-width Adjustment (mm)" },
                        { key: "pass", label: "Passes" },
                        { key: "cross", label: "Crosshatch" },
                        { key: "air", label: "Air Assist" },
      ],
      setting.raster_settings
    )}
    </div>
  );
}
