"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { cn } from "@/lib/utils";
import { CanvasTemplate } from "@/lib/canvas-data";
import { CanvasField } from "../CanvasField";
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>
  );
}

const DECISION_OPTIONS = [
  { value: "", label: "EN ATTENTE", color: "bg-gray-100 text-gray-500", border: "border-gray-200" },
  { value: "go", label: "GO", color: "bg-[#22c55e] text-white", border: "border-[#15803d]" },
  { value: "no-go", label: "NO GO", color: "bg-[#ef4444] text-white", border: "border-[#b91c1c]" },
];

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

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

  const currentValue = (getCanvas(canvasId)?.fields[fieldId] as string) || "";
  const currentOption = DECISION_OPTIONS.find((opt) => opt.value === currentValue) || DECISION_OPTIONS[0];

  const handleSelect = useCallback(
    (value: string) => {
      updateCanvasField(canvasId, fieldId, value);
      setOpen(false);
    },
    [canvasId, fieldId, 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="relative w-full h-full">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className={cn(
          "w-full h-full min-h-[40px] flex items-center justify-center text-[12px] font-bold border-2 transition-all hover:opacity-90",
          currentOption.color,
          currentValue === "" ? "border-dashed border-gray-300 hover:border-gray-400" : "border-transparent"
        )}
      >
        {currentOption.label}
        <span className="ml-1 text-[10px] opacity-60">▼</span>
      </button>

      {open && (
        <div className="absolute bottom-full left-0 w-full mb-1 bg-white rounded shadow-xl border border-gray-200 z-50 overflow-hidden">
          {DECISION_OPTIONS.map((option) => (
            <button
              key={option.value || "default"}
              type="button"
              onClick={() => handleSelect(option.value)}
              className={cn(
                "w-full text-left px-3 py-2 text-[11px] font-bold transition-colors hover:brightness-95 flex items-center justify-between",
                option.color,
                option.value === "" && "bg-white text-gray-500 hover:bg-gray-50"
              )}
            >
              {option.label}
              {currentValue === option.value && <span>✓</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

interface ConceptEvaluationCanvasProps {
  canvas: CanvasTemplate;
  teamName?: string;
  className?: string;
}

const criteria = [
  "Désirabilité utilisateur",
  "Preuves du terrain",
  "Complexité opérationnelle",
  "Intérêt du partenaire",
];

const conceptColors = [
  "bg-[#dbeafe]", // blue
  "bg-[#dcfce7]", // green
  "bg-[#fef3c7]", // yellow
  "bg-[#fce7f3]", // pink
];

// Helper to get border classes based on decision
// Helper to get border classes based on decision
const getColumnBorderClass = (decision: string, position: 'header' | 'body' | 'footer') => {
  if (decision === 'go') {
    const base = "border-l-4 border-r-4 border-[#15803d] z-20"; // Green-700, high z-index
    if (position === 'header') return `${base} border-t-4 border-b-2 border-b-[#d1d5dc]`;
    if (position === 'footer') return `${base} border-b-4 border-t-0`;
    return `${base} border-t-0 border-b-2 border-b-[#d1d5dc]`;
  }
  if (decision === 'no-go') {
    const base = "border-l-4 border-r-4 border-[#b91c1c] z-20"; // Red-700, high z-index
    if (position === 'header') return `${base} border-t-4 border-b-2 border-b-[#d1d5dc]`;
    if (position === 'footer') return `${base} border-b-4 border-t-0`;
    return `${base} border-t-0 border-b-2 border-b-[#d1d5dc]`;
  }
  return "border-2 border-[#d1d5dc] z-0";
};

export function ConceptEvaluationCanvas({ canvas, className = "", teamName }: ConceptEvaluationCanvasProps) {
  const { getCanvas } = useCanvasStore();
  const canvasData = getCanvas(canvas.id);

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

  // Get decisions to apply column highlighting
  const getDecision = (letter: string) =>
    (canvasData?.fields[`concept-${letter.toLowerCase()}-decision`] as string) || "";



  return (
    <DesktopOnlyGuard>
      <div className={`bg-white flex flex-col h-full ${className}`}>


        {/* Main Content */}
        <div className="flex-1 px-8 py-4 flex flex-col min-h-0 overflow-hidden">
          {/* Evaluation Table */}
          <div className="flex-1 flex flex-col min-h-0">
            {/* Table Header */}
            {/* Table Header */}
            <div className="grid grid-cols-[200px_1fr_1fr_1fr_1fr] gap-x-2 gap-y-0 shrink-0 mb-0">
              <div className="bg-[#f9fafb] border-2 border-[#d1d5dc] p-2 text-center">
                <span className="text-[11px] font-bold text-[#4a5565] uppercase">Critères d'évaluation</span>
              </div>
              {["A", "B", "C", "D"].map((letter, idx) => {
                const decision = getDecision(letter);
                const borderClass = getColumnBorderClass(decision, 'header');

                return (
                  <div key={letter} className={`${conceptColors[idx]} ${borderClass} p-2 text-center transition-all duration-300 relative z-10 box-border`}>
                    <span className="text-[11px] font-bold text-[#4a5565] uppercase block">Concept {letter}</span>
                    <CanvasField
                      canvasId={canvas.id}
                      field={{
                        id: `concept-${letter.toLowerCase()}-name`,
                        type: "text",
                        label: "",
                        placeholder: "(Nom)",
                      }}
                      hideLabel
                      className="w-full mt-1"
                      inputClassName="bg-white/50 border-b border-[#99a1af] focus:border-black text-center text-[11px] h-auto py-0.5 px-0 font-medium placeholder:font-normal placeholder:text-gray-400"
                    />
                  </div>
                );
              })}
            </div>

            {/* Table Body */}
            <div className="flex-1 flex flex-col gap-0 min-h-0">
              {criteria.map((criterion) => (
                <div key={criterion} className="grid grid-cols-[200px_1fr_1fr_1fr_1fr] gap-x-2 gap-y-0 flex-1 min-h-0">
                  <div className="bg-[#f9fafb] border-2 border-[#d1d5dc] p-2 flex items-center">
                    <span className="text-[10px] text-[#4a5565]">{criterion}</span>
                  </div>
                  {["A", "B", "C", "D"].map((letter) => {
                    const fieldId = `${criterion.toLowerCase().replace(/\s+/g, "-")}-concept-${letter.toLowerCase()}`;
                    const decision = getDecision(letter);
                    const borderClass = getColumnBorderClass(decision, 'body');

                    return (
                      <div
                        key={`${criterion}-${letter}`}
                        className={`group relative ${borderClass} p-2 min-h-0 transition-colors duration-200 box-border`}
                        style={{ backgroundColor: getColor(fieldId) || "white" }}
                      >
                        <CellColorPicker canvasId={canvas.id} fieldId={fieldId} />
                        <CanvasField
                          canvasId={canvas.id}
                          field={{
                            id: fieldId,
                            type: "textarea",
                            label: "",
                            rows: 2,
                          }}
                          hideLabel
                          className="h-full"
                          inputClassName="bg-transparent border-0 !p-0 text-[10px] h-full resize-none !rounded-none"
                        />
                      </div>
                    );
                  })}
                </div>
              ))}

              {/* Decision Row */}
              <div className="grid grid-cols-[200px_1fr_1fr_1fr_1fr] gap-x-2 gap-y-0 shrink-0 mt-0">
                <div className="bg-black border-2 border-black p-2 flex items-center justify-center">
                  <span className="text-[12px] font-bold text-white uppercase tracking-wider">DÉCISION</span>
                </div>
                {["A", "B", "C", "D"].map((letter) => {
                  const decision = getDecision(letter);
                  const borderClass = getColumnBorderClass(decision, 'footer');

                  return (
                    <div key={`decision-${letter}`} className={`h-full ${borderClass} transition-all duration-300 box-border`}>
                      <DecisionSelector
                        canvasId={canvas.id}
                        fieldId={`concept-${letter.toLowerCase()}-decision`}
                      />
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Arguments Section */}
          <div className="border-2 border-black p-4 mt-4 shrink-0">
            <h3 className="text-[14px] font-bold uppercase mb-2 border-b border-black pb-2">
              Arguments Clés pour la Décision
            </h3>
            <CanvasField
              canvasId={canvas.id}
              field={{
                id: "decision-arguments",
                type: "textarea",
                label: "",
                rows: 4,
              }}
              hideLabel
              className=""
              inputClassName="bg-transparent border-0 !p-0 text-[11px] resize-none !rounded-none"
            />
          </div>

          {/* Info Banner */}
          <div className="bg-[#f9fafb] border-2 border-[#d1d5dc] py-2 px-4 text-center shrink-0 mt-4">
            <p className="text-[11px] text-[#6a7282] italic">
              Cette matrice soutient la discussion, elle ne remplace pas le jugement de l'équipe
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="px-8 py-3 border-t-2 border-[#d1d5dc] flex justify-between items-center shrink-0">
          <span className="text-[12px] text-[#6a7282]">Équipe : {teamName || ''}</span>
          <span className="text-[12px] text-[#6a7282]">© Mathieu Aguesse 2026</span>
          <span className="text-[12px] text-[#6a7282]">Date :</span>
        </div>
      </div>
    </DesktopOnlyGuard>
  );
}
