"use client";

import { useState, useRef } from "react";
import { Upload, X, Loader2, FileImage } from "lucide-react";

export interface UploadResult {
  fileId: string;
  contentType: string;
  mediaType: "image" | "gif" | "video";
  size: number;
  name: string;
}

const ACCEPT = "image/png,image/jpeg,image/webp,image/gif,video/mp4,video/webm";

export default function MediaUploader({
  value,
  onChange,
  label = "Medya Dosyası",
  accept = ACCEPT,
  className = "",
}: {
  value: UploadResult | null;
  onChange: (v: UploadResult | null) => void;
  label?: string;
  accept?: string;
  className?: string;
}) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  async function handleSelect(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    setLoading(true);
    setError(null);

    const fd = new FormData();
    fd.append("file", file);

    try {
      const res = await fetch("/api/files", {
        method: "POST",
        body: fd,
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Yükleme başarısız");
      onChange(data as UploadResult);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Yükleme hatası");
    } finally {
      setLoading(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }

  return (
    <div className={className}>
      <label className="block text-sm text-brand-200 mb-1">{label}</label>
      {value ? (
        <div className="relative glass rounded-xl overflow-hidden">
          <div className="aspect-video bg-black/40 flex items-center justify-center">
            {value.mediaType === "video" ? (
              <video
                src={`/api/files/${value.fileId}`}
                controls
                className="max-w-full max-h-full"
              />
            ) : (
              <img
                src={`/api/files/${value.fileId}`}
                alt={value.name}
                className="max-w-full max-h-full object-contain"
              />
            )}
          </div>
          <div className="p-3 flex items-center justify-between gap-3 border-t border-brand-700/30">
            <div className="text-xs text-brand-300 truncate">
              <span className="font-medium text-white">{value.name}</span>
              <span className="ml-2 text-brand-400">
                {(value.size / 1024).toFixed(1)} KB · {value.mediaType.toUpperCase()}
              </span>
            </div>
            <button
              type="button"
              onClick={() => onChange(null)}
              className="text-red-300 hover:text-red-200 p-1"
              aria-label="Kaldır"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      ) : (
        <button
          type="button"
          onClick={() => inputRef.current?.click()}
          disabled={loading}
          className="w-full glass rounded-xl border-2 border-dashed border-brand-700/50 hover:border-brand-400 transition p-8 text-center disabled:opacity-60"
        >
          {loading ? (
            <Loader2 className="w-8 h-8 mx-auto text-brand-300 animate-spin" />
          ) : (
            <Upload className="w-8 h-8 mx-auto text-brand-300" />
          )}
          <p className="mt-2 text-sm text-brand-200">
            {loading ? "Yükleniyor..." : "Dosya seçmek için tıklayın"}
          </p>
          <p className="mt-1 text-xs text-brand-400">
            PNG, JPG, GIF, WEBP, MP4, WEBM (max 60MB)
          </p>
        </button>
      )}
      <input
        ref={inputRef}
        type="file"
        accept={accept}
        onChange={handleSelect}
        className="hidden"
      />
      {error && (
        <p className="mt-2 text-xs text-red-300 inline-flex items-center gap-1">
          <FileImage className="w-3 h-3" /> {error}
        </p>
      )}
    </div>
  );
}
