import { redirect } from "next/navigation";
import {
  adminAddWholesaleLotAction,
  adminCreateAuctionAction,
  adminSetRoleAction,
} from "@/app/actions/community";
import { PageShell } from "@/components/page";
import { prisma } from "@/lib/prisma";
import { AUCTION_CATEGORIES, isAdmin } from "@/lib/roles";
import { readSession } from "@/lib/session";

export default async function AdminPage() {
  const session = await readSession();
  if (!isAdmin(session)) redirect("/directory");

  const members = await prisma.user.findMany({
    include: { profile: true },
    orderBy: { createdAt: "desc" },
  });
  const reports = await prisma.report.findMany({ take: 10, orderBy: { createdAt: "desc" } });

  return (
    <PageShell
      wide
      eyebrow="Master control"
      title="Trust queue"
      lede="Approve members, verify professionals, grant wholesale, schedule auctions. Gem inventory stays in the staff app."
    >
      <section>
        <h2 className="text-2xl">Members</h2>
        <div className="mt-4 overflow-x-auto">
          <table className="eg-table min-w-[720px] text-sm">
            <thead>
              <tr>
                <th>Member</th>
                <th>Type</th>
                <th>Access</th>
              </tr>
            </thead>
            <tbody>
              {members.map((member) => (
                <tr key={member.id}>
                  <td>
                    <strong>{member.name}</strong>
                    <div className="text-muted">{member.email}</div>
                    <div className="text-muted">verify: {member.verificationStatus}</div>
                  </td>
                  <td>{member.profile?.type}</td>
                  <td>
                    <form action={adminSetRoleAction.bind(null, member.id)} className="flex flex-wrap items-center gap-2">
                      <select name="role" defaultValue={member.role}>
                        <option value="member">member</option>
                        <option value="verified">verified</option>
                        <option value="wholesale">wholesale</option>
                        <option value="admin">admin</option>
                      </select>
                      <select name="verificationStatus" defaultValue={member.verificationStatus}>
                        <option value="pending">pending</option>
                        <option value="approved">approved</option>
                        <option value="rejected">rejected</option>
                      </select>
                      <select name="wholesaleStatus" defaultValue={member.wholesaleStatus}>
                        <option value="none">none</option>
                        <option value="pending">pending</option>
                        <option value="approved">approved</option>
                        <option value="revoked">revoked</option>
                      </select>
                      <label className="flex items-center gap-2 text-xs uppercase tracking-[0.1em]">
                        <input type="checkbox" name="featured" defaultChecked={member.featured} className="w-auto" />
                        Feature
                      </label>
                      <button className="eg-btn eg-btn-solid !py-2" type="submit">
                        Update
                      </button>
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      <section className="mt-12 grid gap-8 md:grid-cols-2">
        <form action={adminCreateAuctionAction} className="eg-card grid gap-3">
          <h2 className="text-xl">Schedule an auction lot</h2>
          <input name="title" placeholder="Title" required />
          <select name="category" defaultValue="medium">
            {AUCTION_CATEGORIES.map((item) => (
              <option key={item.value} value={item.value}>
                {item.label}
              </option>
            ))}
          </select>
          <textarea name="description" rows={3} placeholder="Description" />
          <input name="origin" placeholder="Origin" />
          <input name="certification" placeholder="Lab / cert number" />
          <input name="treatment" placeholder="Treatment" />
          <input name="startingBid" type="number" placeholder="Starting bid" required />
          <input name="minIncrement" type="number" placeholder="Min increment" defaultValue={50} />
          <label className="eg-label">Starts</label>
          <input name="startsAt" type="datetime-local" required />
          <label className="eg-label">Ends</label>
          <input name="endsAt" type="datetime-local" required />
          <label className="flex items-center gap-2 text-sm">
            <input name="memberOnly" type="checkbox" className="w-auto" defaultChecked /> Member only
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input name="wholesaleOnly" type="checkbox" className="w-auto" /> Wholesale only
          </label>
          <button className="eg-btn eg-btn-accent w-fit" type="submit">
            Publish lot
          </button>
        </form>

        <form action={adminAddWholesaleLotAction} className="eg-card grid gap-3">
          <h2 className="text-xl">Add wholesale lot</h2>
          <input name="title" placeholder="Title" required />
          <input name="origin" placeholder="Origin" />
          <textarea name="description" rows={3} placeholder="Description" />
          <input name="wholesalePrice" type="number" placeholder="Wholesale price" required />
          <input name="quantity" type="number" placeholder="Quantity" defaultValue={1} />
          <input name="certificate" placeholder="Certificate" />
          <input name="treatment" placeholder="Treatment" />
          <label className="flex items-center gap-2 text-sm">
            <input name="privateOffer" type="checkbox" className="w-auto" /> Private offer
          </label>
          <button className="eg-btn eg-btn-solid w-fit" type="submit">
            Add to trade desk
          </button>
        </form>
      </section>

      {reports.length ? (
        <section className="mt-12">
          <h2 className="text-2xl">Reports</h2>
          <ul className="mt-3">
            {reports.map((report) => (
              <li key={report.id}>
                {report.targetType} {report.targetId} — {report.reason}
              </li>
            ))}
          </ul>
        </section>
      ) : null}
    </PageShell>
  );
}
