"use client";

import { useRef, useState } from "react";
import Image from "next/image";
import { Upload, X, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";

interface Props {
  value?: string;
  onChange: (url: string) => void;
  className?: string;
}

export function ImageUpload({ value, onChange, className }: Props) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  async function handleFile(file: File) {
    setError(null);
    setUploading(true);
    try {
      const form = new FormData();
      form.append("file", file);
      const res = await fetch("/api/admin/upload", { method: "POST", body: form });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? "Upload failed");
      onChange(data.url);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Upload failed");
    } finally {
      setUploading(false);
    }
  }

  function handleDrop(e: React.DragEvent) {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  }

  return (
    <div className={cn("space-y-2", className)}>
      {value ? (
        <div className="relative group">
          <div className="relative h-48 w-full overflow-hidden rounded-lg border border-border">
            <Image src={value} alt="Cover image" fill className="object-cover" unoptimized />
          </div>
          <button
            type="button"
            onClick={() => onChange("")}
            className="absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded-full bg-danger/90 text-white opacity-0 transition-opacity group-hover:opacity-100"
          >
            <X size={14} />
          </button>
          <div className="mt-2 font-mono text-xs text-text-secondary truncate">{value}</div>
        </div>
      ) : (
        <div
          onDrop={handleDrop}
          onDragOver={(e) => e.preventDefault()}
          onClick={() => inputRef.current?.click()}
          className="flex h-40 cursor-pointer flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-border transition-colors hover:border-accent/40 hover:bg-surface-hover"
        >
          {uploading ? (
            <Loader2 size={24} className="animate-spin text-accent" />
          ) : (
            <>
              <Upload size={24} className="text-text-secondary" />
              <div className="text-center">
                <p className="text-sm font-medium text-text-primary">آپلود تصویر</p>
                <p className="text-xs text-text-secondary">کلیک یا کشیدن فایل — JPG, PNG, WebP تا ۱۰ مگ</p>
              </div>
            </>
          )}
        </div>
      )}

      {error && <p className="text-xs text-danger">{error}</p>}

      {/* URL input */}
      <div className="flex gap-2">
        <input
          type="url"
          placeholder="یا آدرس URL عکس را وارد کنید..."
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          className="flex-1 rounded-lg border border-border bg-surface-hover px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus:border-accent/50 focus:outline-none"
        />
      </div>

      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (file) handleFile(file);
          e.target.value = "";
        }}
      />
    </div>
  );
}
