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

const requestStatuses = [
  ["NEW", "New"],
  ["IN_REVIEW", "In Review"],
  ["CONTACTED", "Contacted"],
  ["RESOLVED", "Resolved"],
  ["CLOSED", "Closed"]
];

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 = [...requestStatuses];
  if (current && !options.some(([value]) => value === current)) {
    options.unshift([current, current]);
  }
  return options;
}

function maskBankDetails(value: string) {
  const trimmed = value.trim();
  if (!trimmed) return "Not provided";
  if (trimmed.length <= 8) return "Provided";
  return `${trimmed.slice(0, 4)}...${trimmed.slice(-4)}`;
}

export default async function SellBackRequestDetailPage({ params }: { params: { id: string } }) {
  const record = await prisma.sellBackRequest.findUnique({ where: { id: params.id } });
  if (!record) notFound();

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

  return (
    <section>
      <AdminPageHeader
        title={record.fullName}
        subtitle="Sell-back request details for manual bullion review and follow-up."
        action={<Link href="/admin/sell-back-requests" className="btn btn-secondary">Back to Sell-Back Requests</Link>}
      />

      <div className="grid gap-4 md:grid-cols-3">
        <div className="panel p-4"><div className="text-[#666]">Status</div><div className="mt-2"><AdminStatusBadge value={record.status} /></div></div>
        <div className="panel p-4"><div className="text-[#666]">Created</div><strong>{record.createdAt.toLocaleString()}</strong></div>
        <div className="panel p-4"><div className="text-[#666]">Payout Details</div><strong>{maskBankDetails(record.bankDetailsForPayout)}</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">Seller Details</h2>
            <div><div className="text-sm text-[#666]">Email</div><strong>{record.email}</strong></div>
            <div><div className="text-sm text-[#666]">Phone</div><strong>{record.phone}</strong></div>
            <div><div className="text-sm text-[#666]">Signature</div><strong>{record.signature}</strong></div>
            <div><div className="text-sm text-[#666]">Ownership Declaration</div><strong>{record.ownershipDeclarationAccepted ? "Accepted" : "Not accepted"}</strong></div>
            <div><div className="text-sm text-[#666]">AML/KYC Confirmation</div><strong>{record.amlKycAccepted ? "Accepted" : "Not accepted"}</strong></div>
            <div><div className="text-sm text-[#666]">Photo Links</div><strong>{record.photoUrls || "None provided"}</strong></div>
          </div>

          <div className="panel grid gap-4 p-5 md:grid-cols-2">
            <h2 className="text-xl font-black md:col-span-2">Product Details</h2>
            <div><div className="text-sm text-[#666]">Product Type</div><strong>{record.productType}</strong></div>
            <div><div className="text-sm text-[#666]">Weight</div><strong>{record.weight}</strong></div>
            <div><div className="text-sm text-[#666]">Mint / Brand</div><strong>{record.mintBrand}</strong></div>
            <div><div className="text-sm text-[#666]">Condition</div><strong>{record.condition}</strong></div>
            <div><div className="text-sm text-[#666]">Packaging</div><strong>{record.packagingCondition}</strong></div>
            <div><div className="text-sm text-[#666]">Serial Number</div><strong>{record.serialNumber || "Not provided"}</strong></div>
            <div><div className="text-sm text-[#666]">Purchase Date</div><strong>{record.purchaseDate ? record.purchaseDate.toLocaleDateString() : "Not provided"}</strong></div>
            <div><div className="text-sm text-[#666]">Purchase Source</div><strong>{record.purchaseSource || "Not provided"}</strong></div>
          </div>
        </div>

        <form action={updateRecord} className="panel grid h-fit gap-4 p-5">
          <h2 className="text-xl font-black">Request Controls</h2>
          <label>
            Status
            <span className="relative mt-1 block">
              <select name="status" defaultValue={record.status} className={selectClassName}>
                {statusOptions(record.status).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>
          <label>
            Admin Notes
            <textarea name="adminNotes" defaultValue={record.adminNotes || ""} />
          </label>
          <button className="btn btn-primary w-fit">Save Sell-Back Updates</button>
        </form>
      </div>
    </section>
  );
}
