'use client';

import { useRef, useState } from 'react';
import { Upload, X, Link as LinkIcon, Image as ImageIcon, ChevronDown, ChevronUp } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';

const API_BASE = (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api').replace('/api', '');

function resolveUrl(url: string): string {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) return url;
  return `${API_BASE}${url}`;
}

const STOCK_IMAGES: { category: string; images: { url: string; label: string }[] }[] = [
  {
    category: 'Golf Courses',
    images: [
      { url: 'https://images.unsplash.com/photo-1538648759472-7251f7cb2c2f?w=1200&q=80', label: 'Golf field under blue sky' },
      { url: 'https://images.unsplash.com/photo-1592937238247-cd0090e02f65?w=1200&q=80', label: 'Green fairway with trees' },
      { url: 'https://images.unsplash.com/photo-1500932334442-8761ee4810a7?w=1200&q=80', label: 'Aerial course view' },
      { url: 'https://images.unsplash.com/photo-1632946269126-0f8edbe8b068?w=1200&q=80', label: 'Ball on the green' },
      { url: 'https://images.unsplash.com/photo-1623567341691-1f47b5cf949e?w=1200&q=80', label: 'Mountain golf course' },
      { url: 'https://images.unsplash.com/photo-1587205476864-4a5a195167b4?w=1200&q=80', label: 'Tropical palm course' },
      { url: 'https://images.unsplash.com/photo-1605144884374-ecbb643615f6?w=1200&q=80', label: 'Riverside course aerial' },
      { url: 'https://images.unsplash.com/photo-1606443192517-919653213206?w=1200&q=80', label: 'Course with distant trees' },
      { url: 'https://images.unsplash.com/photo-1582528979903-bee578216a69?w=1200&q=80', label: 'Lakeside fairway' },
      { url: 'https://images.unsplash.com/photo-1592919505780-303950717480?w=1200&q=80', label: 'Golfer on wide course' },
    ],
  },
  {
    category: 'Golfers & Action',
    images: [
      { url: 'https://images.unsplash.com/photo-1591491659771-3f9777200049?w=1200&q=80', label: 'Golfer holding club' },
      { url: 'https://images.unsplash.com/photo-1535131749006-b7f58c99034b?w=1200&q=80', label: 'Driver swing' },
      { url: 'https://images.unsplash.com/photo-1690288505632-bb7f38d663d4?w=1200&q=80', label: 'Ball next to club' },
      { url: 'https://images.unsplash.com/photo-1662224107406-cfbd51edd90c?w=1200&q=80', label: 'Person playing golf' },
      { url: 'https://images.unsplash.com/photo-1591491640784-3232eb748d4b?w=1200&q=80', label: 'Golfer ready to swing' },
      { url: 'https://images.unsplash.com/photo-1633597468433-fdb200b73f62?w=1200&q=80', label: 'Swing on green field' },
      { url: 'https://images.unsplash.com/photo-1631294949134-ecd4ecd5f4b2?w=1200&q=80', label: 'Mid-swing on course' },
      { url: 'https://images.unsplash.com/photo-1591491680738-eae9159fced6?w=1200&q=80', label: 'Golfer in action' },
      { url: 'https://images.unsplash.com/photo-1535132011086-b8818f016104?w=1200&q=80', label: 'Playing during daytime' },
      { url: 'https://images.unsplash.com/photo-1611374243147-44a702c2d44c?w=1200&q=80', label: 'Golfer on the course' },
    ],
  },
  {
    category: 'Equipment & Gear',
    images: [
      { url: 'https://images.unsplash.com/photo-1602991174407-a015b35a7b00?w=1200&q=80', label: 'Golf cart on course' },
      { url: 'https://images.unsplash.com/photo-1763111332218-bf71f80d258d?w=1200&q=80', label: 'Club striking ball' },
      { url: 'https://images.unsplash.com/photo-1761233976530-d09fc58ad175?w=1200&q=80', label: 'Vintage clubs in bag' },
      { url: 'https://images.unsplash.com/photo-1763111118127-5107b8f38b1e?w=1200&q=80', label: 'Putter with balls and tees' },
      { url: 'https://images.unsplash.com/photo-1770219792075-0aafd9043d77?w=1200&q=80', label: 'Iron head closeup' },
      { url: 'https://images.unsplash.com/photo-1763003275218-6f2c2d0e741a?w=1200&q=80', label: 'Indoor putting practice' },
      { url: 'https://images.unsplash.com/photo-1595827432953-7161e19e303e?w=1200&q=80', label: 'Golf irons on rack' },
      { url: 'https://images.unsplash.com/photo-1763043041179-7675eb1c6b66?w=1200&q=80', label: 'Putter and balls on turf' },
      { url: 'https://images.unsplash.com/photo-1762766375841-b26baebb9547?w=1200&q=80', label: 'Balls in the hole' },
      { url: 'https://images.unsplash.com/photo-1763031382553-a4a8672b378f?w=1200&q=80', label: 'Putter on green turf' },
    ],
  },
  {
    category: 'Events & Venues',
    images: [
      { url: 'https://images.unsplash.com/photo-1766206096984-5b13b0f1eedd?w=1200&q=80', label: 'Spectators watching golfer' },
      { url: 'https://images.unsplash.com/photo-1761074936575-e04432667eaf?w=1200&q=80', label: 'Golf flag on course' },
      { url: 'https://images.unsplash.com/photo-1773338402392-f33ec62abaca?w=1200&q=80', label: 'Golfer sitting on grass' },
      { url: 'https://images.unsplash.com/photo-1670254494696-909c4e429575?w=1200&q=80', label: 'Golfer swinging at event' },
      { url: 'https://images.unsplash.com/photo-1766206096924-c78074981e84?w=1200&q=80', label: 'Tournament spectators' },
      { url: 'https://images.unsplash.com/photo-1763917343408-4cfcc6bdd381?w=1200&q=80', label: 'Golfers with sand traps' },
      { url: 'https://images.unsplash.com/photo-1760253488608-2658f402dc74?w=1200&q=80', label: 'Woman swinging on sunny day' },
      { url: 'https://images.unsplash.com/photo-1762774172043-091b81edd2a2?w=1200&q=80', label: 'Golf branded bags on turf' },
      { url: 'https://images.unsplash.com/photo-1773338437446-723d784c9008?w=1200&q=80', label: 'Woman in golf cart' },
      { url: 'https://images.unsplash.com/photo-1766288020088-4b95f5409376?w=1200&q=80', label: 'Oceanside course dining' },
    ],
  },
  {
    category: 'Lifestyle & Scenery',
    images: [
      { url: 'https://images.unsplash.com/photo-1707995927264-a5b3d6952c6a?w=1200&q=80', label: 'Golfer on scenic course' },
      { url: 'https://images.unsplash.com/photo-1761141987961-ed96a841fe21?w=1200&q=80', label: 'Misty morning course' },
      { url: 'https://images.unsplash.com/photo-1768396747938-1b3c749f6d8f?w=1200&q=80', label: 'Lake and mountain course' },
      { url: 'https://images.unsplash.com/photo-1763113898928-7d25a12f7099?w=1200&q=80', label: 'Balls on putting green' },
      { url: 'https://images.unsplash.com/photo-1764963837399-964ca5944e78?w=1200&q=80', label: 'Golf cart sunny day' },
      { url: 'https://images.unsplash.com/photo-1709525616662-8d9f9a995ceb?w=1200&q=80', label: 'Course from the green' },
      { url: 'https://images.unsplash.com/photo-1443706340763-4b60757a36ce?w=1200&q=80', label: 'Wide green field' },
      { url: 'https://images.unsplash.com/photo-1605147861225-7bcd55f8e513?w=1200&q=80', label: 'Green grass daytime' },
      { url: 'https://images.unsplash.com/photo-1763032859297-6f245877e074?w=1200&q=80', label: 'Indoor putting green' },
      { url: 'https://images.unsplash.com/photo-1762950891047-71950c788609?w=1200&q=80', label: 'Putting green with balls' },
    ],
  },
  {
    category: 'Training & Academy',
    images: [
      { url: 'https://images.unsplash.com/photo-1763002947756-1e5c1fa4dc6e?w=1200&q=80', label: 'Indoor putting practice' },
      { url: 'https://images.unsplash.com/photo-1763042485152-90f540ca8704?w=1200&q=80', label: 'Placing ball on tee' },
      { url: 'https://images.unsplash.com/photo-1762951359246-04032fbbbf55?w=1200&q=80', label: 'Indoor swing practice' },
      { url: 'https://images.unsplash.com/photo-1763118487688-ba93698b0149?w=1200&q=80', label: 'Indoor mini golf' },
      { url: 'https://images.unsplash.com/photo-1763002487829-a177254d758e?w=1200&q=80', label: 'Ball dispenser on turf' },
      { url: 'https://images.unsplash.com/photo-1763044258116-378a2d45d2c5?w=1200&q=80', label: 'Putting green practice' },
      { url: 'https://images.unsplash.com/photo-1763119536099-af7883330642?w=1200&q=80', label: 'Balls spilling from bag' },
      { url: 'https://images.unsplash.com/photo-1763040544499-c7f95476fab2?w=1200&q=80', label: 'Putting on mini course' },
      { url: 'https://images.unsplash.com/photo-1762952078331-a680492cffe3?w=1200&q=80', label: 'Indoor green with TV' },
      { url: 'https://images.unsplash.com/photo-1761315307561-e2ec45a2bb8a?w=1200&q=80', label: 'Clubs arranged on turf' },
    ],
  },
];

interface ImageUploaderProps {
  label?: string;
  value: string;
  onChange: (url: string) => void;
  hint?: string;
  /** Height class for the preview, e.g. "h-32" or "h-48". Default "h-36" */
  previewHeight?: string;
}

export default function ImageUploader({
  label,
  value,
  onChange,
  hint,
  previewHeight = 'h-36',
}: ImageUploaderProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [dragOver, setDragOver] = useState(false);
  const [showUrlInput, setShowUrlInput] = useState(false);
  const [showStockImages, setShowStockImages] = useState(false);
  const [stockCategory, setStockCategory] = useState(STOCK_IMAGES[0].category);

  const handleFiles = async (files: FileList | File[]) => {
    const file = Array.from(files)[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      toast.error('Please select an image file');
      return;
    }

    setIsUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      const media = await api.uploadMedia(formData);
      onChange(resolveUrl(media.url));
    } catch {
      toast.error('Upload failed');
    } finally {
      setIsUploading(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
    if (e.dataTransfer.files) handleFiles(e.dataTransfer.files);
  };

  const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      handleFiles(e.target.files);
      e.target.value = '';
    }
  };

  const displayUrl = resolveUrl(value);
  const activeStock = STOCK_IMAGES.find((c) => c.category === stockCategory) ?? STOCK_IMAGES[0];

  return (
    <div className="space-y-1.5">
      {label && (
        <label className="block text-sm font-medium text-gray-700">{label}</label>
      )}

      {displayUrl ? (
        <div className="relative group rounded-lg overflow-hidden border border-gray-200">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={displayUrl}
            alt={label || 'Uploaded image'}
            className={`w-full ${previewHeight} object-cover`}
          />
          <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="px-3 py-1.5 bg-white text-gray-700 text-xs font-medium rounded-lg hover:bg-gray-100"
            >
              Replace
            </button>
            <button
              type="button"
              onClick={() => onChange('')}
              className="p-1.5 bg-white text-red-600 rounded-lg hover:bg-red-50"
            >
              <X size={14} />
            </button>
          </div>
        </div>
      ) : (
        <div
          onDrop={handleDrop}
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onClick={() => fileInputRef.current?.click()}
          className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${
            dragOver
              ? 'border-blue-400 bg-blue-50'
              : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
          }`}
        >
          {isUploading ? (
            <div className="flex flex-col items-center gap-2">
              <div className="w-6 h-6 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" />
              <p className="text-xs text-gray-500">Uploading...</p>
            </div>
          ) : (
            <>
              <Upload size={20} className="mx-auto text-gray-400 mb-1.5" />
              <p className="text-xs text-gray-500">
                Drop an image or <span className="text-blue-600">click to upload</span>
              </p>
            </>
          )}
        </div>
      )}

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

      {/* Action row */}
      <div className="flex items-center gap-3">
        <button
          type="button"
          onClick={() => setShowUrlInput(!showUrlInput)}
          className="inline-flex items-center gap-1 text-xs text-gray-400 hover:text-gray-600"
        >
          <LinkIcon size={12} />
          {showUrlInput ? 'Hide URL input' : 'Or paste URL'}
        </button>
        <button
          type="button"
          onClick={() => setShowStockImages(!showStockImages)}
          className="inline-flex items-center gap-1 text-xs text-gray-400 hover:text-gray-600"
        >
          <ImageIcon size={12} />
          Image Library
          {showStockImages ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
        </button>
      </div>

      {showUrlInput && (
        <input
          type="url"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="https://..."
          className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      )}

      {showStockImages && (
        <div className="border border-gray-200 rounded-lg p-3 space-y-2.5">
          <div className="flex gap-1.5 flex-wrap">
            {STOCK_IMAGES.map((cat) => (
              <button
                key={cat.category}
                type="button"
                onClick={() => setStockCategory(cat.category)}
                className={`px-2.5 py-1 text-xs rounded-md transition-colors ${
                  stockCategory === cat.category
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                {cat.category} ({cat.images.length})
              </button>
            ))}
          </div>
          <div className="grid grid-cols-5 gap-2">
            {activeStock.images.map((img) => (
              <button
                key={img.url}
                type="button"
                onClick={() => { onChange(img.url); setShowStockImages(false); }}
                className="relative group/stock aspect-video rounded-md overflow-hidden border border-gray-200 hover:border-blue-400 hover:shadow-sm transition-all"
                title={img.label}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={`${img.url.split('?')[0]}?w=200&q=60`} alt={img.label} className="w-full h-full object-cover" />
                <span className="absolute inset-0 bg-black/0 group-hover/stock:bg-black/40 transition-colors flex items-end justify-start p-1.5">
                  <span className="text-white text-[10px] font-medium opacity-0 group-hover/stock:opacity-100 transition-opacity leading-tight drop-shadow-sm">
                    {img.label}
                  </span>
                </span>
              </button>
            ))}
          </div>
          <p className="text-[10px] text-gray-400">60 royalty-free golf images from Unsplash</p>
        </div>
      )}

      {hint && <p className="text-xs text-gray-500">{hint}</p>}
    </div>
  );
}
