"use client";

import React, { useState, useRef } from "react";
import Image from "next/image";
import { Upload, X, Image as ImageIcon, Link as LinkIcon, Check, RefreshCw } from "lucide-react";

interface PresetOption {
  name: string;
  url: string;
}

interface ImageUploadInputProps {
  label: string;
  value: string;
  onChange: (value: string) => void;
  presets?: PresetOption[];
  aspectRatio?: "square" | "video" | "banner";
  placeholderText?: string;
  helperText?: string;
  className?: string;
}

export function ImageUploadInput({
  label,
  value,
  onChange,
  presets = [],
  aspectRatio = "video",
  placeholderText = "Upload Image File from Device",
  helperText,
  className = ""
}: ImageUploadInputProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [showUrlInput, setShowUrlInput] = useState(false);
  const [urlInputVal, setUrlInputVal] = useState(value);

  const handleFile = (file: File) => {
    if (!file.type.startsWith("image/")) {
      alert("Please upload a valid image file (PNG, JPG, WEBP, SVG).");
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      if (e.target?.result && typeof e.target.result === "string") {
        onChange(e.target.result);
      }
    };
    reader.readAsDataURL(file);
  };

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

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

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

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

  const aspectClasses = {
    square: "h-32 w-32",
    video: "h-36 sm:h-44 w-full sm:w-72",
    banner: "h-24 sm:h-28 w-full sm:w-80",
  }[aspectRatio];

  const hasImage = Boolean(value && value.trim().length > 0);

  return (
    <div className={`space-y-2.5 font-sans ${className}`}>
      <div className="flex items-center justify-between">
        <label className="font-mono text-xs text-muted-foreground block font-medium">
          {label}
        </label>

        <button
          type="button"
          onClick={() => {
            setShowUrlInput(!showUrlInput);
            setUrlInputVal(value);
          }}
          className="font-mono text-[11px] text-[#024d37] hover:underline flex items-center gap-1 cursor-pointer"
        >
          <LinkIcon className="h-3 w-3" />
          <span>{showUrlInput ? "Hide Direct URL" : "Paste URL / Presets"}</span>
        </button>
      </div>

      {/* Hidden File Input */}
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileInputChange}
        accept="image/png, image/jpeg, image/webp, image/svg+xml, image/gif"
        className="hidden"
      />

      {/* Upload Zone & Preview Box */}
      <div className="grid grid-cols-1 sm:grid-cols-12 gap-4 items-start">
        {/* Left: Interactive Preview Thumbnail */}
        <div className="sm:col-span-6 lg:col-span-5">
          {hasImage ? (
            <div className="relative group rounded-2xl border-2 border-[#024d37]/50 bg-muted/80 overflow-hidden p-2 flex items-center justify-center shadow-sm">
              <div className={`relative ${aspectClasses} overflow-hidden rounded-xl flex items-center justify-center bg-card`}>
                <Image
                  src={value}
                  alt="Uploaded Asset Preview"
                  fill
                  className="object-contain p-1"
                />
              </div>

              {/* Action Overlay */}
              <div className="absolute inset-0 bg-black/60 backdrop-blur-xs opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2 p-3">
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="rounded-full bg-white text-black px-3 py-1.5 font-mono text-[11px] font-bold flex items-center gap-1 hover:bg-slate-100 cursor-pointer shadow-md"
                >
                  <RefreshCw className="h-3 w-3" /> Change File
                </button>
                <button
                  type="button"
                  onClick={() => onChange("")}
                  className="rounded-full bg-destructive text-white px-3 py-1.5 font-mono text-[11px] font-bold flex items-center gap-1 hover:bg-destructive/90 cursor-pointer shadow-md"
                >
                  <X className="h-3 w-3" /> Remove
                </button>
              </div>
            </div>
          ) : (
            <div
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onDrop={handleDrop}
              onClick={() => fileInputRef.current?.click()}
              className={`rounded-2xl border-2 border-dashed p-6 text-center transition-all cursor-pointer flex flex-col items-center justify-center space-y-2 ${
                isDragging
                  ? "border-[#024d37] bg-[#024d37]/15 scale-[1.02]"
                  : "border-border hover:border-[#024d37]/60 bg-muted/40 hover:bg-muted/70"
              }`}
            >
              <div className="h-10 w-10 rounded-full bg-muted border border-border flex items-center justify-center text-muted-foreground group-hover:text-foreground">
                <Upload className="h-5 w-5 text-[#024d37]" />
              </div>
              <div>
                <div className="font-sans text-xs font-semibold text-foreground">
                  {placeholderText}
                </div>
                <div className="font-mono text-[10px] text-muted-foreground mt-0.5">
                  Click to browse or Drag & Drop (PNG, JPG, WEBP, SVG)
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Right: Direct File Action Controls & Presets */}
        <div className="sm:col-span-6 lg:col-span-7 space-y-2.5">
          <div className="flex flex-wrap items-center gap-2">
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="rounded-xl border border-[#024d37] bg-[#024d37]/10 px-4 py-2 text-xs font-bold text-[#024d37] hover:bg-[#024d37] hover:text-white transition-all flex items-center gap-1.5 cursor-pointer shadow-xs"
            >
              <Upload className="h-3.5 w-3.5" />
              <span>Upload from Computer</span>
            </button>

            {hasImage && (
              <button
                type="button"
                onClick={() => onChange("")}
                className="rounded-xl border border-border bg-card px-3 py-2 text-xs text-muted-foreground hover:text-destructive hover:border-destructive/40 transition-colors cursor-pointer"
              >
                Clear
              </button>
            )}
          </div>

          {helperText && (
            <p className="text-[11px] text-muted-foreground leading-relaxed font-sans">
              {helperText}
            </p>
          )}

          {/* Optional URL input toggle */}
          {showUrlInput && (
            <div className="space-y-1.5 pt-2 border-t border-border animate-in fade-in duration-100">
              <span className="font-mono text-[10px] text-muted-foreground uppercase block">
                Direct Image Path or Hosted URL:
              </span>
              <div className="flex gap-2">
                <input
                  type="text"
                  placeholder="https://... or /assets/..."
                  value={urlInputVal}
                  onChange={(e) => setUrlInputVal(e.target.value)}
                  className="flex-1 rounded-xl border border-border bg-muted px-3 py-1.5 text-xs text-foreground font-mono focus:border-[#024d37] focus:outline-none"
                />
                <button
                  type="button"
                  onClick={() => onChange(urlInputVal)}
                  className="rounded-xl bg-foreground text-background px-3 py-1.5 text-xs font-mono font-semibold hover:opacity-90 cursor-pointer"
                >
                  Apply
                </button>
              </div>
            </div>
          )}

          {/* Preset Buttons */}
          {presets.length > 0 && (
            <div className="space-y-1 pt-1">
              <span className="font-mono text-[10px] text-muted-foreground block">
                Quick Built-in Presets:
              </span>
              <div className="flex flex-wrap gap-1.5">
                {presets.map((preset) => (
                  <button
                    key={preset.name}
                    type="button"
                    onClick={() => {
                      onChange(preset.url);
                      setUrlInputVal(preset.url);
                    }}
                    className={`rounded-lg border px-2.5 py-1 text-[10px] font-mono transition-colors cursor-pointer ${
                      value === preset.url
                        ? "border-[#024d37] bg-[#024d37] text-white font-bold"
                        : "border-border bg-card text-foreground hover:border-[#024d37]/60"
                    }`}
                  >
                    {preset.name}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
