'use client';

import React, { useState } from 'react';
import { Upload, X } from 'lucide-react';
import { apiUpload } from '../lib/api';

type Kind = 'players' | 'teams' | 'tournaments' | 'matches' | 'banner';

type Props = {
  kind: Kind;
  value: string;
  onChange: (url: string) => void;
  label?: string;
  /** preview aspect — square for logos/photos, wide for banners */
  aspect?: 'square' | 'wide';
};

export function AdminImageUpload({
  kind,
  value,
  onChange,
  label = 'Photo',
  aspect = 'square',
}: Props) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');

  const upload = async (file: File) => {
    setError('');
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
      setError('Use JPG, PNG, or WebP only.');
      return;
    }
    if (file.size > 3 * 1024 * 1024) {
      setError('Max size 3MB.');
      return;
    }
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await apiUpload<{ url: string }>(`/uploads/${kind}`, fd);
      onChange(res.data.url);
    } catch (e: any) {
      setError(e.message || 'Upload failed');
    } finally {
      setUploading(false);
    }
  };

  const box =
    aspect === 'wide'
      ? 'h-24 w-40'
      : 'h-20 w-20';

  return (
    <div className="space-y-2">
      <p className="text-[11px] font-semibold uppercase tracking-wide text-zinc-400">{label}</p>
      <div className="flex flex-wrap items-start gap-3">
        {value ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={value}
            alt=""
            className={`${box} rounded-xl border border-zinc-700 object-cover`}
          />
        ) : (
          <div
            className={`flex ${box} items-center justify-center rounded-xl border border-dashed border-zinc-700 bg-zinc-950 text-[10px] text-zinc-500`}
          >
            No image
          </div>
        )}
        <div className="space-y-2">
          <label className="inline-flex min-h-11 cursor-pointer items-center gap-2 rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2.5 text-xs font-semibold text-zinc-200 hover:border-emerald-600 hover:text-emerald-400">
            <Upload className="h-3.5 w-3.5" />
            {uploading ? 'Uploading…' : 'Upload image'}
            <input
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="hidden"
              disabled={uploading}
              onChange={(e) => {
                const file = e.target.files?.[0];
                if (file) upload(file);
                e.target.value = '';
              }}
            />
          </label>
          {value && (
            <button
              type="button"
              onClick={() => onChange('')}
              className="flex items-center gap-1 text-[11px] text-zinc-500 hover:text-rose-400"
            >
              <X className="h-3 w-3" /> Remove
            </button>
          )}
          <p className="text-[10px] text-zinc-500">JPG / PNG / WebP · max 3MB</p>
        </div>
      </div>
      {error && <p className="text-[11px] text-rose-400">{error}</p>}
    </div>
  );
}
