"use client";

import React, { useState, useRef, ChangeEvent, DragEvent, useEffect } from "react";
import jsPDF from "jspdf";

export default function PrintConverter() {
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [imgElement, setImgElement] = useState<HTMLImageElement | null>(null);

  // Sozlamalar state'lari
  const [presetWidth, setPresetWidth] = useState<number>(1080); // 360, 720, 1080
  const [dpi, setDpi] = useState<number>(300); // 150, 300, 600
  const [bleed, setBleed] = useState<number>(3); // 0mm, 3mm, 5mm

  const fileInputRef = useRef<HTMLInputElement | null>(null);

  // Rasmni yuklash va o'qish funksiyasi
  const handleFileSelect = (file: File) => {
    if (!file.type.startsWith("image/")) {
      alert("Iltimos, faqat rasm faylini kiriting (PNG, JPG, SVG va h.k.)!");
      return;
    }
    setImageFile(file);

    const reader = new FileReader();
    reader.onload = (e) => {
      const result = e.target?.result as string;
      setImagePreview(result);

      const img = new Image();
      img.src = result;
      img.onload = () => {
        setImgElement(img);
      };
    };
    reader.readAsDataURL(file);
  };

 // Ctrl + V (Paste) uchun universal va kuchaytirilgan handler
  useEffect(() => {
    const handlePaste = async (e: ClipboardEvent) => {
      
      const items = e.clipboardData?.items;
      if (items) {
        for (let i = 0; i < items.length; i++) {
          if (items[i].type.startsWith("image/")) {
            const file = items[i].getAsFile();
            if (file) {
              handleFileSelect(file);
              return;
            }
          }
        }
      }

     
      try {
        if (navigator.clipboard && navigator.clipboard.read) {
          const clipboardItems = await navigator.clipboard.read();
          for (const item of clipboardItems) {
            const imageType = item.types.find((type) => type.startsWith("image/"));
            if (imageType) {
              const blob = await item.getType(imageType);
              const file = new File([blob], "pasted-image.png", { type: imageType });
              handleFileSelect(file);
              return;
            }
          }
        }
      } catch (err) {
        console.log("Clipboard API ruxsati berilmadi yoki qo'llab-quvvatlanmaydi:", err);
      }
    };

    window.addEventListener("paste", handlePaste);
    return () => {
      window.removeEventListener("paste", handlePaste);
    };
  }, []);

  const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileSelect(e.target.files[0]);
    }
  };

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  };

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileSelect(e.dataTransfer.files[0]);
    }
  };

  // Canvas yaratish yordamchi funksiyasi
  const createCanvas = (bgColor: string = "transparent") => {
    if (!imgElement) return null;

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    const aspectRatio = imgElement.height / imgElement.width;
    const targetWidth = presetWidth;
    const targetHeight = presetWidth * aspectRatio;

    canvas.width = targetWidth;
    canvas.height = targetHeight;

    if (ctx) {
      if (bgColor !== "transparent") {
        ctx.fillStyle = bgColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      }
      ctx.drawImage(imgElement, 0, 0, targetWidth, targetHeight);
    }

    return canvas;
  };

  // 1. PNG Eksport
  const downloadPNG = () => {
    const canvas = createCanvas("transparent");
    if (!canvas) return;

    const link = document.createElement("a");
    link.download = `PixPrint_${presetWidth}px_${dpi}DPI.png`;
    link.href = canvas.toDataURL("image/png");
    link.click();
  };

  // 2. JPG Eksport
  const downloadJPG = () => {
    const canvas = createCanvas("#FFFFFF");
    if (!canvas) return;

    const link = document.createElement("a");
    link.download = `PixPrint_${presetWidth}px_${dpi}DPI.jpg`;
    link.href = canvas.toDataURL("image/jpeg", 0.95);
    link.click();
  };

  // 3. PDF Eksport — Bleed va DPI bilan
  const downloadPDF = () => {
    if (!imgElement) return;

    const canvas = createCanvas("#FFFFFF");
    if (!canvas) return;

    const imgData = canvas.toDataURL("image/jpeg", 1.0);
    
    const pxToMm = (px: number) => (px / dpi) * 25.4;
    
    let imgWidthMm = pxToMm(canvas.width);
    let imgHeightMm = pxToMm(canvas.height);

    const totalWidthMm = imgWidthMm + bleed * 2;
    const totalHeightMm = imgHeightMm + bleed * 2;

    const pdf = new jsPDF({
      orientation: totalWidthMm > totalHeightMm ? "landscape" : "portrait",
      unit: "mm",
      format: [totalWidthMm, totalHeightMm],
    });

    pdf.addImage(imgData, "JPEG", bleed, bleed, imgWidthMm, imgHeightMm);

    if (bleed > 0) {
      pdf.setDrawColor(200, 0, 0);
      pdf.setLineWidth(0.2);
      
      pdf.line(0, bleed, bleed, bleed);
      pdf.line(bleed, 0, bleed, bleed);
      
      pdf.line(totalWidthMm - bleed, 0, totalWidthMm - bleed, bleed);
      pdf.line(totalWidthMm - bleed, bleed, totalWidthMm, bleed);
    }

    pdf.save(`PixPrint_Print_${presetWidth}px_${dpi}DPI_${bleed}mm.pdf`);
  };

  // 4. SVG Eksport
  const downloadSVG = () => {
    const canvas = createCanvas("transparent");
    if (!canvas) return;

    const imgDataDataUrl = canvas.toDataURL("image/png");
    const svgContent = `
      <svg xmlns="http://www.w3.org/2000/svg" width="${canvas.width}" height="${canvas.height}">
        <image href="${imgDataDataUrl}" width="${canvas.width}" height="${canvas.height}"/>
      </svg>
    `.trim();

    const blob = new Blob([svgContent], { type: "image/svg+xml;charset=utf-8" });
    const link = document.createElement("a");
    link.download = `PixPrint_${presetWidth}px.svg`;
    link.href = URL.createObjectURL(blob);
    link.click();
  };

  return (
    <main className="min-h-screen bg-[#090D16] text-white flex flex-col items-center justify-center p-4 sm:p-8 font-sans">
      {/* Header */}
      <div className="text-center mb-8">
        <span className="bg-blue-950/80 border border-blue-500/30 text-blue-400 text-xs font-semibold px-4 py-1.5 rounded-full tracking-wider uppercase">
          
        </span>
        <h1 className="text-4xl sm:text-5xl font-extrabold tracking-tight mt-4 mb-2">
          Abdumalik | <span className="text-blue-500">PixPrint</span>
        </h1>
        <p className="text-slate-400 text-sm sm:text-base max-w-xl mx-auto">
          Rasmlar va fayllarni bir zumda PDF, PNG, JPG yoki SVG formatga o'tkazing.
        </p>
      </div>

      {/* Main Container */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 w-full max-w-5xl">
        {/* Chap tomon: Rasm yuklash joyi */}
        <div className="lg:col-span-7 bg-[#0F172A]/80 border border-slate-800 rounded-2xl p-6 flex flex-col justify-center items-center relative min-h-[380px]">
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleInputChange}
            accept="image/*"
            className="hidden"
          />

          {!imagePreview ? (
            <div
              onDragOver={handleDragOver}
              onDrop={handleDrop}
              onClick={() => fileInputRef.current?.click()}
              className="w-full h-full border-2 border-dashed border-slate-700 hover:border-blue-500/50 hover:bg-slate-800/30 transition-all rounded-xl p-8 flex flex-col items-center justify-center cursor-pointer text-center group"
            >
              <div className="w-16 h-16 bg-slate-800/80 group-hover:bg-blue-600/20 rounded-full flex items-center justify-center mb-4 transition-all">
                <svg
                  className="w-8 h-8 text-slate-400 group-hover:text-blue-400 transition-all"
                  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>
              </div>
              <h3 className="text-lg font-medium text-slate-200 mb-1">
                Rasm yoki faylni tanlang
              </h3>
              <p className="text-xs text-slate-500 mb-4">
                PNG, JPG, JPEG, SVG (Max 50MB)
              </p>

              <button
                type="button"
                className="bg-slate-900 border border-slate-700 text-slate-300 px-4 py-2 rounded-lg text-xs font-medium hover:bg-slate-800 transition-all"
              >
                 Yoki rasmni nusxalab (Ctrl + V) tashlang
              </button>
            </div>
          ) : (
            <div className="w-full h-full flex flex-col items-center justify-center relative group">
              <img
                src={imagePreview}
                alt="Preview"
                className="max-h-[300px] object-contain rounded-lg border border-slate-800"
              />
              <button
                onClick={() => {
                  setImageFile(null);
                  setImagePreview(null);
                  setImgElement(null);
                }}
                className="mt-4 text-xs text-red-400 hover:text-red-300 bg-red-950/30 border border-red-900/50 px-3 py-1.5 rounded-lg transition-all"
              >
                 Rasmni almashtirish
              </button>
            </div>
          )}

          {/* Bottom indicator */}
          <div className="w-full mt-6 pt-4 border-t border-slate-800/80 flex justify-between items-center text-xs text-slate-500">
            <span>
              Rejim: <strong className="text-emerald-400">Pro License Unlocked</strong>
            </span>
            <span>Formatlar: <strong>PNG / JPG / PDF / SVG</strong></span>
          </div>
        </div>

        {/* O'ng tomon: Matbaa Sozlamalari */}
        <div className="lg:col-span-5 bg-[#0F172A]/80 border border-slate-800 rounded-2xl p-6 flex flex-col justify-between">
          <div>
            <div className="flex items-center gap-2 mb-6">
              <span className="text-blue-500 text-lg"></span>
              <h2 className="text-lg font-bold">Matbaa Sozlamalari</h2>
            </div>

            {/* Kenglik (Preset PX) */}
            <div className="mb-5">
              <label className="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2 block flex items-center gap-1">
                <span className="text-blue-400">⤢</span> KENGLIK (PRESET PX)
              </label>
              <div className="grid grid-cols-3 gap-2">
                {[360, 720, 1080].map((px) => (
                  <button
                    key={px}
                    onClick={() => setPresetWidth(px)}
                    className={`py-2 px-3 rounded-xl text-xs font-semibold transition-all ${
                      presetWidth === px
                        ? "bg-blue-600 text-white shadow-lg shadow-blue-600/30 border border-blue-400"
                        : "bg-slate-900/90 text-slate-400 border border-slate-800 hover:bg-slate-800"
                    }`}
                  >
                    {px}px
                  </button>
                ))}
              </div>
            </div>

            {/* Zichlik Ko'rsatkich (DPI) */}
            <div className="mb-5">
              <label className="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2 block">
                ZICHLIK KO'RSATKICHI (DPI)
              </label>
              <div className="grid grid-cols-3 gap-2">
                {[150, 300, 600].map((val) => (
                  <button
                    key={val}
                    onClick={() => setDpi(val)}
                    className={`py-2 px-3 rounded-xl text-xs font-semibold transition-all ${
                      dpi === val
                        ? "bg-blue-600 text-white shadow-lg shadow-blue-600/30 border border-blue-400"
                        : "bg-slate-900/90 text-slate-400 border border-slate-800 hover:bg-slate-800"
                    }`}
                  >
                    {val} DPI
                  </button>
                ))}
              </div>
            </div>

            {/* Kesim Joyi (Bleed Margin) */}
            <div className="mb-6">
              <label className="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2 block">
                KESIM JOYI (BLEED MARGIN)
              </label>
              <div className="grid grid-cols-3 gap-2">
                {[0, 3, 5].map((mm) => (
                  <button
                    key={mm}
                    onClick={() => setBleed(mm)}
                    className={`py-2 px-3 rounded-xl text-xs font-semibold transition-all ${
                      bleed === mm
                        ? "bg-blue-600 text-white shadow-lg shadow-blue-600/30 border border-blue-400"
                        : "bg-slate-900/90 text-slate-400 border border-slate-800 hover:bg-slate-800"
                    }`}
                  >
                    {mm} mm
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Eksport Tugmalari */}
          <div className="grid grid-cols-2 gap-3 pt-4 border-t border-slate-800">
            <button
              disabled={!imagePreview}
              onClick={downloadPNG}
              className="py-3 px-4 bg-slate-900 hover:bg-slate-800 disabled:opacity-40 disabled:cursor-not-allowed border border-slate-700 text-slate-200 rounded-xl font-medium text-xs flex items-center justify-center gap-2 transition-all"
            >
               PNG
            </button>
            <button
              disabled={!imagePreview}
              onClick={downloadJPG}
              className="py-3 px-4 bg-slate-900 hover:bg-slate-800 disabled:opacity-40 disabled:cursor-not-allowed border border-slate-700 text-slate-200 rounded-xl font-medium text-xs flex items-center justify-center gap-2 transition-all"
            >
               JPG
            </button>
            <button
              disabled={!imagePreview}
              onClick={downloadPDF}
              className="py-3 px-4 bg-slate-900 hover:bg-slate-800 disabled:opacity-40 disabled:cursor-not-allowed border border-slate-700 text-slate-200 rounded-xl font-medium text-xs flex items-center justify-center gap-2 transition-all"
            >
               PDF
            </button>
            <button
              disabled={!imagePreview}
              onClick={downloadSVG}
              className="py-3 px-4 bg-slate-900 hover:bg-slate-800 disabled:opacity-40 disabled:cursor-not-allowed border border-slate-700 text-slate-200 rounded-xl font-medium text-xs flex items-center justify-center gap-2 transition-all"
            >
               SVG
            </button>
          </div>
        </div>
      </div>
    </main>
  );
}