import { ArrowLeft, BadgeCheck, Clock, Eye, Gem, Heart, ShieldCheck } from 'lucide-react'
import { Link, useParams } from 'react-router-dom'

import { AppShell } from '@/components/layout/AppShell'
import { Alert, Badge, Button, Card, EmptyState, PageSpinner } from '@/components/ui'
import { useDomainListing } from '@/features/marketplace/queries'
import { ApiError } from '@/lib/api'

/**
 * The listing detail page.
 *
 * Indexable and addressed by the name itself, which is why the route is
 * `/domain/example.com` rather than an opaque id — that URL shape was fixed
 * before anything indexed it and is not something to change later.
 *
 * The buy and offer actions are intentionally inert here. Checkout, payment and
 * negotiation are later phases, and a button that looks live but silently does
 * nothing is worse on a marketplace than one that says what it is waiting for.
 */
export function DomainDetailPage() {
  const { domain: name } = useParams<{ domain: string }>()
  const { data: listing, isLoading, isError, error } = useDomainListing(name)

  const notFound = error instanceof ApiError && error.status === 404

  return (
    <AppShell>
      <div className="container-page py-8 lg:py-12">
        <Link
          to="/domains"
          className="inline-flex items-center gap-1.5 text-sm text-text-secondary hover:text-text-primary"
        >
          <ArrowLeft aria-hidden className="size-4" />
          Back to browse
        </Link>

        {isLoading ? (
          <PageSpinner label="Loading domain" />
        ) : notFound ? (
          <EmptyState
            className="mt-8"
            icon={<ShieldCheck className="size-5" />}
            title="This domain is not for sale"
            description={`${name ?? 'That name'} is not currently listed on Domainsansar. It may have sold, been withdrawn, or never been listed.`}
            action={
              <Link to="/domains">
                <Button variant="secondary">Browse other domains</Button>
              </Link>
            }
          />
        ) : isError || listing === undefined ? (
          <Alert tone="error" title="Could not load this domain" className="mt-8">
            Refresh the page to try again.
          </Alert>
        ) : (
          <div className="mt-6 grid gap-6 lg:grid-cols-[minmax(0,1fr)_20rem]">
            {/* ---------------------------------------------------------- */}
            {/* The name and its terms                                     */}
            {/* ---------------------------------------------------------- */}
            <div>
              <div className="flex flex-wrap items-center gap-2">
                {listing.domain.ownership_verified && (
                  <Badge tone="positive" icon={<BadgeCheck aria-hidden className="size-3.5" />}>
                    Ownership verified
                  </Badge>
                )}
                {listing.is_featured && (
                  <Badge tone="premium" icon={<Gem aria-hidden className="size-3.5" />}>
                    Featured
                  </Badge>
                )}
                {listing.status === 'under_offer' && (
                  <Badge tone="caution">{listing.status_label}</Badge>
                )}
              </div>

              <h1 className="mt-4 text-3xl font-semibold tracking-[-0.02em] break-words text-text-primary sm:text-4xl">
                <span>{listing.domain.label}</span>
                <span className="text-text-muted">{listing.domain.tld_display}</span>
              </h1>

              {listing.headline !== listing.domain.name && (
                <p className="mt-2 text-lg text-text-secondary">{listing.headline}</p>
              )}

              {listing.description !== null && (
                <p className="mt-5 whitespace-pre-line text-text-secondary">{listing.description}</p>
              )}

              <dl className="mt-8 grid grid-cols-2 gap-x-6 gap-y-4 border-t border-border-subtle pt-6 sm:grid-cols-4">
                <Fact label="Length" value={`${listing.domain.length} characters`} />
                <Fact label="Extension" value={listing.domain.tld_display} />
                <Fact label="Sale type" value={listing.type_label} />
                <Fact
                  label="Characters"
                  value={
                    [
                      listing.domain.has_hyphen ? 'hyphen' : null,
                      listing.domain.has_digit ? 'numbers' : null,
                    ]
                      .filter((part) => part !== null)
                      .join(', ') || 'letters only'
                  }
                />
              </dl>

              {listing.category !== undefined && listing.category !== null && (
                <p className="mt-6 text-sm text-text-secondary">
                  Listed in{' '}
                  <Link
                    to={`/domains?category=${listing.category.slug}`}
                    className="text-text-accent underline decoration-border-strong underline-offset-4"
                  >
                    {listing.category.name}
                  </Link>
                </p>
              )}
            </div>

            {/* ---------------------------------------------------------- */}
            {/* Price, actions and the seller                              */}
            {/* ---------------------------------------------------------- */}
            <div className="flex flex-col gap-4">
              <Card elevation="raised" className="p-5">
                {listing.price !== null ? (
                  <>
                    <p className="text-sm text-text-secondary">Asking price</p>
                    <p data-numeric className="mt-1 text-3xl font-semibold text-text-primary">
                      {listing.price.formatted}
                    </p>
                  </>
                ) : (
                  <>
                    <p className="text-sm text-text-secondary">Price</p>
                    <p className="mt-1 text-xl font-medium text-text-accent">
                      Open to offers
                    </p>
                  </>
                )}

                <div className="mt-5 flex flex-col gap-2.5">
                  {listing.is_buy_now && (
                    <Button size="lg" fullWidth disabled>
                      Buy now
                    </Button>
                  )}
                  {listing.accepts_offers && (
                    <Button
                      size="lg"
                      fullWidth
                      variant={listing.is_buy_now ? 'secondary' : 'primary'}
                      disabled
                    >
                      Make an offer
                    </Button>
                  )}
                  <Button
                    variant="ghost"
                    fullWidth
                    disabled
                    leadingIcon={<Heart aria-hidden className="size-4" />}
                  >
                    Watch this domain
                  </Button>
                </div>

                {/* Said plainly rather than leaving three dead buttons
                    unexplained. */}
                <p className="mt-4 border-t border-border-subtle pt-4 text-xs text-text-muted">
                  Checkout and offers arrive with the payments phase. Nothing is charged and no
                  offer is sent from this page yet.
                </p>
              </Card>

              {/* Only while the lock is still in force -- see DomainCard. */}
              {listing.domain.is_transfer_locked &&
                listing.domain.transfer_available_from !== null && (
                <Card className="p-5">
                  <p className="inline-flex items-center gap-2 text-sm font-medium text-text-primary">
                    <Clock aria-hidden className="size-4 text-text-muted" />
                    Transfer window
                  </p>
                  <p className="mt-2 text-sm text-text-secondary">
                    This name is inside its registrar lock until{' '}
                    {new Date(listing.domain.transfer_available_from).toLocaleDateString()}. A sale
                    can be agreed now, but the handover cannot complete before then.
                  </p>
                </Card>
              )}

              <Card className="p-5">
                <p className="text-sm font-medium text-text-primary">Seller</p>

                <Link
                  to={`/seller/${listing.seller.handle}`}
                  className="mt-2 block text-base font-semibold text-text-accent"
                >
                  {listing.seller.display_name}
                </Link>

                <p className="mt-1 text-xs text-text-muted">{listing.seller.tier_label}</p>

                {listing.seller.badges.length > 0 && (
                  <div className="mt-3 flex flex-wrap gap-1.5">
                    {listing.seller.badges.map((badge) => (
                      <Badge key={badge.type} tone="neutral">
                        {badge.label}
                      </Badge>
                    ))}
                  </div>
                )}

                <dl className="mt-4 space-y-2 border-t border-border-subtle pt-4 text-sm">
                  <div className="flex justify-between gap-3">
                    <dt className="text-text-secondary">Completed sales</dt>
                    <dd data-numeric className="text-text-primary">
                      {listing.seller.completed_sales_count}
                    </dd>
                  </div>
                  {listing.seller.rating_count > 0 && (
                    <div className="flex justify-between gap-3">
                      <dt className="text-text-secondary">Rating</dt>
                      <dd data-numeric className="text-text-primary">
                        {listing.seller.rating_average.toFixed(1)} ({listing.seller.rating_count})
                      </dd>
                    </div>
                  )}
                </dl>
              </Card>

              <p className="inline-flex items-center gap-1.5 text-xs text-text-muted">
                <Eye aria-hidden className="size-3.5" />
                <span data-numeric>{listing.views_count}</span> views
              </p>
            </div>
          </div>
        )}
      </div>
    </AppShell>
  )
}

function Fact({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-xs text-text-muted">{label}</dt>
      <dd className="mt-1 text-sm font-medium text-text-primary">{value}</dd>
    </div>
  )
}
