import Link from "next/link";
import { notFound } from "next/navigation";
import { ChevronDown } from "lucide-react";
import { DataTable } from "@/components/admin/DataTable";
import { AdminPageHeader, AdminStatusBadge } from "@/components/admin/AdminPresentation";
import { prisma } from "@/lib/prisma";
import { updateServicePayment } from "@/lib/service-request-actions";
import { currency } from "@/lib/utils";

const paymentStatuses = [
  ["PENDING", "Pending"],
  ["PAID", "Paid"],
  ["FAILED", "Failed"],
  ["REFUNDED", "Refunded"]
];

const selectClassName = "w-full cursor-pointer appearance-none rounded border border-[#D8C98F] bg-white px-3 py-2 pr-11 font-bold text-[#171717] shadow-sm transition hover:border-[#B9922F] focus:border-[#B9922F] focus:outline-none focus:ring-2 focus:ring-[#D8C98F]";

function statusOptions(current?: string | null) {
  const options = [...paymentStatuses];
  if (current && !options.some(([value]) => value === current)) {
    options.unshift([current, current]);
  }
  return options;
}

export default async function ServicePaymentDetailPage({ params }: { params: { id: string } }) {
  const record = await prisma.servicePayment.findUnique({
    where: { id: params.id },
    include: { paymentLogs: { orderBy: { createdAt: "desc" } } }
  });
  if (!record) notFound();

  const updateRecord = updateServicePayment.bind(null, record.id);

  return (
    <section>
      <AdminPageHeader
        title={record.serviceType}
        subtitle="Service fee payment request and provider log history."
        action={<Link href="/admin/service-payments" className="btn btn-secondary">Back to Service Payments</Link>}
      />

      <div className="grid gap-4 md:grid-cols-3">
        <div className="panel p-4"><div className="text-[#666]">Payment Status</div><div className="mt-2"><AdminStatusBadge value={record.paymentStatus} /></div></div>
        <div className="panel p-4"><div className="text-[#666]">Amount</div><strong>{currency(String(record.amount))}</strong></div>
        <div className="panel p-4"><div className="text-[#666]">Created</div><strong>{record.createdAt.toLocaleString()}</strong></div>
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.3fr_0.9fr]">
        <div className="grid gap-6">
          <div className="panel grid gap-4 p-5 md:grid-cols-2">
            <h2 className="text-xl font-black md:col-span-2">Customer Details</h2>
            <div><div className="text-sm text-[#666]">Customer Name</div><strong>{record.customerName}</strong></div>
            <div><div className="text-sm text-[#666]">Email</div><strong>{record.customerEmail}</strong></div>
            <div><div className="text-sm text-[#666]">Phone</div><strong>{record.customerPhone}</strong></div>
            <div><div className="text-sm text-[#666]">Payment Method</div><strong>{record.paymentMethod}</strong></div>
            <div className="md:col-span-2"><div className="text-sm text-[#666]">Agreement Accepted</div><strong>{record.agreementAccepted ? "Yes" : "No"}</strong></div>
          </div>

          <div className="panel p-5">
            <h2 className="text-xl font-black">Related Payment Logs</h2>
            <div className="mt-4">
              <DataTable
                headers={["Provider", "Status", "Amount", "Currency", "Created"]}
                rows={record.paymentLogs.map((log) => [
                  log.provider,
                  <AdminStatusBadge key="status" value={log.status} />,
                  currency(String(log.amount)),
                  log.currency,
                  log.createdAt.toLocaleString()
                ])}
              />
            </div>
          </div>
        </div>

        <form action={updateRecord} className="panel grid h-fit gap-4 p-5">
          <h2 className="text-xl font-black">Payment Controls</h2>
          <label>
            Payment Status
            <span className="relative mt-1 block">
              <select name="paymentStatus" defaultValue={record.paymentStatus} className={selectClassName}>
                {statusOptions(record.paymentStatus).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
              </select>
              <ChevronDown className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[#7A5310]" size={18} />
            </span>
          </label>
          <p className="text-sm text-[#666]">This updates the stored admin-facing payment status only. It does not reconcile or change the real payment provider state.</p>
          <button className="btn btn-primary w-fit">Save Payment Status</button>
        </form>
      </div>
    </section>
  );
}
