"use client";

import { useCallback } from "react";
import { cn } from "@/lib/utils";
import { CanvasField } from "../CanvasField";
import type { CanvasTemplate } from "@/lib/types";
import { useCanvasStore } from "@/lib/store";

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

/**
 * Scenario Validation Canvas Template (Template #13)
 * Valider la cohérence, la clarté et l'utilité des scénarios avant sélection et raffinement
 * 
 * Design: 3 validation cards with interactive GO/NO-GO buttons
 * Each card: Number + 3 columns (Résumé, Hypothèses, Retours Facilitateur + buttons)
 * Clicking GO/NO-GO colors the entire scenario row green/red.
 * Bottom: Actions section (black bg)
 * 
 * Supports multi-page: each page uses page-prefixed field IDs.
 */

// Background colors for GO/NO-GO decisions
const DECISION_COLORS: Record<string, string> = {
  go: "#dcfce7",    // stronger green
  nogo: "#fecaca",  // stronger red
};

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

function ValidationRow({ canvasId, scenarioNumber, fieldPrefix }: ValidationRowProps) {
  const { getCanvas, updateCanvasField } = useCanvasStore();
  const decisionFieldId = `${fieldPrefix}validation-${scenarioNumber}-decision`;
  const decision = (getCanvas(canvasId)?.fields[decisionFieldId] as string) ?? "";

  const handleDecision = useCallback(
    (value: "go" | "nogo") => {
      // Toggle: clicking the active button resets to no decision
      updateCanvasField(canvasId, decisionFieldId, decision === value ? "" : value);
    },
    [canvasId, decisionFieldId, decision, updateCanvasField]
  );

  const rowBg = DECISION_COLORS[decision] || "white";

  return (
    <div
      className="border-4 border-black p-3 md:p-4 flex flex-col md:flex-row gap-3 h-full md:min-h-0 overflow-auto transition-colors duration-300"
      style={{ backgroundColor: rowBg }}
    >
      {/* Number Badge */}
      <div className="bg-black w-[40px] h-[40px] shrink-0 flex items-center justify-center self-start">
        <span className="text-[20px] font-bold text-white">{scenarioNumber}</span>
      </div>

      {/* Content Columns */}
      <div className="flex-1 flex flex-col md:flex-row gap-3 min-h-0">
        {/* Résumé du scénario */}
        <div className="flex-1 flex flex-col gap-1 min-h-0">
          <label className="text-[11px] font-bold text-[#0a0a0a] uppercase shrink-0">
            Résumé du scénario
          </label>
          <CanvasField
            canvasId={canvasId}
            field={{
              id: `${fieldPrefix}validation-${scenarioNumber}-summary`,
              type: "textarea",
              label: "",
              placeholder: scenarioNumber === 1
                ? "Ex : En 2028, Anya, nomade digital, ouvre un compte en 90 secondes via reconnaissance faciale + vérification par son réseau social professionnel. Plus de documents papier, la banque valide son identité par croisement de données biométriques et réputation numérique."
                : "",
              rows: 4,
            }}
            hideLabel
            className="flex-1 min-h-[100px] md:min-h-0"
            inputClassName="bg-white/80 border-2 border-[#d1d5dc] !p-2 text-[10px] h-full resize-none !rounded-none"
          />
        </div>

        {/* Hypothèses clés */}
        <div className="flex-1 flex flex-col gap-1 min-h-0">
          <label className="text-[11px] font-bold text-[#0a0a0a] uppercase shrink-0">
            Hypothèses clés
          </label>
          <CanvasField
            canvasId={canvasId}
            field={{
              id: `${fieldPrefix}validation-${scenarioNumber}-hypotheses`,
              type: "textarea",
              label: "",
              placeholder: scenarioNumber === 1
                ? "Ex : La biométrie remplace les justificatifs. La réputation numérique devient un critère KYC. Les régulateurs acceptent la vérification décentralisée. Les clients privilégient vitesse et fluidité sur sécurité perçue."
                : "",
              rows: 4,
            }}
            hideLabel
            className="flex-1 min-h-[100px] md:min-h-0"
            inputClassName="bg-white/80 border-2 border-[#d1d5dc] !p-2 text-[10px] h-full resize-none !rounded-none"
          />
        </div>

        {/* Retours facilitateur + GO/NO-GO */}
        <div className="flex-1 flex flex-col gap-1 min-h-0">
          <label className="text-[11px] font-bold text-[#0a0a0a] uppercase shrink-0">
            Retours facilitateur
          </label>
          <CanvasField
            canvasId={canvasId}
            field={{
              id: `${fieldPrefix}validation-${scenarioNumber}-feedback`,
              type: "textarea",
              label: "",
              rows: 3,
            }}
            hideLabel
            className="flex-1 min-h-[80px] md:min-h-0"
            inputClassName="bg-white/80 border-2 border-[#d1d5dc] !p-2 text-[10px] h-full resize-none !rounded-none"
          />

          {/* GO / NO-GO Buttons — clickable, toggle row color */}
          <div className="flex gap-2 shrink-0 mt-1">
            <button
              type="button"
              onClick={() => handleDecision("go")}
              className={cn(
                "flex-1 border-2 border-black py-2 text-center cursor-pointer transition-all duration-200",
                decision === "go"
                  ? "bg-[#22c55e] text-white ring-2 ring-[#16a34a] ring-offset-1"
                  : "bg-[#f0fdf4] hover:bg-[#dcfce7] text-[#0a0a0a]"
              )}
            >
              <span className="text-[11px] font-bold">✓ GO</span>
            </button>
            <button
              type="button"
              onClick={() => handleDecision("nogo")}
              className={cn(
                "flex-1 border-2 border-black py-2 text-center cursor-pointer transition-all duration-200",
                decision === "nogo"
                  ? "bg-[#ef4444] text-white ring-2 ring-[#dc2626] ring-offset-1"
                  : "bg-[#fef2f2] hover:bg-[#fecaca] text-[#0a0a0a]"
              )}
            >
              <span className="text-[11px] font-bold">✗ NO-GO</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export function ScenarioValidationCanvas({ canvas, className, teamName, pageIndex = 1, isMultiPage = false }: ScenarioValidationCanvasProps) {
  // Use page-indexed field IDs to keep data separate per page
  const fieldPrefix = pageIndex > 1 ? `page${pageIndex}-` : '';

  return (
    <div className={cn("h-full flex flex-col overflow-auto md:overflow-hidden", className)}>
      {/* Page indicator for multi-page */}
      {isMultiPage && (
        <div className="px-3 md:px-6 pb-1 shrink-0">
          <span className="inline-block px-2 py-0.5 bg-gray-100 text-[10px] text-gray-500 font-medium rounded">
            Page {pageIndex}
          </span>
        </div>
      )}

      {/* Subtitle */}
      <div className="px-3 md:px-6 pb-2 shrink-0">
        <p className="text-[12px] md:text-[14px] text-[#364153] leading-[18px] md:leading-[20px]">
          Valider la cohérence, la clarté et l'utilité des scénarios avant sélection et raffinement
        </p>
      </div>

      {/* Main Content - 3 Validation Rows */}
      {/* Scenario numbers continue across pages: page 1 → 1,2,3 / page 2 → 4,5,6 / etc. */}
      <div className="flex-1 flex flex-col gap-3 px-3 md:px-6 pb-2 min-h-0">
        <div className="flex-1 min-h-0">
          <ValidationRow canvasId={canvas.id} scenarioNumber={(pageIndex - 1) * 3 + 1} fieldPrefix={fieldPrefix} />
        </div>
        <div className="flex-1 min-h-0">
          <ValidationRow canvasId={canvas.id} scenarioNumber={(pageIndex - 1) * 3 + 2} fieldPrefix={fieldPrefix} />
        </div>
        <div className="flex-1 min-h-0">
          <ValidationRow canvasId={canvas.id} scenarioNumber={(pageIndex - 1) * 3 + 3} fieldPrefix={fieldPrefix} />
        </div>
      </div>

      {/* Actions Section - Black Background */}
      <div className="bg-black border-4 border-black mx-6 p-4 shrink-0">
        <h3 className="text-[14px] font-bold text-white uppercase mb-2">
          → Actions à prendre avant la sélection finale
        </h3>
        <CanvasField
          canvasId={canvas.id}
          field={{
            id: `${fieldPrefix}pre-selection-actions`,
            type: "textarea",
            label: "",
            rows: 2,
          }}
          hideLabel
          className="h-[55px]"
          inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[11px] h-full resize-none !rounded-none"
        />
      </div>

      {/* Footer */}
      <div className="border-t-2 border-[#d1d5dc] mx-6 pt-2 pb-1 shrink-0 mt-2">
        <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>
  );
}
