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 { updateIraTrustApplication } 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 maskOptionalValue(value?: string | null) {
  const text = value?.trim();
  if (!text) return "Not provided";
  const compact = text.replace(/\s+/g, "");
  if (compact.length <= 4) return "Provided";
  return `Provided ending in ${compact.slice(-4)}`;
}

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

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

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

  return (
    <section>
      <AdminPageHeader
        title={record.fullName}
        subtitle="IRA and trust intake details for manual follow-up."
        action={<Link href="/admin/ira-trust-applications" className="btn btn-secondary">Back to Applications</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]">Sensitive SSN Field</div><strong>{maskOptionalValue(record.ssnOptional)}</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">Applicant 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]">Date of Birth</div><strong>{record.dateOfBirth.toLocaleDateString()}</strong></div>
            <div><div className="text-sm text-[#666]">Citizenship</div><strong>{record.citizenshipStatus}</strong></div>
            <div className="md:col-span-2"><div className="text-sm text-[#666]">Address</div><strong>{record.address}</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">Account Preferences</h2>
            <div><div className="text-sm text-[#666]">Account Type</div><strong>{record.accountType}</strong></div>
            <div><div className="text-sm text-[#666]">Investment Preference</div><strong>{record.investmentPreference}</strong></div>
            <div><div className="text-sm text-[#666]">Storage Preference</div><strong>{record.storagePreference}</strong></div>
            <div><div className="text-sm text-[#666]">Custodian Partner</div><strong>{record.custodianPartner}</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">Agreements</h2>
            <div><div className="text-sm text-[#666]">AML/KYC Accepted</div><strong>{record.amlKycAccepted ? "Yes" : "No"}</strong></div>
            <div><div className="text-sm text-[#666]">Custodian Agreement</div><strong>{record.custodianAgreementAccepted ? "Accepted" : "Not accepted"}</strong></div>
            <div><div className="text-sm text-[#666]">Storage Agreement</div><strong>{record.storageAgreementAccepted ? "Accepted" : "Not accepted"}</strong></div>
            <div><div className="text-sm text-[#666]">Service Agreement</div><strong>{record.serviceAgreementAccepted ? "Accepted" : "Not accepted"}</strong></div>
          </div>
        </div>

        <form action={updateRecord} className="panel grid h-fit gap-4 p-5">
          <h2 className="text-xl font-black">Application 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 Application Updates</button>
        </form>
      </div>
    </section>
  );
}
