import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import PageShell from "./_pageShell";
import { api } from "../services/api";
import { Table } from "../components/ui/Table";

async function listPlans() {
  const res = await api.get("/api/admin/billing/plans/");
  return res.data;
}
async function listInvoices() {
  const res = await api.get("/api/admin/billing/invoices/");
  return res.data;
}

export default function Billing() {
  const [tab, setTab] = useState("plans");
  const plansQ = useQuery({ queryKey: ["plans"], queryFn: listPlans });
  const invQ = useQuery({ queryKey: ["invoices"], queryFn: listInvoices });

  const plans = Array.isArray(plansQ.data) ? plansQ.data : (plansQ.data?.results || []);
  const invoices = Array.isArray(invQ.data) ? invQ.data : (invQ.data?.results || []);

  return (
    <PageShell title="Billing">
      <div className="flex gap-2 mb-4">
        <button onClick={()=>setTab("plans")} className={`rounded-xl px-3 py-2 text-sm ${tab==="plans"?"bg-black text-white":"bg-white border border-neutral-200"}`}>Plans</button>
        <button onClick={()=>setTab("invoices")} className={`rounded-xl px-3 py-2 text-sm ${tab==="invoices"?"bg-black text-white":"bg-white border border-neutral-200"}`}>Invoices</button>
      </div>

      {(plansQ.error || invQ.error) && (
        <div className="mb-4 rounded-xl bg-amber-50 px-4 py-3 text-sm text-amber-800">
          Billing module endpoints needed:
          <ul className="list-disc pl-5 mt-2">
            <li><code className="rounded bg-white/60 px-1">GET /api/admin/billing/plans/</code></li>
            <li><code className="rounded bg-white/60 px-1">GET /api/admin/billing/invoices/</code></li>
          </ul>
        </div>
      )}

      {tab === "plans" ? (
        <Table
          columns={[
            { key: "name", header: "Plan" },
            { key: "price", header: "Price" },
            { key: "period_days", header: "Period (days)" },
            { key: "storage_limit", header: "Storage limit" },
            { key: "is_active", header: "Active", render: (r) => (r.is_active ? "Yes" : "No") },
          ]}
          rows={plans}
          emptyText={plansQ.isLoading ? "Loading..." : "No plans"}
        />
      ) : (
        <Table
          columns={[
            { key: "number", header: "Invoice #" },
            { key: "user", header: "User" },
            { key: "status", header: "Status" },
            { key: "total", header: "Total" },
            { key: "discount", header: "Discount" },
            { key: "created_at", header: "Created" },
          ]}
          rows={invoices}
          emptyText={invQ.isLoading ? "Loading..." : "No invoices"}
        />
      )}
    </PageShell>
  );
}
