import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { formatDateTime } from "@/lib/format";
import { parseStringArray } from "@/lib/serialize";
import { updateRepairBooking } from "@/app/admin/actions";
import {
  REPAIR_STATUSES,
  REPAIR_STATUS_META,
  SERVICE_MODE_META,
  type RepairStatus,
  type ServiceMode,
} from "@/lib/constants";

export const dynamic = "force-dynamic";

export default async function AdminRepairDetail({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const [booking, technicians] = await Promise.all([
    prisma.repairBooking.findUnique({
      where: { id },
      include: { service: true, technician: true },
    }),
    prisma.technician.findMany({ orderBy: { sortOrder: "asc" } }),
  ]);
  if (!booking) notFound();

  const photos = parseStringArray(booking.photos);
  const waHref = `https://wa.me/${booking.customerPhone.replace(/[^\d]/g, "")}?text=${encodeURIComponent(
    `Hi ${booking.customerName}, regarding your repair booking ${booking.bookingNumber}…`,
  )}`;

  return (
    <div className="space-y-4">
      <a href="/admin/repairs" className="text-sm text-slate-400 hover:text-brand-600">
        ← Back to repairs
      </a>

      <div className="grid gap-5 lg:grid-cols-[1fr_320px]">
        <div className="space-y-4">
          <div className="rounded-xl border border-slate-200 bg-white p-5">
            <div className="flex items-start justify-between">
              <div>
                <h2 className="text-lg font-bold text-slate-900">
                  {booking.bookingNumber}
                </h2>
                <p className="text-sm text-slate-500">
                  {booking.service?.name ?? "General / other"} •{" "}
                  {formatDateTime(booking.createdAt)}
                </p>
              </div>
              <span
                className={`rounded-full px-2.5 py-0.5 text-xs font-semibold ${
                  REPAIR_STATUS_META[booking.status as RepairStatus]?.className ??
                  "bg-slate-100 text-slate-600"
                }`}
              >
                {REPAIR_STATUS_META[booking.status as RepairStatus]?.label ??
                  booking.status}
              </span>
            </div>

            <dl className="mt-4 grid gap-3 text-sm sm:grid-cols-2">
              <div>
                <dt className="text-slate-400">Customer</dt>
                <dd className="font-medium text-slate-700">{booking.customerName}</dd>
              </div>
              <div>
                <dt className="text-slate-400">Phone</dt>
                <dd className="font-medium text-slate-700">{booking.customerPhone}</dd>
              </div>
              {booking.customerEmail ? (
                <div>
                  <dt className="text-slate-400">Email</dt>
                  <dd className="font-medium text-slate-700">{booking.customerEmail}</dd>
                </div>
              ) : null}
              <div>
                <dt className="text-slate-400">Device</dt>
                <dd className="font-medium text-slate-700">
                  {[booking.deviceType, booking.brand, booking.model]
                    .filter(Boolean)
                    .join(" • ") || "—"}
                </dd>
              </div>
              <div>
                <dt className="text-slate-400">Service mode</dt>
                <dd className="font-medium text-slate-700">
                  {SERVICE_MODE_META[booking.serviceMode as ServiceMode]?.label ??
                    booking.serviceMode}
                </dd>
              </div>
              <div>
                <dt className="text-slate-400">Preferred</dt>
                <dd className="font-medium text-slate-700">
                  {[booking.preferredDate, booking.preferredTime]
                    .filter(Boolean)
                    .join(", ") || "Any time"}
                </dd>
              </div>
            </dl>

            {booking.serviceMode === "HOME_VISIT" && booking.address ? (
              <div className="mt-4">
                <p className="text-slate-400">Visit address</p>
                <p className="mt-1 whitespace-pre-line text-sm text-slate-700">
                  {booking.address}
                </p>
              </div>
            ) : null}

            <div className="mt-4">
              <p className="text-slate-400">Problem described</p>
              <p className="mt-1 whitespace-pre-line text-sm text-slate-700">
                {booking.problem || "—"}
              </p>
            </div>

            <a
              href={waHref}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-4 inline-flex items-center gap-2 rounded-lg border border-[#25D366] px-4 py-2 text-sm font-semibold text-[#1a8f4a] hover:bg-[#25D366]/10"
            >
              💬 Contact customer on WhatsApp
            </a>
          </div>

          {photos.length > 0 ? (
            <div className="rounded-xl border border-slate-200 bg-white p-5">
              <h3 className="text-sm font-bold text-slate-700">Photos</h3>
              <div className="mt-3 grid grid-cols-3 gap-3 sm:grid-cols-4">
                {photos.map((src) => (
                  <a
                    key={src}
                    href={src}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block aspect-square overflow-hidden rounded-lg border border-slate-200"
                  >
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={src} alt="" className="h-full w-full object-cover" />
                  </a>
                ))}
              </div>
            </div>
          ) : null}
        </div>

        <div className="lg:sticky lg:top-6 lg:self-start">
          <form
            action={updateRepairBooking}
            className="rounded-xl border border-slate-200 bg-white p-5"
          >
            <input type="hidden" name="id" value={booking.id} />
            <h3 className="text-sm font-bold text-slate-700">Manage booking</h3>

            <label className="mt-3 block">
              <span className="text-sm font-medium text-slate-600">Assign technician</span>
              <select
                name="technicianId"
                defaultValue={booking.technicianId ?? ""}
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              >
                <option value="">Unassigned</option>
                {technicians.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.name}
                    {t.specialization ? ` — ${t.specialization}` : ""}
                  </option>
                ))}
              </select>
            </label>

            <label className="mt-3 block">
              <span className="text-sm font-medium text-slate-600">
                Quoted cost (₹)
              </span>
              <input
                type="number"
                name="quotedCost"
                min={0}
                defaultValue={booking.quotedCost ?? ""}
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              />
            </label>

            <label className="mt-3 block">
              <span className="text-sm font-medium text-slate-600">Status</span>
              <select
                name="status"
                defaultValue={booking.status}
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              >
                {REPAIR_STATUSES.map((s) => (
                  <option key={s} value={s}>
                    {REPAIR_STATUS_META[s].label}
                  </option>
                ))}
              </select>
            </label>

            <label className="mt-3 block">
              <span className="text-sm font-medium text-slate-600">Internal notes</span>
              <textarea
                name="adminNotes"
                rows={4}
                defaultValue={booking.adminNotes ?? ""}
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              />
            </label>

            <button className="mt-4 w-full rounded-lg bg-brand-600 py-2.5 text-sm font-semibold text-white hover:bg-brand-700">
              Save
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
