'use client';

import { useRef, useState } from 'react';
import toast from 'react-hot-toast';
import { Upload, RotateCcw, Loader2 } from 'lucide-react';
import { Btn, Field } from '@/components/admin/marketing/ui';

// Picks the image used in the Facebook ad. Ad creatives are often different
// from the website's product photos, so besides the product images the admin
// can upload a dedicated ad image (stored on Cloudinary; the full https URL
// is saved as the ad's image_url and uploaded to Facebook on publish).

const MAX_MB = 8;
const TYPES = ['image/jpeg', 'image/png', 'image/webp'];
// Meta's minimum for link ads; 1080×1080 or 1200×628 is recommended.
const MIN_SIDE = 600;

interface AdImagePickerProps {
  value: string;
  onChange: (url: string) => void;
  productImages?: string[];
  // The image the ad started with (product image) — "Use original" goes back to it.
  originalImage?: string | null;
}

function imageSize(file: File): Promise<{ width: number; height: number } | null> {
  return new Promise((resolve) => {
    const url = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      resolve({ width: img.naturalWidth, height: img.naturalHeight });
      URL.revokeObjectURL(url);
    };
    img.onerror = () => {
      resolve(null);
      URL.revokeObjectURL(url);
    };
    img.src = url;
  });
}

export default function AdImagePicker({ value, onChange, productImages = [], originalImage }: AdImagePickerProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  const choices = Array.from(new Set([...productImages, ...(originalImage ? [originalImage] : [])].filter(Boolean)));

  const upload = async (file: File) => {
    if (!TYPES.includes(file.type)) {
      toast.error('Use a JPG, PNG or WebP image');
      return;
    }
    if (file.size > MAX_MB * 1024 * 1024) {
      toast.error(`Image must be under ${MAX_MB} MB`);
      return;
    }
    const size = await imageSize(file);
    if (size && Math.min(size.width, size.height) < MIN_SIDE) {
      toast(`This image is ${size.width}×${size.height}. Facebook recommends at least 1080×1080 — it may look blurry.`, { icon: '⚠️' });
    }

    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('folder', 'ads');
      const res = await fetch('/api/cloudinary-upload', { method: 'POST', body: fd });
      const data = await res.json().catch(() => ({}));
      const url: string | undefined = data?.data?.url;
      if (!res.ok || !data.success || !url) throw new Error(data?.message || 'Upload failed');
      onChange(url);
      toast.success('Ad image uploaded');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Upload failed');
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = '';
    }
  };

  return (
    <Field label="Ad image" hint="Square 1080×1080 or landscape 1200×628 works best. JPG/PNG/WebP, up to 8 MB.">
      <div className="space-y-2">
        <div className="flex flex-wrap items-center gap-2">
          {choices.map((img) => (
            <button
              key={img}
              type="button"
              onClick={() => onChange(img)}
              title={img === originalImage ? 'Original image' : 'Product image'}
              className="h-16 w-16 overflow-hidden rounded-lg cursor-pointer"
              style={{ outline: value === img ? '2px solid var(--color-cta)' : '1px solid var(--color-border)' }}
            >
              {/* eslint-disable-next-line @next/next/no-img-element -- any image URL; small choice thumbnail */}
              <img src={img} alt="" className="h-full w-full object-cover" />
            </button>
          ))}
          {value && !choices.includes(value) && (
            <div className="h-16 w-16 overflow-hidden rounded-lg" style={{ outline: '2px solid var(--color-cta)' }} title="Uploaded ad image">
              {/* eslint-disable-next-line @next/next/no-img-element -- uploaded ad image preview */}
              <img src={value} alt="" className="h-full w-full object-cover" />
            </div>
          )}
        </div>
        <div className="flex flex-wrap gap-2">
          <input
            ref={inputRef}
            type="file"
            accept={TYPES.join(',')}
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) void upload(file);
            }}
          />
          <Btn type="button" onClick={() => inputRef.current?.click()} disabled={uploading}>
            {uploading ? <Loader2 size={15} className="animate-spin" /> : <Upload size={15} />}
            {uploading ? 'Uploading…' : 'Upload ad image'}
          </Btn>
          {originalImage && value !== originalImage && (
            <Btn type="button" onClick={() => onChange(originalImage)} disabled={uploading}>
              <RotateCcw size={15} /> Use original image
            </Btn>
          )}
        </div>
      </div>
    </Field>
  );
}
