"use client";

import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Upload, X, Loader2 } from "lucide-react";

export default function NewGallery() {
  const router = useRouter();
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState("");
  const [title, setTitle] = useState("");
  const [boardId, setBoardId] = useState("");
  const [sportId, setSportId] = useState("");
  const [boards, setBoards] = useState<{ id: string; name: string }[]>([]);
  const [sports, setSports] = useState<{ id: string; name: string }[]>([]);
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const token = localStorage.getItem("auth_token");
    Promise.all([
      fetch("/api/admin/boards", { headers: { Authorization: `Bearer ${token}` } }).then(r => r.json()),
      fetch("/api/sports", { headers: { Authorization: `Bearer ${token}` } }).then(r => r.json()),
    ]).then(([b, s]) => {
      if (Array.isArray(b)) setBoards(b);
      if (Array.isArray(s)) setSports(s);
    }).catch(() => {});
  }, []);

  const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f || !f.type.startsWith("image/")) return;
    setFile(f);
    setPreview(URL.createObjectURL(f));
  };

  const handleSubmit = async () => {
    setError("");
    if (!file) { setError("تصویر را انتخاب کنید"); return; }

    setSubmitting(true);
    const token = localStorage.getItem("auth_token");
    try {
      const fd = new FormData();
      fd.append("file", file);
      if (title.trim()) fd.append("title", title.trim());
      if (boardId) fd.append("boardId", boardId);
      if (sportId) fd.append("sportId", sportId);

      const res = await fetch("/api/gallery", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: fd,
      });
      if (!res.ok) throw new Error("خطا");
      router.push("/dashboard/admin/gallery");
      router.refresh();
    } catch {
      setError("خطا در آپلود");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto">
      <button
        onClick={() => router.push("/dashboard/admin/gallery")}
        className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900 mb-4 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        بازگشت
      </button>

      <h1 className="text-2xl font-bold text-gray-900 mb-6">تصویر جدید</h1>

      <div className="space-y-6">
        <div className="border rounded-xl p-6 bg-white space-y-4">
          {preview ? (
            <div className="relative rounded-lg overflow-hidden border border-gray-200">
              <img src={preview} alt="" className="w-full aspect-video object-cover" />
              <button
                type="button"
                onClick={() => { setFile(null); setPreview(""); }}
                className="absolute top-2 left-2 w-8 h-8 rounded-full bg-black/50 flex items-center justify-center hover:bg-black/70"
              >
                <X className="h-4 w-4 text-white" />
              </button>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => inputRef.current?.click()}
              className="w-full aspect-video rounded-lg border-2 border-dashed border-gray-200 bg-gray-50 hover:bg-gray-100 hover:border-[#2563EB]/40 transition-all flex flex-col items-center justify-center gap-1.5"
            >
              <Upload className="h-6 w-6 text-gray-400" />
              <span className="text-sm text-gray-500">انتخاب تصویر</span>
            </button>
          )}

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

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">توضیحات (اختیاری)</label>
            <input
              className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="توضیح کوتاه..."
            />
          </div>

          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">هیئت ورزشی (اختیاری)</label>
              <select
                className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                value={boardId}
                onChange={(e) => setBoardId(e.target.value)}
              >
                <option value="">همه هیئت‌ها</option>
                {boards.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">رشته ورزشی (اختیاری)</label>
              <select
                className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                value={sportId}
                onChange={(e) => setSportId(e.target.value)}
              >
                <option value="">همه رشته‌ها</option>
                {sports.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
          </div>
        </div>

        {error && <div className="text-sm text-red-600 bg-red-50 p-3 rounded-lg">{error}</div>}

        <div className="flex gap-3">
          <Button
            className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1"
            onClick={handleSubmit}
            disabled={submitting}
          >
            {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : "آپلود"}
          </Button>
          <Button variant="outline" className="flex-1" onClick={() => router.push("/dashboard/admin/gallery")}>
            انصراف
          </Button>
        </div>
      </div>
    </div>
  );
}
