
import Link from "next/link";

import {
  AlertIcon,
  ArrowUpRightIcon,
  Badge,
  BoltIcon,
  CalendarIcon,
  CarIcon,
  MessageIcon,
  Panel,
  ProgressBar,
  Sparkline,
  StatCard,
  WrenchIcon,
} from "@/components/dashboard-ui";
import { OverviewPropertyFlicker } from "@/components/overview-property-flicker";
import { PropertyCareDashboard } from "@/components/property-care-dashboard";
import { PropertyDocumentVault } from "@/components/property-document-vault";
import { HideableTile } from "@/components/view-customiser";
import { YearlyCheckWheel } from "@/components/yearly-check-wheel";
import {
  actionItems,
  calendarEvents,
  collectionTrend,
  complianceItems,
  formatCompactCurrency,
  formatCurrency,
  formatDate,
  formatDateTime,
  formatPercent,
  getPropertyName,
  messageThreads,
  portfolioSnapshot,
  properties,
  residents,
  serviceModules,
  workOrders,
} from "@/lib/property-data-uk";

const renewalPipeline = residents
  .filter((resident) => resident.status !== "Stable")
  .slice()
  .sort((a, b) => a.tenancyEnds.localeCompare(b.tenancyEnds));

const urgentOrders = workOrders.filter(
  (order) =>
    order.status !== "Resolved" &&
    (order.priority === "Critical" || order.priority === "High"),
);

export function DashboardHome() {
  return (
    <div className="space-y-6">
      <HideableTile
        anchorId="home-care"
        id="overview-home-care-cockpit"
        label="home care bills and checks"
      >
        <PropertyCareDashboard
          complianceItems={complianceItems}
          properties={properties}
          showHeaderMap
        />
      </HideableTile>

      <HideableTile
        anchorId="property-profile"
        id="overview-property-flicker"
        label="property flick-through"
      >
        <OverviewPropertyFlicker
          complianceItems={complianceItems}
          messageThreads={messageThreads}
          properties={properties}
          workOrders={workOrders}
        />
      </HideableTile>

      <HideableTile
        anchorId="property-documents"
        id="overview-property-documents"
        label="property document vault"
      >
        <PropertyDocumentVault
          compact
          description="Keep insurance, warranties, safety certificates, tenancy PDFs, and receipts attached to the correct home."
          properties={properties}
          title="Vault for every property"
        />
      </HideableTile>

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <HideableTile id="overview-occupancy" label="portfolio occupancy tile">
          <StatCard
            label="Portfolio occupancy"
            value={formatPercent(portfolioSnapshot.occupancyRate)}
            hint={`${portfolioSnapshot.occupiedUnits} occupied lettable homes across ${portfolioSnapshot.propertyCount} properties.`}
            change="+1.8 pts vs last month"
            tone="teal"
            icon={<ArrowUpRightIcon />}
          />
        </HideableTile>
        <HideableTile id="overview-rent-collected" label="rent collected tile">
          <StatCard
            label="Rent collected"
            value={formatCompactCurrency(portfolioSnapshot.monthlyCollected)}
            hint={`${formatCurrency(portfolioSnapshot.arrearsAmount)} still outstanding this period.`}
            change={formatPercent(portfolioSnapshot.collectionRate)}
            tone="amber"
            icon={<ArrowUpRightIcon />}
          />
        </HideableTile>
        <HideableTile id="overview-urgent-repairs" label="urgent repairs tile">
          <StatCard
            label="Urgent repairs"
            value={`${urgentOrders.length} live`}
            hint="Critical or high-priority work orders still within the active response window."
            change="SLA focus"
            tone="red"
            icon={<WrenchIcon />}
          />
        </HideableTile>
        <HideableTile id="overview-epc-readiness" label="EPC readiness tile">
          <StatCard
            label="EPC readiness"
            value={formatPercent(portfolioSnapshot.epcCOrAboveRate, 0)}
            hint={`${portfolioSnapshot.epcCOrAboveAssets}/${portfolioSnapshot.propertyCount} properties are EPC C or above.`}
            change={`${portfolioSnapshot.rightToRentGaps} right to rent gaps`}
            tone={portfolioSnapshot.epcCOrAboveRate >= 75 ? "success" : "amber"}
            icon={<AlertIcon />}
          />
        </HideableTile>
      </section>

      <HideableTile id="overview-yearly-check-wheel" label="yearly checks timeframe">
        <YearlyCheckWheel
          complianceItems={complianceItems}
          description="The landlord timeframe bars show gas, electrical, EPC, insurance, fire, legionella, and licence deadlines by urgency."
          properties={properties}
          title="Yearly checks for 10 properties"
        />
      </HideableTile>

      <section className="grid gap-6 xl:grid-cols-[1.25fr_0.95fr]">
        <HideableTile
          id="overview-collection-momentum"
          label="collection and occupancy momentum"
        >
          <Panel
            title="Collection and occupancy momentum"
            description="Monthly rent performance for a small portfolio, with enough context to spot arrears before they snowball."
            action={
              <Link
                href="/finance"
                className="inline-flex items-center gap-2 rounded-full border border-border bg-white/70 px-4 py-2 text-sm font-medium text-foreground transition hover:border-primary/20"
              >
                Open finance <ArrowUpRightIcon className="h-4 w-4" />
              </Link>
            }
          >
            <div className="grid gap-5 lg:grid-cols-[0.9fr_1.1fr]">
              <div className="rounded-[24px] bg-surface-deep p-5 text-white">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="font-mono text-xs uppercase tracking-[0.28em] text-white/55">
                      Rent trend
                    </p>
                    <p className="mt-2 text-3xl font-semibold tracking-tight">
                      {formatCompactCurrency(portfolioSnapshot.monthlyRentRoll)}
                    </p>
                    <p className="mt-2 text-sm leading-6 text-white/70">
                      Scheduled rent roll this month. Collection is tracking at{" "}
                      {formatPercent(portfolioSnapshot.collectionRate)} with arrears
                      concentrated in a few tenants.
                    </p>
                  </div>
                  <Badge tone="teal">Rent on track</Badge>
                </div>
                <div className="mt-5">
                  <Sparkline
                    points={collectionTrend.map((point) => point.collected)}
                    tone="teal"
                  />
                </div>
              </div>

              <div className="space-y-4">
                {collectionTrend.map((point) => {
                  const ratio = (point.collected / point.target) * 100;

                  return (
                    <div key={point.month} className="space-y-2">
                      <div className="flex items-center justify-between text-sm">
                        <span className="font-medium text-foreground">{point.month}</span>
                        <span className="text-muted">
                          {formatCompactCurrency(point.collected)} /{" "}
                          {formatCompactCurrency(point.target)}
                        </span>
                      </div>
                      <ProgressBar value={ratio} tone={ratio > 97 ? "teal" : "amber"} />
                    </div>
                  );
                })}
              </div>
            </div>
          </Panel>
        </HideableTile>

        <HideableTile
          anchorId="today-actions"
          id="overview-action-centre"
          label="action centre"
        >
          <Panel
            title="Action centre"
            description="The landlord tasks that need attention this week."
          >
            <div className="space-y-4">
              {actionItems.map((item) => (
                <article
                  key={item.id}
                  className="rounded-[24px] 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 className="space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <Badge tone={item.tone}>{item.owner}</Badge>
                        <span className="text-xs uppercase tracking-[0.2em] text-muted">
                          Due {formatDate(item.dueDate)}
                        </span>
                      </div>
                      <h3 className="text-base font-semibold text-foreground">
                        {item.title}
                      </h3>
                      <p className="text-sm leading-6 text-muted">{item.detail}</p>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </Panel>
        </HideableTile>
      </section>

      <section className="grid gap-6 xl:grid-cols-3">
        <HideableTile id="overview-renewals" label="tenancy renewals and move-ins">
          <Panel
            title="Tenancy renewals and move-ins"
            description="Tenants who need pricing, approvals, onboarding, or retention work."
          >
            <div className="space-y-4">
              {renewalPipeline.map((resident) => (
                <div
                  key={resident.id}
                  className="flex items-start justify-between gap-3 rounded-[22px] border border-border bg-white/72 p-4"
                >
                  <div>
                    <p className="font-semibold text-foreground">{resident.name}</p>
                    <p className="text-sm text-muted">
                      {resident.unit} at {getPropertyName(resident.propertyId)}
                    </p>
                    <p className="mt-1 text-sm text-muted">
                      Tenancy touchpoint: {formatDate(resident.tenancyEnds)}
                    </p>
                  </div>
                  <Badge tone={resident.balance > 0 ? "amber" : "teal"}>
                    {resident.renewalStage}
                  </Badge>
                </div>
              ))}
            </div>
          </Panel>
        </HideableTile>

        <HideableTile id="overview-repairs-pressure" label="repairs pressure points">
          <Panel
            title="Repairs pressure points"
            description="Repairs with the most tenant experience or property risk attached."
          >
            <div className="space-y-4">
              {urgentOrders.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">
                    <div>
                      <p className="font-semibold text-foreground">{order.title}</p>
                      <p className="text-sm text-muted">
                        {getPropertyName(order.propertyId)} · {order.unit}
                      </p>
                    </div>
                    <Badge tone={order.priority === "Critical" ? "red" : "amber"}>
                      {order.priority}
                    </Badge>
                  </div>
                  <p className="mt-2 text-sm text-muted">
                    Assigned to {order.assignedTo} and last updated{" "}
                    {formatDateTime(order.createdAt)}.
                  </p>
                </div>
              ))}
            </div>
          </Panel>
        </HideableTile>

        <HideableTile id="overview-tenant-pulse" label="tenant experience pulse">
          <Panel
            title="Tenant experience pulse"
            description="Live signal from your inbox, tenant messages, and phone notes."
          >
            <div className="space-y-4">
              {messageThreads.slice(0, 4).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">
                    <div>
                      <p className="font-semibold text-foreground">{thread.title}</p>
                      <p className="text-sm text-muted">{thread.participants}</p>
                    </div>
                    <Badge
                      tone={
                        thread.sentiment === "Needs attention"
                          ? "red"
                          : thread.sentiment === "Positive"
                            ? "success"
                            : "neutral"
                      }
                    >
                      {thread.unread} unread
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          </Panel>
        </HideableTile>
      </section>

      <section className="grid gap-6 lg:grid-cols-[1.05fr_0.95fr]">
        <HideableTile id="overview-calendar" label="landlord calendar">
          <Panel
            title="Landlord calendar"
            description="A simple run sheet for inspections, renewals, repairs, and certificate visits."
          >
            <div className="space-y-4">
              {calendarEvents.map((event) => (
                <div
                  key={event.id}
                  className="flex items-start gap-4 rounded-[22px] border border-border bg-white/72 p-4"
                >
                  <div className="rounded-2xl bg-primary/10 p-3 text-primary">
                    <CalendarIcon />
                  </div>
                  <div className="flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="font-semibold text-foreground">{event.title}</p>
                      <Badge tone="neutral">{event.category}</Badge>
                    </div>
                    <p className="mt-1 text-sm text-muted">
                      {formatDate(event.date)} · {event.owner}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </Panel>
        </HideableTile>

        <HideableTile id="overview-super-app" label="landlord admin helpers">
          <Panel
            title="Landlord admin helpers"
            description="The admin layers that save time when you manage 7-15 properties yourself."
          >
            <div className="space-y-4">
              {serviceModules.map((module, index) => (
                <div
                  key={module.id}
                  className="rounded-[24px] border border-border bg-white/72 p-4"
                >
                  <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-3">
                      <span className="rounded-2xl bg-primary/10 p-3 text-primary">
                        {index % 2 === 0 ? <CarIcon /> : <BoltIcon />}
                      </span>
                      <div>
                        <p className="font-semibold text-foreground">{module.title}</p>
                        <p className="text-sm text-muted">{module.adoption}</p>
                      </div>
                    </div>
                    <Badge tone="teal">Live</Badge>
                  </div>
                  <p className="mt-3 text-sm leading-6 text-muted">
                    {module.description}
                  </p>
                </div>
              ))}
            </div>
          </Panel>
        </HideableTile>
      </section>

      <section className="grid gap-6 xl:grid-cols-[0.95fr_1.05fr]">
        <HideableTile id="overview-compliance-radar" label="compliance radar">
          <Panel
            title="Compliance radar"
            description="Upcoming tasks (CP12, EICR, EPC and more) that keep each property safe and documented."
          >
            <div className="space-y-4">
              {complianceItems
                .filter((item) => item.status !== "Completed")
                .slice(0, 5)
                .map((item) => (
                  <div
                    key={item.id}
                    className="flex items-start justify-between gap-3 rounded-[22px] border border-border bg-white/72 p-4"
                  >
                    <div>
                      <p className="font-semibold text-foreground">{item.title}</p>
                      <p className="text-sm text-muted">
                        {getPropertyName(item.propertyId)} · {item.owner}
                      </p>
                      <p className="mt-1 text-sm text-muted">
                        Due {formatDate(item.dueDate)}
                      </p>
                    </div>
                    <Badge
                      tone={
                        item.status === "Blocked"
                          ? "red"
                          : item.status === "Due soon"
                            ? "amber"
                            : "teal"
                      }
                    >
                      {item.status}
                    </Badge>
                  </div>
                ))}
            </div>
          </Panel>
        </HideableTile>

        <HideableTile id="overview-track-list" label="what PropertyPilot is built to track">
          <Panel
            title="What PropertyPilot is built to track"
            description="Core records small landlords usually end up juggling across spreadsheets, inboxes, and contractor notes."
          >
            <div className="grid gap-4 md:grid-cols-2">
              {[
                "Portfolio and unit occupancy",
                "Tenancies, renewals, and move-ins",
                "Rent roll, arrears, and budgets",
                "Work orders and contractor SLAs",
                "Compliance, insurance, and certifications",
                "Tenant messages and announcements",
                "Parking permits, access, and EV charging",
                "Deposits, right to rent, and document packs",
              ].map((item) => (
                <div
                  key={item}
                  className="flex items-center gap-3 rounded-[22px] border border-border bg-white/72 p-4"
                >
                  <span className="rounded-2xl bg-primary-soft p-3 text-primary">
                    <MessageIcon />
                  </span>
                  <p className="text-sm font-medium text-foreground">{item}</p>
                </div>
              ))}
            </div>
          </Panel>
        </HideableTile>
      </section>
    </div>
  );
}
