"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 UVSettingDetailPage() {
  const { id } = useParams();
  const [setting, setSetting] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) return;
    fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/items/settings_uv/${id}?fields=submission_id,setting_title,uploader,setting_notes,photo.filename_disk,mat.name,mat_coat.name,mat_color.name,mat_opacity.opacity,mat_thickness,source.model,lens.field_size,lens.focal_length,focus,fill_settings,line_settings,raster_settings`)
      .then((res) => {
        if (!res.ok) throw new Error("Failed to load");
        return res.json();
      })
      .then((data) => {
        setSetting(data.data);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [id]);

  const openSearchInNewTab = (value) => {
    if (!value || typeof window === "undefined") return;
    const url = new URL("/uv-settings", window.location.origin);
    url.searchParams.set("query", value);
    window.open(url.toString(), "_blank", "noopener,noreferrer");
  };

  const renderRepeaterCard = (title, fields, data) => {
    if (!data || !Array.isArray(data) || data.length === 0) return null;
    return (
      <div className="card bg-card p-4">
        <h2 className="text-xl font-semibold mb-2">{title}</h2>
        {data.map((item, i) => (
          <div key={i} className="mb-4 border-b border-muted pb-2">
            {fields.map((field) =>
              field.condition === undefined || field.condition(item) ? (
                <p key={field.key}>
                  <strong>{field.label}:</strong>{" "}
                  {item[field.key] !== undefined && item[field.key] !== null ? item[field.key].toString() : "—"}
                </p>
              ) : null
            )}
          </div>
        ))}
      </div>
    );
  };

  if (loading) return <div className="p-6 max-w-7xl mx-auto">Loading…</div>;
  if (!setting) return <div className="p-6 max-w-7xl mx-auto">Setting not found.</div>;

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        <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>
            <p className="text-muted-foreground mb-4">Uploaded by: {setting.uploader || "—"}</p>
          </div>
          <a
            href="/uv-settings"
            className="inline-block mt-2 px-4 py-2 bg-accent text-background rounded-md text-sm self-start"
          >
            ← Back to UV Settings
          </a>
        </div>

        <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 && (
              <Image
                src={`${process.env.NEXT_PUBLIC_API_BASE_URL}/assets/${setting.photo.filename_disk}`}
                alt="Preview"
                width={300}
                height={300}
                className="rounded-md"
              />
            )}
          </div>
          <div>
            <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` : "—"}</p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="card bg-card p-4">
          <h2 className="text-xl font-semibold mb-2">Laser</h2>
          <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> {setting.lens?.field_size || "—"} mm | {setting.lens?.focal_length || "—"} mm</p>
        </div>

        <div className="card bg-card p-4">
          <h2 className="text-xl font-semibold mb-2">Focus</h2>
          <p><strong>Focus:</strong> {setting.focus || "—"}</p>
        </div>
      </div>

      <div className="card bg-card p-4 mt-6">
        <h2 className="text-xl font-semibold mb-2">Notes</h2>
        <div className="prose dark:prose-invert">
          <Markdown>{setting.setting_notes || "—"}</Markdown>
        </div>
      </div>

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

      {renderRepeaterCard("Fill Settings", [
        { key: "name", label: "Fill Name" },
        { 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) => 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: "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 Override" },
        { key: "skip", label: "Skip Pass" },
        { key: "wobble", label: "Wobble Enabled" },
        { key: "step", label: "Wobble Step" },
        { key: "size", label: "Wobble Size" },
        { key: "pass", label: "Passes" },
        { key: "air", label: "Air Assist" },
      ], setting.line_settings)}

      {renderRepeaterCard("Raster Settings", [
        { key: "name", label: "Raster Name" },
        { 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: "Halftone Cell" },
        { key: "halftone_angle", label: "Halftone Angle" },
        { key: "inversion", label: "Invert Colors" },
        { key: "interval", label: "Interval (mm)" },
        { key: "dot", label: "Dot Size" },
        { key: "pass", label: "Passes" },
        { key: "cross", label: "Crosshatch" },
        { key: "air", label: "Air Assist" },
      ], setting.raster_settings)}
    </div>
  );
}

