"use client";

import { useEffect, useState } from "react";
import { useAuth } from "@/lib/stores/auth-store";

interface Payment {
  id: string;
  amount: string;
  status: string;
  description?: string;
  paidAt?: string;
  createdAt: string;
  userId: string;
  registration?: {
    course: { title: string };
    user: { fullName?: string; phone: string };
  };
  user: { fullName?: string; phone: string };
}

interface Board {
  id: string;
  name: string;
}

interface Sport {
  id: string;
  name: string;
}

export default function AdminFinance() {
  const { token } = useAuth();
  const [payments, setPayments] = useState<Payment[]>([]);
  const [boards, setBoards] = useState<Board[]>([]);
  const [sports, setSports] = useState<Sport[]>([]);
  const [selectedBoardId, setSelectedBoardId] = useState("");
  const [selectedSportId, setSelectedSportId] = useState("");

  useEffect(() => {
    if (!token) return;
    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(() => {});
  }, [token]);

  useEffect(() => {
    if (!token) return;
    const params = new URLSearchParams();
    if (selectedBoardId) params.set("boardId", selectedBoardId);
    if (selectedSportId) params.set("sportId", selectedSportId);
    const qs = params.toString();
    fetch(`/api/payments${qs ? `?${qs}` : ""}`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(async (r) => {
        if (!r.ok) {
          const err = await r.json().catch(() => ({}));
          throw new Error(err.error || `HTTP ${r.status}`);
        }
        return r.json();
      })
      .then(setPayments)
      .catch((e) => {
        console.error("Finance fetch error:", e);
        setPayments([]);
      });
  }, [token, selectedBoardId, selectedSportId]);

  const totalRevenue = payments.reduce((sum, t) => sum + Number(t.amount || 0), 0);
  const todayCount = payments.filter(
    (t) => new Date(t.createdAt).toDateString() === new Date().toDateString()
  ).length;
  const paidCount = payments.filter((t) => t.status === "PAID").length;
  const pendingCount = payments.filter((t) => t.status === "PENDING" || t.status === "FAILED").length;

  const inputClass = "rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 focus:border-[#2563EB] focus:ring-1 focus:ring-[#2563EB]/20 outline-none transition-colors";

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

      <div className="grid md:grid-cols-4 gap-4 mb-6">
        {[
          { label: "کل درآمد", value: `${totalRevenue.toLocaleString()} ریال` },
          { label: "تراکنش‌های امروز", value: String(todayCount) },
          { label: "پرداخت‌های موفق", value: String(paidCount) },
          { label: "در انتظار پرداخت", value: String(pendingCount) },
        ].map((item) => (
          <div key={item.label} className="rounded-xl border bg-white p-4">
            <div className="text-sm text-gray-500">{item.label}</div>
            <div className="text-lg font-bold text-gray-900">{item.value}</div>
          </div>
        ))}
      </div>

      <div className="flex gap-3 mb-4">
        <select
          className={inputClass}
          value={selectedBoardId}
          onChange={(e) => setSelectedBoardId(e.target.value)}
        >
          <option value="">همه هیئت‌ها</option>
          {boards.map((b) => (
            <option key={b.id} value={b.id}>{b.name}</option>
          ))}
        </select>
        <select
          className={inputClass}
          value={selectedSportId}
          onChange={(e) => setSelectedSportId(e.target.value)}
        >
          <option value="">همه رشته‌ها</option>
          {sports.map((s) => (
            <option key={s.id} value={s.id}>{s.name}</option>
          ))}
        </select>
      </div>

      <div className="rounded-xl border bg-white overflow-hidden">
        <div className="overflow-x-auto">
          <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-right p-3 font-medium">وضعیت</th>
                <th className="text-right p-3 font-medium">تاریخ</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {payments.length === 0 ? (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-gray-500">تراکنشی وجود ندارد</td>
                </tr>
              ) : (
                payments.map((p) => (
                  <tr key={p.id}>
                    <td className="p-3 text-gray-500 font-mono text-xs">{p.id.slice(0, 8)}...</td>
                    <td className="p-3">{p.user?.fullName || p.registration?.user?.fullName || p.user?.phone || "-"}</td>
                    <td className="p-3">{p.registration?.course?.title || p.description || "-"}</td>
                    <td className="p-3 font-medium">{Number(p.amount).toLocaleString()} ریال</td>
                    <td className="p-3">
                      <span className={p.status === "PAID" ? "text-green-600 font-medium" : p.status === "PENDING" ? "text-amber-600" : "text-red-600"}>
                        {p.status === "PAID" ? "پرداخت شده" : p.status === "PENDING" ? "در انتظار" : "لغو شده"}
                      </span>
                    </td>
                    <td className="p-3 text-gray-500">{new Date(p.paidAt || p.createdAt).toLocaleDateString("fa-IR")}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
