import Link from "next/link";
import { notFound } from "next/navigation";

import {
  Badge,
  PageHeader,
  Panel,
  ProgressBar,
  StatCard,
} from "@/components/dashboard-ui";
import { PropertyDocumentVault } from "@/components/property-document-vault";
import { PropertyMap } from "@/components/property-map";
import {
  formatCompactCurrency,
  formatCurrency,
  formatDate,
  getComplianceByProperty,
  getMessagesByProperty,
  getPropertyBySlug,
  getPropertyCollectionRate,
  getPropertyOccupancy,
  getResidentsByProperty,
  getWorkOrdersByProperty,
} from "@/lib/property-data-uk";

export default async function PropertyDetailPage({
  params,
}: {
  params: Promise<{ propertyId: string }>;
}) {
  const { propertyId } = await params;
  const property = getPropertyBySlug(propertyId);

  if (!property) {
    notFound();
  }

  const occupancy = getPropertyOccupancy(property);
  const collectionRate = getPropertyCollectionRate(property);
  const residentList = getResidentsByProperty(property.id);
  const orderList = getWorkOrdersByProperty(property.id);
  const complianceList = getComplianceByProperty(property.id);
  const threads = getMessagesByProperty(property.id);

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Property detail"
        title={property.name}
        description={`${property.address}, ${property.city}, ${property.postcode}. ${property.tagline}`}
        actions={
          <Link
            href="/properties"
            className="rounded-full border border-border bg-white/72 px-5 py-3 text-sm font-semibold text-foreground transition hover:border-primary/20"
          >
            Back to properties
          </Link>
        }
      />

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <StatCard
          label="Occupancy"
          value={`${property.occupiedUnits}/${property.units}`}
          hint={`Tracking at ${occupancy.toFixed(1)}% occupied.`}
          change={occupancy > 94 ? "Healthy lettings" : "Needs lettings attention"}
          tone={occupancy > 94 ? "teal" : "amber"}
        />
        <StatCard
          label="Collections"
          value={formatCompactCurrency(property.monthlyCollected)}
          hint={`${formatCurrency(property.arrearsAmount)} outstanding on current ledger.`}
          change={`${collectionRate.toFixed(1)}% collected`}
          tone="amber"
        />
        <StatCard
          label="Tenant score"
          value={`${property.residentScore.toFixed(1)}/5`}
          hint={`${threads.reduce((sum, thread) => sum + thread.unread, 0)} unread tenant messages.`}
          change="Live service signal"
          tone="success"
        />
        <StatCard
          label="Parking and EV"
          value={`${property.permitsIssued}/${property.parkingSpaces}`}
          hint={`${property.evBays} EV bays live · EPC ${property.epcRating} (expires ${formatDate(property.epcExpires)}).`}
          change={property.emissionZone === "None" ? "Local access" : property.emissionZone}
          tone="teal"
        />
      </section>

      <PropertyDocumentVault
        description="Store this property's insurance policy, appliance warranties, certificates, tenancy PDFs, invoices, and review dates in one place."
        initialPropertyId={property.id}
        properties={[property]}
        title={`${property.name} document vault`}
      />

      <section className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
        <Panel
          title="Tenant roster"
          description="Tenancy status, balances, deposits, and communication preferences for this property."
        >
          <div className="space-y-4">
            {residentList.map((resident) => (
              <div
                key={resident.id}
                className="rounded-[22px] border border-border bg-white/72 p-4"
              >
                <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                  <div>
                    <p className="font-semibold text-foreground">{resident.name}</p>
                    <p className="text-sm text-muted">
                      {resident.unit} · Tenancy ends {formatDate(resident.tenancyEnds)}
                    </p>
                    <p className="mt-2 text-sm text-muted">
                      Channel: {resident.preferredChannel} · Right to rent{" "}
                      {resident.rightToRentStatus}
                    </p>
                    <p className="mt-2 text-sm text-muted">
                      Deposit: {formatCurrency(resident.depositAmount)} ·{" "}
                      {resident.depositStatus} ({resident.depositScheme})
                    </p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <Badge tone={resident.balance > 0 ? "amber" : "teal"}>
                      {resident.balance > 0
                        ? `${formatCurrency(resident.balance)} due`
                        : "In good standing"}
                    </Badge>
                    <Badge tone="neutral">{resident.renewalStage}</Badge>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Panel>

        <Panel
          title="Operations pulse"
          description="Top-level operating metrics for a hands-on landlord or small managing agent."
        >
          <div className="space-y-5">
            <div className="rounded-[24px] bg-surface-deep p-5 text-white">
              <p className="font-mono text-xs uppercase tracking-[0.3em] text-white/55">
                Monthly pulse
              </p>
              <dl className="mt-4 grid gap-4 sm:grid-cols-2">
                <div>
                  <dt className="text-sm text-white/60">Average response</dt>
                  <dd className="mt-1 text-2xl font-semibold">
                    {property.avgResponseHours.toFixed(1)}h
                  </dd>
                </div>
                <div>
                  <dt className="text-sm text-white/60">Open work orders</dt>
                  <dd className="mt-1 text-2xl font-semibold">{property.openTickets}</dd>
                </div>
              </dl>
            </div>

            <div className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="font-medium text-foreground">Collection progress</span>
                <span className="text-muted">{collectionRate.toFixed(1)}%</span>
              </div>
              <ProgressBar value={collectionRate} tone="amber" />
            </div>

            <div className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="font-medium text-foreground">Occupancy</span>
                <span className="text-muted">{occupancy.toFixed(1)}%</span>
              </div>
              <ProgressBar value={occupancy} tone="teal" />
            </div>

            <div className="rounded-[22px] border border-border bg-white/72 p-4">
              <p className="font-semibold text-foreground">Next inspection</p>
              <p className="mt-2 text-sm text-muted">{formatDate(property.nextInspection)}</p>
            </div>
          </div>
        </Panel>
      </section>

      <section className="grid gap-6 xl:grid-cols-3">
        <Panel
          title="Live work orders"
          description="Where site teams and contractors are currently spending time."
        >
          <div className="space-y-4">
            {orderList.map((order) => (
              <div
                key={order.id}
                className="rounded-[22px] border border-border bg-white/72 p-4"
              >
                <div className="flex items-center justify-between gap-3">
                  <p className="font-semibold text-foreground">{order.title}</p>
                  <Badge
                    tone={
                      order.priority === "Critical"
                        ? "red"
                        : order.priority === "High"
                          ? "amber"
                          : "neutral"
                    }
                  >
                    {order.priority}
                  </Badge>
                </div>
                <p className="mt-2 text-sm text-muted">
                  {order.unit} · {order.assignedTo} · {order.status}
                </p>
              </div>
            ))}
          </div>
        </Panel>

        <Panel
          title="Compliance schedule"
          description="The items keeping this property inspection-ready."
        >
          <div className="space-y-4">
            {complianceList.map((item) => (
              <div
                key={item.id}
                className="rounded-[22px] border border-border bg-white/72 p-4"
              >
                <div className="flex items-center justify-between gap-3">
                  <p className="font-semibold text-foreground">{item.title}</p>
                  <Badge
                    tone={
                      item.status === "Blocked"
                        ? "red"
                        : item.status === "Due soon"
                          ? "amber"
                          : item.status === "Completed"
                            ? "success"
                            : "teal"
                    }
                  >
                    {item.status}
                  </Badge>
                </div>
                <p className="mt-2 text-sm text-muted">
                  Due {formatDate(item.dueDate)} · {item.owner}
                </p>
              </div>
            ))}
          </div>
        </Panel>

        <Panel
          title="Amenities and location"
          description="Maps, local context, and the services tenants actually notice."
        >
          <div className="space-y-4">
            <div className="rounded-[22px] border border-border bg-white/72 p-4">
              <p className="font-semibold text-foreground">Map</p>
              <p className="mt-2 text-sm text-muted">
                {property.localAuthority} · Council tax band {property.councilTaxBand} ·{" "}
                {property.emissionZone === "None"
                  ? "No low emission zone flagged"
                  : `${property.emissionZone} area`}
              </p>
              <div className="mt-4">
                <PropertyMap
                  title={property.name}
                  lat={property.coordinates.lat}
                  lng={property.coordinates.lng}
                />
              </div>
              <dl className="mt-4 grid gap-3 text-sm text-muted sm:grid-cols-2">
                <div>
                  <dt>Transport score</dt>
                  <dd className="mt-1 font-semibold text-foreground">
                    {property.transportScore}/100
                  </dd>
                </div>
                <div>
                  <dt>Flood risk</dt>
                  <dd className="mt-1 font-semibold text-foreground">{property.floodRisk}</dd>
                </div>
              </dl>
            </div>
            <div className="rounded-[22px] border border-border bg-white/72 p-4">
              <p className="font-semibold text-foreground">Amenities live</p>
              <div className="mt-3 flex flex-wrap gap-2">
                {property.amenities.map((amenity) => (
                  <Badge key={amenity} tone="neutral">
                    {amenity}
                  </Badge>
                ))}
              </div>
            </div>
            <div className="rounded-[22px] border border-border bg-white/72 p-4">
              <p className="font-semibold text-foreground">Parking and EV</p>
              <p className="mt-2 text-sm text-muted">
                {property.permitsIssued} permits issued, {property.evBays} chargers
                live, and guest access routed through the tenant app.
              </p>
            </div>
            {threads.map((thread) => (
              <div
                key={thread.id}
                className="rounded-[22px] border border-border bg-white/72 p-4"
              >
                <div className="flex items-center justify-between gap-3">
                  <p className="font-semibold text-foreground">{thread.title}</p>
                  <Badge tone="amber">{thread.unread} unread</Badge>
                </div>
                <p className="mt-2 text-sm text-muted">{thread.participants}</p>
              </div>
            ))}
            {threads.length === 0 ? (
              <div className="rounded-[22px] border border-dashed border-border bg-white/60 p-6 text-sm text-muted">
                No live tenant conversations for this property right now.
              </div>
            ) : null}
          </div>
        </Panel>
      </section>
    </div>
  );
}
