"use client";

import React, { useEffect, useRef, useState } from 'react';
import { RefreshCcw, AlertTriangle, CheckCircle } from 'lucide-react';
import { fabric } from 'fabric';

interface DesignCanvasProps {
  selectedProduct: any;
  productColor: any; // We now receive the full object with the hex code
  uploadedImage: string | null;
  setUploadedImage: (img: string | null) => void;
  customText: string;
  textColor: string;
  fontFamily: string;
  isBold: boolean;
  isItalic: boolean;
}

const colorMap: Record<string, string> = {
  'text-white': '#ffffff',
  'text-neutral-900': '#171717',
  'text-red-500': '#ef4444',
  'text-yellow-500': '#eab308'
};

export default function DesignCanvas({
  selectedProduct, productColor, uploadedImage, setUploadedImage,
  customText, textColor, fontFamily, isBold, isItalic
}: DesignCanvasProps) {
  
  const canvasContainerRef = useRef<HTMLDivElement>(null);
  const fabricCanvasRef = useRef<fabric.Canvas | null>(null);
  const textObjRef = useRef<fabric.IText | null>(null);
  const imgObjRef = useRef<fabric.Image | null>(null);
  const [dpiWarning, setDpiWarning] = useState<boolean>(false);

  useEffect(() => {
    if (!fabricCanvasRef.current) {
      fabricCanvasRef.current = new fabric.Canvas('fabric-canvas', {
        width: 320,
        height: 480,
        preserveObjectStacking: true, 
      });
    }

    return () => {
      if (fabricCanvasRef.current) {
        fabricCanvasRef.current.dispose();
        fabricCanvasRef.current = null;
      }
    };
  }, []);

  useEffect(() => {
    if (!fabricCanvasRef.current) return;

    if (customText) {
      if (!textObjRef.current) {
        textObjRef.current = new fabric.IText(customText, {
          left: 160, top: 350, originX: 'center', originY: 'center',
          fill: colorMap[textColor] || '#ffffff', fontFamily: fontFamily,
          fontWeight: isBold ? 'bold' : 'normal', fontStyle: isItalic ? 'italic' : 'normal',
          fontSize: 32, cornerColor: '#eab308', cornerStyle: 'circle',
          transparentCorners: false, borderColor: '#eab308',
        });
        fabricCanvasRef.current.add(textObjRef.current);
        fabricCanvasRef.current.setActiveObject(textObjRef.current);
      } else {
        textObjRef.current.set({
          text: customText, fill: colorMap[textColor] || '#ffffff',
          fontFamily: fontFamily, fontWeight: isBold ? 'bold' : 'normal',
          fontStyle: isItalic ? 'italic' : 'normal',
        });
        fabricCanvasRef.current.renderAll();
      }
    } else if (textObjRef.current) {
      fabricCanvasRef.current.remove(textObjRef.current);
      textObjRef.current = null;
    }
  }, [customText, textColor, fontFamily, isBold, isItalic]);

  useEffect(() => {
    if (!fabricCanvasRef.current) return;

    if (uploadedImage) {
      const img = new window.Image();
      img.src = uploadedImage;
      img.onload = () => {
        setDpiWarning(img.width < 1500);

        fabric.Image.fromURL(uploadedImage, (fabImg) => {
          fabImg.scaleToWidth(200);
          fabImg.set({
            left: 160, top: 180, originX: 'center', originY: 'center',
            cornerColor: '#eab308', cornerStyle: 'circle',
            transparentCorners: false, borderColor: '#eab308',
          });
          
          if (imgObjRef.current) fabricCanvasRef.current?.remove(imgObjRef.current);
          
          fabricCanvasRef.current?.add(fabImg);
          fabricCanvasRef.current?.sendToBack(fabImg); 
          fabricCanvasRef.current?.setActiveObject(fabImg);
          imgObjRef.current = fabImg;
        });
      };
    } else if (imgObjRef.current) {
      fabricCanvasRef.current.remove(imgObjRef.current);
      imgObjRef.current = null;
      setDpiWarning(false);
    }
  }, [uploadedImage]);

  const handleClearSelection = () => {
    fabricCanvasRef.current?.discardActiveObject();
    fabricCanvasRef.current?.renderAll();
  };

  // Upgraded structural UI representations of the products
  const renderProductShape = () => {
    const isDark = productColor.hex === '#171717' || productColor.hex === '#1e3a8a';
    const shadowClass = isDark ? 'shadow-black/50' : 'shadow-black/10';

    switch (selectedProduct.shape) {
      case 'mug':
        return (
          <div className="absolute inset-0 mx-auto w-[240px] h-[300px] top-1/2 -translate-y-1/2 flex items-center justify-center">
            <div className={`absolute -right-[60px] w-24 h-48 border-[16px] rounded-r-[50px] transition-colors duration-300 z-0 ${shadowClass}`} style={{ borderColor: productColor.hex }}></div>
            <div className={`relative w-full h-full rounded-[40px] rounded-t-[10px] rounded-b-[10px] shadow-2xl transition-colors duration-300 z-10 overflow-hidden border-2 border-black/5`} style={{ backgroundColor: productColor.hex }}>
              <div className="absolute left-0 top-0 w-8 h-full bg-white/20 blur-xl"></div>
              <div className="absolute right-0 top-0 w-12 h-full bg-black/20 blur-xl"></div>
            </div>
          </div>
        );
      case 'cap':
        return (
          <div className="absolute inset-0 mx-auto w-[300px] h-[200px] top-[140px] relative">
            <div className={`absolute top-0 w-full h-[160px] rounded-t-[140px] shadow-2xl transition-colors duration-300 z-10 overflow-hidden border border-black/10`} style={{ backgroundColor: productColor.hex }}>
               {/* 6-panel hat stitching simulation */}
               <div className="absolute top-0 left-1/2 -translate-x-1/2 w-0.5 h-full bg-black/10"></div>
               <div className="absolute top-0 left-1/2 -translate-x-1/2 w-0.5 h-full bg-black/10 rotate-45 transform origin-top"></div>
               <div className="absolute top-0 left-1/2 -translate-x-1/2 w-0.5 h-full bg-black/10 -rotate-45 transform origin-top"></div>
               <div className="absolute top-2 left-1/2 -translate-x-1/2 w-4 h-4 bg-black/20 rounded-full"></div>
            </div>
            <div className="absolute bottom-0 left-[-20px] right-[-20px] h-[60px] rounded-b-[100%] shadow-xl z-20 border-t border-black/10 flex items-end justify-center pb-2" style={{ backgroundColor: productColor.hex, filter: 'brightness(0.9)' }}>
               <div className="w-[80%] h-1 bg-black/10 rounded-full blur-sm"></div>
            </div>
          </div>
        );
      case 'hoodie':
        return (
          <div className={`absolute inset-0 mx-auto w-full max-w-[360px] h-[500px] rounded-[50px] rounded-t-[80px] shadow-2xl transition-colors duration-300 z-10 overflow-hidden border border-black/5`} style={{ backgroundColor: productColor.hex }}>
            {/* Hood depth & Drawstrings */}
            <div className="absolute top-0 left-1/2 -translate-x-1/2 w-48 h-24 bg-black/10 rounded-b-[100px] shadow-inner"></div>
            <div className="absolute top-20 left-[35%] w-1.5 h-24 bg-neutral-200 rounded-full shadow-sm drop-shadow-md rotate-3"></div>
            <div className="absolute top-20 right-[35%] w-1.5 h-20 bg-neutral-200 rounded-full shadow-sm drop-shadow-md -rotate-3"></div>
            {/* Kangaroo Pocket */}
            <div className="absolute bottom-8 left-1/2 -translate-x-1/2 w-[220px] h-[120px] rounded-t-[40px] rounded-b-[20px] border-t-2 border-white/10 z-0 flex" style={{ backgroundColor: productColor.hex, filter: 'brightness(0.95)' }}>
               <div className="w-16 h-full bg-black/5 rounded-tl-[40px] border-r border-black/5"></div>
               <div className="flex-1"></div>
               <div className="w-16 h-full bg-black/5 rounded-tr-[40px] border-l border-black/5"></div>
            </div>
            {/* Fabric rendering overlays */}
            <div className="absolute left-0 top-0 w-12 h-full bg-white/10 blur-xl"></div>
            <div className="absolute right-0 top-0 w-16 h-full bg-black/20 blur-xl"></div>
          </div>
        );
      case 'tshirt':
      default:
        return (
          <div className={`absolute inset-0 mx-auto w-full max-w-[340px] h-[480px] rounded-[40px] shadow-2xl transition-colors duration-300 z-10 overflow-hidden border border-black/5`} style={{ backgroundColor: productColor.hex }}>
            {/* Collar */}
            <div className="absolute -top-4 left-1/2 -translate-x-1/2 w-[140px] h-[40px] bg-white rounded-b-[100px] shadow-inner border-b-4 border-black/10"></div>
            {/* Fabric rendering overlays */}
            <div className="absolute left-0 top-0 w-10 h-full bg-white/10 blur-xl"></div>
            <div className="absolute right-0 top-0 w-12 h-full bg-black/20 blur-xl"></div>
          </div>
        );
    }
  };

  return (
    <div className="flex-1 bg-white rounded-3xl border border-neutral-200 shadow-sm overflow-hidden flex flex-col items-center justify-center p-4 sm:p-8 relative min-h-[600px] bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] [background-size:16px_16px]">
      
      {uploadedImage && (
        <div className="absolute top-6 left-6 z-30">
          {dpiWarning ? (
            <div className="flex items-center gap-2 bg-red-50 text-red-700 px-4 py-2 rounded-full font-bold text-xs border border-red-200 shadow-sm animate-in fade-in">
              <AlertTriangle className="w-4 h-4" /> Low Resolution Warning
            </div>
          ) : (
            <div className="flex items-center gap-2 bg-green-50 text-green-700 px-4 py-2 rounded-full font-bold text-xs border border-green-200 shadow-sm animate-in fade-in">
              <CheckCircle className="w-4 h-4" /> Print Quality: Excellent
            </div>
          )}
        </div>
      )}

      <div className="relative flex justify-center items-center w-full max-w-[360px] h-[500px]" onClick={handleClearSelection}>
        
        {renderProductShape()}

        <div className="absolute inset-0 z-20 flex items-center justify-center pointer-events-auto" ref={canvasContainerRef}>
          <div className="relative w-[320px] h-[480px]">
            <canvas id="fabric-canvas" width={320} height={480} className="absolute inset-0" />
            
            {!uploadedImage && !customText && (
              <div className="absolute inset-0 flex flex-col items-center justify-center text-black/30 font-bold text-lg pointer-events-none mix-blend-difference">
                Select tools on the right to begin
              </div>
            )}
          </div>
        </div>
      </div>

      {uploadedImage && (
        <button 
          onClick={() => setUploadedImage(null)}
          className="absolute top-6 right-6 z-30 bg-white border border-neutral-200 text-neutral-600 hover:text-red-500 rounded-full p-2.5 transition-colors shadow-sm font-bold flex items-center gap-2 text-xs"
        >
          <RefreshCcw className="w-3.5 h-3.5" /> Remove Image
        </button>
      )}
    </div>
  );
}