"use client"

import { use, useEffect, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { PageReveal } from "@/components/animations"
import { Navbar } from "@/components/layout/navbar"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
import { getBookingById, formatMoney } from "@/lib/booking-storage"
import type { BookingRecord } from "@/lib/booking-storage"
import {
  formatScheduleSubtitle,
  formatBookedTimestamp,
  BOOKING_STATUS_UI,
} from "@/lib/booking-display"
import { vendors } from "@/lib/mock-data"
import {
  ArrowLeft,
  Calendar,
  Clock,
  Copy,
  Check,
  Receipt,
  QrCode,
  FileText,
  DollarSign,
  Package,
  Store,
  ExternalLink,
} from "lucide-react"
import { cn } from "@/lib/utils"

function downloadReceiptText(booking: BookingRecord) {
  const totalTax = booking.taxState + booking.taxCounty + booking.taxCity
  const lines = [
    `BeachLyfe — Booking receipt`,
    `Confirmation: ${booking.confirmationCode}`,
    `Item: ${booking.itemName} × ${booking.quantity}`,
    `Date: ${booking.date} | Time: ${booking.timeRange || booking.time}`,
    ``,
    `Subtotal: ${formatMoney(booking.subtotal)}`,
    ...(booking.discount > 0 ? [`Discount: -${formatMoney(booking.discount)}`] : []),
    `Tax (state): ${formatMoney(booking.taxState)}`,
    `Tax (county): ${formatMoney(booking.taxCounty)}`,
    `Tax (city): ${formatMoney(booking.taxCity)}`,
    `Tax total: ${formatMoney(totalTax)}`,
    ...(booking.tip > 0 ? [`Tip: ${formatMoney(booking.tip)}`] : []),
    `Total: ${formatMoney(booking.total)}`,
    ``,
    `Booked on ${new Date(booking.createdAt).toLocaleString()}`,
  ]
  const blob = new Blob([lines.join("\n")], { type: "text/plain" })
  const url = URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = `beachlyfe-receipt-${booking.confirmationCode}.txt`
  a.click()
  URL.revokeObjectURL(url)
}

export function BookingDetailClient({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const router = useRouter()
  const [copied, setCopied] = useState(false)
  const [booking, setBooking] = useState<BookingRecord | null | undefined>(undefined)

  useEffect(() => {
    setBooking(getBookingById(id) ?? null)
  }, [id])
  const vendor = booking ? vendors.find((v) => v.id === booking.vendorId) : null
  const status = (booking?.status ?? "scheduled") as keyof typeof BOOKING_STATUS_UI
  const ui = BOOKING_STATUS_UI[status] ?? BOOKING_STATUS_UI.scheduled
  const totalTax = booking ? booking.taxState + booking.taxCounty + booking.taxCity : 0

  const copyCode = () => {
    if (!booking) return
    navigator.clipboard.writeText(booking.confirmationCode).then(() => {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    })
  }

  if (booking === undefined) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <div className="flex flex-col items-center justify-center py-24 gap-3">
          <div className="h-10 w-10 animate-spin rounded-full border-2 border-primary border-t-transparent" />
          <p className="text-sm text-muted-foreground">Loading booking…</p>
        </div>
      </div>
    )
  }

  if (!booking) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <PageReveal className="content-80 px-4 py-16 text-center">
          <Package className="mx-auto h-12 w-12 text-muted-foreground/50 mb-4" />
          <h1 className="text-2xl font-bold text-foreground mb-2">Booking not found</h1>
          <p className="text-muted-foreground mb-8 max-w-md mx-auto">
            This reservation may have been removed or the link is incorrect.
          </p>
          <Button asChild>
            <Link href="/bookings">Back to My Bookings</Link>
          </Button>
        </PageReveal>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <div className="relative">
        <div className="pointer-events-none absolute inset-x-0 top-0 h-52 bg-gradient-to-b from-[var(--beach-cyan)]/15 via-transparent to-background" />
        <div className="pointer-events-none absolute inset-x-0 top-0 h-36 bg-[radial-gradient(ellipse_80%_80%_at_50%_-20%,var(--beach-cyan)_0%,transparent_55%)] opacity-50" />

        <PageReveal className="content-80 relative px-4 sm:px-6 lg:px-8 pb-16 pt-6">
          <Button
            variant="ghost"
            size="sm"
            className="mb-6 -ml-2 gap-1 text-muted-foreground hover:text-foreground"
            onClick={() => router.push("/bookings")}
          >
            <ArrowLeft className="h-4 w-4" />
            My bookings
          </Button>

          <div className="mx-auto max-w-3xl space-y-6">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p className="text-xs font-semibold uppercase tracking-widest text-primary/90">Reservation</p>
                <h1 className="mt-1 text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
                  {booking.itemName}
                </h1>
              </div>
              <span
                className={cn(
                  "inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold",
                  ui.chipClass
                )}
              >
                {ui.label}
              </span>
            </div>

            <Card className="overflow-hidden rounded-2xl border border-border/80 shadow-lg shadow-black/[0.04]">
              <div className="relative h-36 sm:h-44 bg-gradient-to-br from-[var(--beach-blue)]/90 via-[var(--beach-cyan)]/80 to-[var(--beach-gold)]/50">
                <div className="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg%20width%3D%2260%22%20height%3D%2260%22%20viewBox%3D%220%200%2060%2060%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cg%20fill%3D%22none%22%20fill-rule%3D%22evenodd%22%3E%3Cg%20fill%3D%22%23ffffff%22%20fill-opacity%3D%220.08%22%3E%3Cpath%20d%3D%22M36%2034v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6%2034v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6%204V0H4v4H0v2h4v4h2V6h4V4H6z%22%2F%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E')] opacity-60" />
                <div className="absolute bottom-4 left-5 right-5 flex items-end justify-between gap-4 text-white">
                  <div>
                    <p className="text-xs font-medium uppercase tracking-wider text-white/80">Confirmation</p>
                    <p className="font-mono text-xl font-bold tracking-wide sm:text-2xl">{booking.confirmationCode}</p>
                  </div>
                  <Button
                    type="button"
                    size="sm"
                    variant="secondary"
                    className="shrink-0 bg-white/20 text-white backdrop-blur-sm hover:bg-white/30 border-0"
                    onClick={copyCode}
                  >
                    {copied ? (
                      <>
                        <Check className="mr-1.5 h-4 w-4" />
                        Copied
                      </>
                    ) : (
                      <>
                        <Copy className="mr-1.5 h-4 w-4" />
                        Copy
                      </>
                    )}
                  </Button>
                </div>
              </div>

              <div className="space-y-5 p-5 sm:p-8">
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="flex gap-3 rounded-xl border border-border/60 bg-muted/30 p-4">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
                      <Calendar className="h-5 w-5" />
                    </div>
                    <div>
                      <p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">When</p>
                      <p className="mt-0.5 text-sm font-medium leading-snug text-foreground">
                        {formatScheduleSubtitle(booking)}
                      </p>
                    </div>
                  </div>
                  <div className="flex gap-3 rounded-xl border border-border/60 bg-muted/30 p-4">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
                      <Clock className="h-5 w-5" />
                    </div>
                    <div>
                      <p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Booked</p>
                      <p className="mt-0.5 text-sm font-medium text-foreground">{formatBookedTimestamp(booking.createdAt)}</p>
                    </div>
                  </div>
                </div>

                {vendor && (
                  <Link
                    href={`/vendor/${vendor.id}`}
                    className="flex items-center gap-4 rounded-xl border border-border/60 p-4 transition-colors hover:bg-muted/40"
                  >
                    <div className="relative h-14 w-14 shrink-0 overflow-hidden rounded-xl border border-border/50 bg-muted">
                      <Image src={vendor.image} alt="" fill className="object-cover" sizes="56px" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Vendor</p>
                      <p className="font-semibold text-foreground">{vendor.name}</p>
                      <p className="mt-0.5 flex items-center gap-1 text-sm text-primary">
                        <Store className="h-3.5 w-3.5" />
                        View profile
                      </p>
                    </div>
                    <ExternalLink className="h-4 w-4 shrink-0 text-muted-foreground" />
                  </Link>
                )}

                <div className="flex flex-wrap gap-2">
                  <Button asChild variant="outline" size="sm" className="rounded-full">
                    <Link href={`/item/${booking.itemId}`}>
                      <Package className="mr-2 h-4 w-4" />
                      View listing
                    </Link>
                  </Button>
                  {booking.status === "completed" && (
                    <Button variant="outline" size="sm" className="rounded-full" onClick={() => downloadReceiptText(booking)}>
                      <Receipt className="mr-2 h-4 w-4" />
                      Download receipt
                    </Button>
                  )}
                </div>

                <Separator />

                <div>
                  <div className="mb-3 flex items-center gap-2">
                    <Receipt className="h-4 w-4 text-muted-foreground" />
                    <h2 className="text-sm font-semibold text-foreground">Payment summary</h2>
                  </div>
                  <div className="rounded-xl border border-border/70 bg-muted/20 p-4 sm:p-5">
                    <dl className="space-y-2.5 text-sm">
                      <div className="flex justify-between gap-4">
                        <dt className="text-muted-foreground">Subtotal</dt>
                        <dd className="tabular-nums font-medium">{formatMoney(booking.subtotal)}</dd>
                      </div>
                      {booking.discount > 0 && (
                        <div className="flex justify-between gap-4 text-emerald-700 dark:text-emerald-400">
                          <dt>Discount</dt>
                          <dd className="tabular-nums">−{formatMoney(booking.discount)}</dd>
                        </div>
                      )}
                      <div className="flex justify-between gap-4">
                        <dt className="text-muted-foreground">Tax (state, county & city)</dt>
                        <dd className="tabular-nums">{formatMoney(totalTax)}</dd>
                      </div>
                      {booking.tip > 0 && (
                        <div className="flex justify-between gap-4">
                          <dt className="flex items-center gap-1 text-muted-foreground">
                            <DollarSign className="h-3.5 w-3.5" />
                            Tip
                          </dt>
                          <dd className="tabular-nums">{formatMoney(booking.tip)}</dd>
                        </div>
                      )}
                      <Separator className="my-2" />
                      <div className="flex justify-between gap-4 pt-1">
                        <dt className="text-base font-semibold text-foreground">Total paid</dt>
                        <dd className="text-lg font-bold tabular-nums text-foreground">{formatMoney(booking.total)}</dd>
                      </div>
                    </dl>
                  </div>
                </div>

                {booking.waiverSignerName && (
                  <div className="rounded-xl border border-border/60 bg-background p-4">
                    <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold">
                      <FileText className="h-4 w-4 text-muted-foreground" />
                      Waiver on file
                    </h3>
                    <p className="text-sm text-muted-foreground">
                      Signed by {booking.waiverSignerName}
                      {booking.waiverSignedAt && (
                        <> · {new Date(booking.waiverSignedAt).toLocaleDateString(undefined, { dateStyle: "long" })}</>
                      )}
                    </p>
                  </div>
                )}

                {booking.redemptionQr && (
                  <div className="rounded-xl border border-dashed border-primary/30 bg-primary/[0.03] p-5">
                    <p className="mb-3 flex items-center gap-2 text-sm font-medium text-foreground">
                      <QrCode className="h-4 w-4 text-primary" />
                      Show at check-in
                    </p>
                    <div className="inline-flex items-center gap-2 rounded-lg bg-muted/80 px-4 py-3 font-mono text-sm">
                      {booking.redemptionQr}
                    </div>
                    <p className="mt-3 text-xs text-muted-foreground">
                      Present this code to the vendor to redeem your booking.
                    </p>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </PageReveal>
      </div>
    </div>
  )
}
