"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { cn } from "@/lib/utils";
import { CanvasField } from "../CanvasField";
import type { CanvasTemplate } from "@/lib/types";
import { DesktopOnlyGuard } from "@/components/ui";
import { useCanvasStore } from "@/lib/store";

// ─── Color Picker ────────────────────────────────────────────────────────────

const PRESET_COLORS = [
  { value: "", label: "Aucune", swatch: "#ffffff", border: true },
  { value: "#dcfce7", label: "Vert", swatch: "#22c55e", border: false },
  { value: "#fed7aa", label: "Orange", swatch: "#f97316", border: false },
  { value: "#fecaca", label: "Rouge", swatch: "#ef4444", border: false },
];

interface CellColorPickerProps {
  canvasId: string;
  fieldId: string;
}

function CellColorPicker({ canvasId, fieldId }: CellColorPickerProps) {
  const [open, setOpen] = useState(false);
  const popoverRef = useRef<HTMLDivElement>(null);
  const { getCanvas, updateCanvasField } = useCanvasStore();

  const colorFieldId = `${fieldId}-color`;
  const currentColor = (getCanvas(canvasId)?.fields[colorFieldId] as string) ?? "";

  const handleSelect = useCallback(
    (color: string) => {
      updateCanvasField(canvasId, colorFieldId, color || "");
      setOpen(false);
    },
    [canvasId, colorFieldId, updateCanvasField]
  );

  // Close on outside click
  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div ref={popoverRef} className="absolute top-1 right-1 z-10 print:hidden">
      {/* Paint icon button — visible on cell hover */}
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className={cn(
          "w-5 h-5 rounded flex items-center justify-center",
          "text-gray-400 hover:text-gray-700 hover:bg-gray-100",
          "opacity-0 group-hover:opacity-100 transition-opacity duration-150",
          open && "!opacity-100 bg-gray-100 text-gray-700"
        )}
        title="Changer la couleur"
      >
        <svg width="12" height="12" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
          <circle cx="8" cy="8" r="6" fill={currentColor || "none"} stroke="currentColor" strokeWidth="1.5" />
        </svg>
      </button>

      {/* Color palette popover */}
      {open && (
        <div className="absolute top-6 right-0 bg-white rounded-lg shadow-lg border border-gray-200 p-1.5 flex gap-1.5">
          {PRESET_COLORS.map((c) => (
            <button
              key={c.value || "none"}
              type="button"
              onClick={() => handleSelect(c.value)}
              title={c.label}
              className={cn(
                "w-5 h-5 rounded-full transition-transform hover:scale-125 focus:outline-none",
                currentColor === c.value && "ring-2 ring-offset-1 ring-gray-500"
              )}
              style={{
                backgroundColor: c.swatch,
                border: c.border ? "1.5px solid #d1d5db" : "none",
              }}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Scenario Row ────────────────────────────────────────────────────────────

interface ScenarioRowProps {
  canvasId: string;
  scenarioNumber: number;
  fieldPrefix: string;
}

function ScenarioRow({ canvasId, scenarioNumber, fieldPrefix }: ScenarioRowProps) {
  const { getCanvas } = useCanvasStore();
  const canvasData = getCanvas(canvasId);

  const getColor = (fieldId: string) =>
    (canvasData?.fields[`${fieldId}-color`] as string) || "";

  // Apply fieldPrefix to all base IDs
  const nameFieldId = `${fieldPrefix}scenario-${scenarioNumber}-name`;
  const plausFieldId = `${fieldPrefix}scenario-${scenarioNumber}-plausibility`;
  const impactFieldId = `${fieldPrefix}scenario-${scenarioNumber}-impact`;
  const origFieldId = `${fieldPrefix}scenario-${scenarioNumber}-originality`;

  return (
    <div className="flex border-b-2 border-l-4 border-r-4 border-black h-full min-h-0">
      {/* Scénario Column - Gray Background */}
      <div className="bg-[#f9fafb] border-r-2 border-black flex flex-col justify-center px-3 w-[25%] shrink-0 py-2">
        <label className="text-[13px] font-bold text-[#0a0a0a] block mb-1">
          Scénario {scenarioNumber} :
        </label>
        <CanvasField
          canvasId={canvasId}
          field={{
            id: nameFieldId,
            type: "text",
            label: "",
            placeholder: "Nom du scénario...",
          }}
          hideLabel
          className="w-full"
          inputClassName="bg-transparent border-b border-gray-300 focus:border-black rounded-none px-0 py-1 text-[13px] font-medium placeholder:font-normal placeholder:text-gray-400 h-auto"
        />
      </div>

      {/* Plausibilité Column */}
      <div
        className="group relative border-r-2 border-black flex-1 p-2 transition-colors duration-200"
        style={{ backgroundColor: getColor(plausFieldId) || "white" }}
      >
        <CellColorPicker canvasId={canvasId} fieldId={plausFieldId} />
        <CanvasField
          canvasId={canvasId}
          field={{
            id: plausFieldId,
            type: "textarea",
            label: "",
            rows: 2,
          }}
          hideLabel
          className="h-full"
          inputClassName="bg-transparent border-0 !p-1 text-[11px] h-full resize-none !rounded-none"
        />
      </div>

      {/* Impact Column */}
      <div
        className="group relative border-r-2 border-black flex-1 p-2 transition-colors duration-200"
        style={{ backgroundColor: getColor(impactFieldId) || "white" }}
      >
        <CellColorPicker canvasId={canvasId} fieldId={impactFieldId} />
        <CanvasField
          canvasId={canvasId}
          field={{
            id: impactFieldId,
            type: "textarea",
            label: "",
            rows: 2,
          }}
          hideLabel
          className="h-full"
          inputClassName="bg-transparent border-0 !p-1 text-[11px] h-full resize-none !rounded-none"
        />
      </div>

      {/* Originalité Column */}
      <div
        className="group relative flex-1 p-2 transition-colors duration-200"
        style={{ backgroundColor: getColor(origFieldId) || "white" }}
      >
        <CellColorPicker canvasId={canvasId} fieldId={origFieldId} />
        <CanvasField
          canvasId={canvasId}
          field={{
            id: origFieldId,
            type: "textarea",
            label: "",
            rows: 2,
          }}
          hideLabel
          className="h-full"
          inputClassName="bg-transparent border-0 !p-1 text-[11px] h-full resize-none !rounded-none"
        />
      </div>
    </div>
  );
}

// ─── Main Canvas ─────────────────────────────────────────────────────────────

interface ScenarioSelectionCanvasProps {
  canvas: CanvasTemplate;
  teamName?: string;
  className?: string;
  pageIndex?: number;
  isMultiPage?: boolean;
}

export function ScenarioSelectionCanvas({
  canvas,
  className,
  teamName,
  pageIndex = 1,
  isMultiPage = false
}: ScenarioSelectionCanvasProps) {
  // Use page-indexed field ids
  const fieldPrefix = pageIndex > 1 ? `page${pageIndex}-` : '';

  return (
    <DesktopOnlyGuard>
      <div className={cn("h-full flex flex-col overflow-hidden", className)}>
        {/* Subtitle */}
        <div className="px-6 pb-3 shrink-0">
          <p className="text-[14px] text-[#364153] leading-[20px]">
            Comparez et sélectionnez les scénarios les plus pertinents à approfondir
          </p>
        </div>

        {/* Main Content */}
        <div className="flex-1 flex flex-col px-6 pb-2 min-h-0">
          {/* Table Header - Black Background */}
          <div className="bg-black border-4 border-black flex shrink-0">
            {/* Scénarios Header */}
            <div className="border-r-2 border-white px-3 py-3 w-[25%] shrink-0">
              <p className="text-[11px] font-bold text-white uppercase">Scénarios</p>
            </div>

            {/* Plausibilité Header */}
            <div className="border-r-2 border-white px-3 py-3 flex-1">
              <p className="text-[11px] font-bold text-white uppercase">Plausibilité</p>
              <p className="text-[11px] text-white/80">Crédibilité ?</p>
            </div>

            {/* Impact Header */}
            <div className="border-r-2 border-white px-3 py-3 flex-1">
              <p className="text-[11px] font-bold text-white uppercase">Impact</p>
              <p className="text-[11px] text-white/80">Ampleur ?</p>
            </div>

            {/* Originalité Header */}
            <div className="px-3 py-3 flex-1">
              <p className="text-[11px] font-bold text-white uppercase">Originalité</p>
              <p className="text-[11px] text-white/80">À quel point c'est surprenant ?</p>
            </div>
          </div>

          {/* Scenario Rows */}
          <div className="flex-1 flex flex-col min-h-0">
            <div className="flex-1 min-h-0">
              <ScenarioRow canvasId={canvas.id} scenarioNumber={1} fieldPrefix={fieldPrefix} />
            </div>
            <div className="flex-1 min-h-0">
              <ScenarioRow canvasId={canvas.id} scenarioNumber={2} fieldPrefix={fieldPrefix} />
            </div>
            <div className="flex-1 min-h-0">
              <ScenarioRow canvasId={canvas.id} scenarioNumber={3} fieldPrefix={fieldPrefix} />
            </div>
            <div className="flex-1 min-h-0">
              <ScenarioRow canvasId={canvas.id} scenarioNumber={4} fieldPrefix={fieldPrefix} />
            </div>
            <div className="flex-1 min-h-0">
              <ScenarioRow canvasId={canvas.id} scenarioNumber={5} fieldPrefix={fieldPrefix} />
            </div>
          </div>

          {/* Synthesis Section */}
          <div className="bg-[#f3f4f6] border-4 border-black p-4 shrink-0">
            <h3 className="text-[14px] font-bold text-[#0a0a0a] uppercase mb-3">
              → Scénarios retenus pour approfondissement :
            </h3>
            <CanvasField
              canvasId={canvas.id}
              field={{
                id: `${fieldPrefix}selected-scenarios`,
                type: "textarea",
                label: "",
                rows: 2,
              }}
              hideLabel
              className="h-[70px]"
              inputClassName="bg-white border-2 border-[#99a1af] !p-2 text-[12px] h-full resize-none !rounded-none"
            />
          </div>
        </div>

        {/* Footer */}
        <div className="border-t-2 border-[#d1d5dc] mx-6 pt-3 pb-1 shrink-0">
          <div className="flex items-center justify-between text-[12px] text-[#6a7282]">
            <span>Équipe : {teamName || ''}</span>
            <span>© Mathieu Aguesse 2026</span>
            <span>
              {isMultiPage && pageIndex > 1 ? `Page ${pageIndex}` : "Date :"}
            </span>
          </div>
        </div>
      </div>
    </DesktopOnlyGuard>
  );
}
