"use client";

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

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

/**
 * Persona du Futur Canvas Template (Template #9)
 * Créez un personnage futuriste, vivant et crédible qui incarne les changements à venir
 * 
 * Layout: 3 columns with specific sections
 * - Column 1: Photo/Dessin + Prénom + Identité
 * - Column 2: Personnalité, Journée typique, Éléments Futuristes (BLACK)
 * - Column 3: Activité pro, Valeurs, Peurs, Détail Surprenant (BLACK)
 * - Bottom: Citation signature
 */
export function PersonaCanvas({ canvas, className, teamName, pageIndex = 1, isMultiPage = false }: PersonaCanvasProps & { pageIndex?: number; isMultiPage?: boolean }) {
  // Use page-indexed field IDs to keep data separate per page
  const fieldPrefix = pageIndex > 1 ? `page${pageIndex}-` : '';

  const { getCanvas, updateCanvasField } = useCanvasStore();
  const canvasData = getCanvas(canvas.id);

  // Image upload state
  const photoFieldId = `${fieldPrefix}persona-photo`;
  const savedPhoto = canvasData?.fields[photoFieldId] ?? "";
  const [photoData, setPhotoData] = useState<string>(
    typeof savedPhoto === "string" ? savedPhoto : ""
  );
  const [isDragging, setIsDragging] = useState(false);
  const [photoError, setPhotoError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Sync with store when it changes externally
  useEffect(() => {
    const newValue = typeof savedPhoto === "string" ? savedPhoto : "";
    setPhotoData(newValue);
  }, [savedPhoto]);

  const handleFile = useCallback((file: File) => {
    setPhotoError(null);
    if (!file.type.startsWith("image/")) {
      setPhotoError("Veuillez sélectionner un fichier image (PNG, JPEG, etc.)");
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      setPhotoError("L'image est trop volumineuse (max 5 Mo)");
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      const result = e.target?.result as string;
      setPhotoData(result);
      updateCanvasField(canvas.id, photoFieldId, result);
    };
    reader.onerror = () => {
      setPhotoError("Erreur lors de la lecture du fichier");
    };
    reader.readAsDataURL(file);
  }, [canvas.id, photoFieldId, updateCanvasField]);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const files = e.dataTransfer.files;
    if (files.length > 0) handleFile(files[0]);
  }, [handleFile]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) handleFile(files[0]);
  }, [handleFile]);

  const handleRemovePhoto = useCallback(() => {
    setPhotoData("");
    updateCanvasField(canvas.id, photoFieldId, "");
    if (fileInputRef.current) fileInputRef.current.value = "";
  }, [canvas.id, photoFieldId, updateCanvasField]);

  const handleBrowseClick = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  return (
    <div className={cn("h-full flex flex-col overflow-auto md:overflow-hidden", className)}>
      {/* Subtitle */}
      <div className="px-3 md:px-6 pb-1 shrink-0">
        <p className="text-[13px] text-[#364153] leading-[18px]">
          Créez un personnage futuriste, vivant et crédible qui incarne les changements à venir
        </p>
      </div>

      {/* Info Banner - Blue/Purple */}
      <div className="bg-[#e0e7ff] border-2 border-[#4f39f6] mx-3 md:mx-6 mb-2 py-2 px-3 shrink-0 flex justify-between items-center">
        <p className="text-[10px] md:text-[12px] text-[#312c85] font-bold uppercase tracking-wide">
          📋 3 PERSONAS NÉCESSAIRES — Créez 3 versions de ce canevas (3 personas différents)
        </p>
        {isMultiPage && pageIndex > 1 && (
          <span className="text-[12px] font-bold text-[#312c85] uppercase">Page {pageIndex}</span>
        )}
      </div>

      {/* Hidden file input */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        className="hidden"
      />

      {/* Main Content - 3 Columns on desktop, stacked on mobile */}
      <div className="flex-1 flex flex-col md:grid md:grid-cols-[1fr_1.7fr_1.35fr] gap-3 px-3 md:px-6 pb-2 md:min-h-0">

        {/* Column 1: Photo + Identity */}
        <div className="flex flex-col gap-3 min-h-0">
          {/* Photo/Dessin + Prénom */}
          <div className="bg-[#f9fafb] border-2 md:border-[3px] border-black md:flex-[1.8] min-h-[200px] md:min-h-0 flex flex-col">
            <div className="flex flex-col gap-1 p-3 flex-1">
              <label className="text-[10px] font-bold text-[#0a0a0a] uppercase">
                Photo / Dessin
              </label>
              {photoData ? (
                /* Image Preview */
                <div className="flex-1 relative border-2 border-[#99a1af] min-h-[120px] overflow-hidden">
                  <img
                    src={photoData}
                    alt="Photo / Dessin du persona"
                    className="w-full h-full object-contain bg-white"
                  />
                  <button
                    onClick={handleRemovePhoto}
                    className="absolute top-1 right-1 bg-red-500 hover:bg-red-600 text-white px-2 py-1 rounded text-[9px] font-medium transition-colors shadow-md"
                  >
                    ✕
                  </button>
                </div>
              ) : (
                /* Drop Zone */
                <div
                  onDrop={handleDrop}
                  onDragOver={handleDragOver}
                  onDragLeave={handleDragLeave}
                  onClick={handleBrowseClick}
                  className={`flex-1 border-2 border-dashed min-h-[120px] flex flex-col items-center justify-center cursor-pointer transition-all duration-200 ${isDragging
                      ? "border-[#4f39f6] bg-indigo-50"
                      : "border-[#99a1af] hover:border-[#4f39f6] hover:bg-indigo-50/30"
                    }`}
                >
                  <svg
                    className={`w-6 h-6 mb-1 ${isDragging ? "text-[#4f39f6]" : "text-gray-400"}`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                    />
                  </svg>
                  <p className={`text-[9px] font-medium ${isDragging ? "text-[#4f39f6]" : "text-gray-500"}`}>
                    {isDragging ? "Déposez ici" : "Glissez ou cliquez"}
                  </p>
                  <p className="text-[8px] text-gray-400 mt-0.5">PNG, JPEG • Max 5 Mo</p>
                </div>
              )}
              {photoError && (
                <p className="text-[9px] text-red-500 mt-1">⚠️ {photoError}</p>
              )}
              <div className="border-t-2 border-black pt-2 mt-2">
                <label className="text-[10px] font-bold text-[#0a0a0a] uppercase mb-1 block">
                  Prénom
                </label>
                <CanvasField
                  canvasId={canvas.id}
                  field={{
                    id: `${fieldPrefix}first-name`,
                    type: "text",
                    label: "",
                    placeholder: "",
                  }}
                  hideLabel
                  inputClassName="bg-white border border-[#d1d5dc] !p-1 text-[10px] !h-[20px] !rounded-none"
                />
              </div>
            </div>
          </div>

          {/* Identity */}
          <div className="border-[3px] border-black flex-1 min-h-0">
            <div className="flex flex-col gap-2 p-3 h-full">
              <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
                Identité
              </h3>
              <div className="flex flex-col gap-2 flex-1">
                <div>
                  <label className="text-[10px] font-bold text-[#0a0a0a] block mb-[2px]">
                    Âge
                  </label>
                  <CanvasField
                    canvasId={canvas.id}
                    field={{ id: `${fieldPrefix}age`, type: "text", label: "", placeholder: "" }}
                    hideLabel
                    inputClassName="bg-white border border-[#d1d5dc] !p-1 text-[10px] !h-[18px] !rounded-none"
                  />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-[#0a0a0a] block mb-[2px]">
                    Lieu de vie
                  </label>
                  <CanvasField
                    canvasId={canvas.id}
                    field={{ id: `${fieldPrefix}location`, type: "text", label: "", placeholder: "" }}
                    hideLabel
                    inputClassName="bg-white border border-[#d1d5dc] !p-1 text-[10px] !h-[18px] !rounded-none"
                  />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-[#0a0a0a] block mb-[2px]">
                    Situation familiale
                  </label>
                  <CanvasField
                    canvasId={canvas.id}
                    field={{ id: `${fieldPrefix}family-situation`, type: "text", label: "", placeholder: "" }}
                    hideLabel
                    inputClassName="bg-white border border-[#d1d5dc] !p-1 text-[10px] !h-[18px] !rounded-none"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Column 2: Personality, Daily Life, Futuristic */}
        <div className="flex flex-col gap-3 min-h-0">
          {/* Personnalité */}
          <div className="bg-[#f9fafb] border-[3px] border-black flex-[0.8]">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
                🎭 Personnalité
              </h3>
              <p className="text-[10px] text-[#4a5565]">
                3-4 traits de caractère marquants. Donnez-lui du relief !
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}personality`, type: "textarea", label: "", placeholder: "", rows: 2 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>

          {/* Journée typique */}
          <div className="border-[3px] border-black flex-1">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
                📅 Une journée typique en 2035
              </h3>
              <p className="text-[10px] text-[#4a5565]">
                Comment se déroule sa journée ? Quelles routines ?
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}typical-day`, type: "textarea", label: "", placeholder: "", rows: 3 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>

          {/* Éléments Futuristes - BLACK */}
          <div className="bg-black border-[3px] border-black flex-[1.2]">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-white uppercase">
                ⚡ Éléments Futuristes
              </h3>
              <p className="text-[10px] text-[#d1d5dc]">
                Technologies, pratiques ou comportements nouveaux qu'elle utilise
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}futuristic-elements`, type: "textarea", label: "", placeholder: "", rows: 3 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#6a7282] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>
        </div>

        {/* Column 3: Professional, Values, Fears, Surprising */}
        <div className="flex flex-col gap-3 min-h-0">
          {/* Activité professionnelle */}
          <div className="border-[3px] border-black flex-[0.8]">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
                💼 Activité professionnelle
              </h3>
              <p className="text-[10px] text-[#4a5565]">
                Que fait-elle comme travail ou occupation ?
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}professional-activity`, type: "textarea", label: "", placeholder: "", rows: 2 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>

          {/* Valeurs & Motivations */}
          <div className="bg-[#f9fafb] border-[3px] border-black flex-[0.9]">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
                💡 Valeurs & Motivations
              </h3>
              <p className="text-[10px] text-[#4a5565]">
                Qu'est-ce qui la fait avancer ? Qu'est-ce qui compte pour elle ?
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}values-motivations`, type: "textarea", label: "", placeholder: "", rows: 2 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>

          {/* Peurs & Frustrations */}
          <div className="border-[3px] border-black flex-[0.9]">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
                ⚠️ Peurs & Frustrations
              </h3>
              <p className="text-[10px] text-[#4a5565]">
                Qu'est-ce qui l'inquiète ou l'agace dans son quotidien ?
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}fears-frustrations`, type: "textarea", label: "", placeholder: "", rows: 2 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>

          {/* Détail Surprenant - BLACK */}
          <div className="bg-black border-[3px] border-black flex-1">
            <div className="flex flex-col gap-1 p-3 h-full">
              <h3 className="text-[12px] font-bold text-white uppercase">
                ✨ Détail Surprenant
              </h3>
              <p className="text-[10px] text-[#d1d5dc]">
                Un fait inattendu, une habitude bizarre, quelque chose qui la rend unique
              </p>
              <CanvasField
                canvasId={canvas.id}
                field={{ id: `${fieldPrefix}surprising-detail`, type: "textarea", label: "", placeholder: "", rows: 2 }}
                hideLabel
                className="flex-1"
                inputClassName="bg-white border-2 border-[#6a7282] !p-2 text-[10px] h-full !rounded-none resize-none"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Bottom: Signature Quote */}
      <div className="bg-[#f3f4f6] border-[3px] border-black mx-6 mb-2 shrink-0">
        <div className="flex flex-col gap-1 p-3">
          <h3 className="text-[12px] font-bold text-[#0a0a0a] uppercase">
            💬 Une phrase qu'elle dit souvent
          </h3>
          <p className="text-[10px] text-[#4a5565]">
            Sa citation signature — quelque chose qui reflète son état d'esprit
          </p>
          <CanvasField
            canvasId={canvas.id}
            field={{ id: `${fieldPrefix}signature-quote`, type: "textarea", label: "", placeholder: "", rows: 1 }}
            hideLabel
            inputClassName="bg-white border-2 border-[#d1d5dc] !p-2 text-[10px] !h-[28px] !rounded-none resize-none"
          />
        </div>
      </div>

      {/* Footer */}
      <div className="border-t-2 border-[#d1d5dc] mx-6 pt-2 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>Date :</span>
        </div>
      </div>
    </div>
  );
}
