"use client";

import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Upload, FileText, Trash2, Download, Loader2 } from "lucide-react";

interface CourseFile {
  id: string;
  title: string;
  type: string;
  filePath: string;
  fileSize?: number;
  section?: string;
  createdAt: string;
  course: { title: string; id: string };
}

export default function CoachFiles() {
  const [files, setFiles] = useState<CourseFile[]>([]);
  const [courses, setCourses] = useState<{ id: string; title: string }[]>([]);
  const [courseId, setCourseId] = useState("");
  const [title, setTitle] = useState("");
  const [section, setSection] = useState("عمومی");
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  const load = async () => {
    const token = localStorage.getItem("auth_token");
    const [filesRes, coursesRes] = await Promise.all([
      fetch("/api/upload", { headers: { Authorization: `Bearer ${token}` } }),
      fetch("/api/courses", { headers: { Authorization: `Bearer ${token}` } }),
    ]);
    if (filesRes.ok) setFiles(await filesRes.json());
    if (coursesRes.ok) {
      const data = await coursesRes.json();
      if (Array.isArray(data)) {
        setCourses(data);
        if (data.length > 0 && !courseId) setCourseId(data[0].id);
      }
    }
  };

  useEffect(() => { load(); }, []);

  const handleUpload = async () => {
    setError("");
    if (!selectedFile) { setError("فایل را انتخاب کنید"); return; }
    if (!courseId) { setError("دوره را انتخاب کنید"); return; }

    setUploading(true);
    const token = localStorage.getItem("auth_token");
    try {
      const fd = new FormData();
      fd.append("file", selectedFile);
      fd.append("courseId", courseId);
      fd.append("title", title.trim() || selectedFile.name);
      fd.append("section", section);

      const res = await fetch("/api/upload", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: fd,
      });

      if (!res.ok) throw new Error("خطا");
      setSelectedFile(null);
      setTitle("");
      setSection("عمومی");
      if (inputRef.current) inputRef.current.value = "";
      load();
    } catch {
      setError("خطا در آپلود");
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("حذف شود؟")) return;
    const token = localStorage.getItem("auth_token");
    const res = await fetch(`/api/upload?id=${id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) setFiles((prev) => prev.filter((f) => f.id !== id));
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">مدیریت فایل‌ها</h1>

      <div className="rounded-xl border bg-white p-6 mb-6">
        <h2 className="font-semibold text-gray-900 mb-4">آپلود فایل جدید</h2>

        {selectedFile ? (
          <div className="flex items-center justify-between p-4 rounded-lg border bg-blue-50 mb-4">
            <div className="flex items-center gap-3">
              <FileText className="h-6 w-6 text-[#2563EB]" />
              <div>
                <div className="text-sm font-medium text-gray-900">{selectedFile.name}</div>
                <div className="text-xs text-gray-500">{(selectedFile.size / 1024).toFixed(0)} KB</div>
              </div>
            </div>
            <button onClick={() => { setSelectedFile(null); if (inputRef.current) inputRef.current.value = ""; }}>
              <span className="text-xs text-red-500 hover:underline">حذف</span>
            </button>
          </div>
        ) : (
          <div
            className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-[#2563EB]/40 transition-colors"
            onClick={() => inputRef.current?.click()}
          >
            <Upload className="h-8 w-8 text-gray-400 mx-auto mb-2" />
            <p className="text-sm text-gray-500 mb-2">فایل را اینجا رها کنید یا کلیک کنید</p>
            <Button variant="outline" size="sm" type="button">انتخاب فایل</Button>
          </div>
        )}

        <input
          ref={inputRef}
          type="file"
          className="hidden"
          onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
        />

        <div className="grid md:grid-cols-3 gap-4 mt-4">
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">دوره</label>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
              value={courseId}
              onChange={(e) => setCourseId(e.target.value)}
            >
              {courses.map((c) => (
                <option key={c.id} value={c.id}>{c.title}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">عنوان</label>
            <input
              className="w-full px-3 py-2 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={selectedFile?.name || "نام فایل"}
            />
          </div>

          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">بخش</label>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
              value={section}
              onChange={(e) => setSection(e.target.value)}
            >
              <option value="عمومی">عمومی</option>
              <option value="جزوه">جزوه</option>
              <option value="تمرین">تمرین</option>
              <option value="منابع">منابع</option>
              <option disabled>──────────</option>
              {Array.from({ length: 20 }, (_, i) => (
                <option key={i + 1} value={`جلسه ${i + 1}`}>جلسه {i + 1}</option>
              ))}
            </select>
          </div>
        </div>

        {error && <p className="text-sm text-red-600 mt-2">{error}</p>}

        <Button
          className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white mt-4"
          onClick={handleUpload}
          disabled={uploading || !selectedFile}
        >
          {uploading ? <Loader2 className="h-4 w-4 animate-spin ml-1" /> : <Upload className="h-4 w-4 ml-1" />}
          {uploading ? "در حال آپلود..." : "آپلود فایل"}
        </Button>
      </div>

      <div className="rounded-xl border bg-white overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-gray-600">
            <tr>
              <th className="text-right p-3 font-medium">عنوان</th>
              <th className="text-right p-3 font-medium">دوره</th>
              <th className="text-right p-3 font-medium">نوع</th>
              <th className="text-right p-3 font-medium">بخش</th>
              <th className="text-left p-3 font-medium">عملیات</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {files.length === 0 ? (
              <tr>
                <td colSpan={5} className="p-8 text-center text-gray-500">فایلی آپلود نشده است</td>
              </tr>
            ) : (
              files.map((f) => (
                <tr key={f.id}>
                  <td className="p-3">
                    <div className="flex items-center gap-2">
                      <FileText className="h-4 w-4 text-gray-400" />
                      {f.title}
                    </div>
                  </td>
                  <td className="p-3 text-gray-500">{f.course.title}</td>
                  <td className="p-3 text-gray-500">{f.type.split("/").pop()?.toUpperCase() || f.type.toUpperCase()}</td>
                  <td className="p-3 text-gray-500">{f.section || "عمومی"}</td>
                  <td className="p-3 text-left">
                    <div className="flex items-center justify-end gap-1">
                      <a href={f.filePath} download>
                        <Button variant="ghost" size="icon-xs"><Download className="h-3.5 w-3.5" /></Button>
                      </a>
                      <Button variant="ghost" size="icon-xs" className="text-red-500" onClick={() => handleDelete(f.id)}>
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
