import {
  Badge,
  PageHeader,
  Panel,
  ProgressBar,
  Sparkline,
  StatCard,
} from "@/components/dashboard-ui";
import { PropertyCareDashboard } from "@/components/property-care-dashboard";
import { YearlyCheckWheel } from "@/components/yearly-check-wheel";
import {
  budgetLines,
  collectionTrend,
  complianceItems,
  formatCompactCurrency,
  formatCurrency,
  formatPercent,
  getPropertyName,
  portfolioSnapshot,
  properties,
  residents,
} from "@/lib/property-data-uk";

const delinquentResidents = residents.filter((resident) => resident.balance > 0);
const monthlyRunningCosts = budgetLines.reduce((sum, line) => sum + line.actual, 0);
const cashAfterCosts = portfolioSnapshot.monthlyCollected - monthlyRunningCosts;

export default function FinancePage() {
  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Finance"
        title="Bills, rent, and home cashflow"
        description="A smaller-portfolio finance view for homeowners and landlords managing around 7-15 homes: electric bills, council tax, insurance, rent coming in, arrears to chase, repairs, and check costs."
      />

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <StatCard
          label="Rent in this month"
          value={formatCompactCurrency(portfolioSnapshot.monthlyCollected)}
          hint={`${formatCompactCurrency(portfolioSnapshot.monthlyRentRoll)} expected across ${portfolioSnapshot.propertyCount} properties.`}
          change={formatPercent(portfolioSnapshot.collectionRate)}
          tone="teal"
        />
        <StatCard
          label="Arrears to chase"
          value={formatCompactCurrency(portfolioSnapshot.arrearsAmount)}
          hint={`${delinquentResidents.length} tenants need a payment nudge or plan.`}
          change="Watch closely"
          tone="amber"
        />
        <StatCard
          label="Bills and repairs"
          value={formatCompactCurrency(monthlyRunningCosts)}
          hint="Month-to-date landlord costs: repairs, service charges, insurance, and certificates."
          change="Cost tracking"
          tone="neutral"
        />
        <StatCard
          label="Cash after costs"
          value={formatCompactCurrency(cashAfterCosts)}
          hint="Simple cashflow after this month's tracked bills and repairs."
          change={cashAfterCosts < 0 ? "Expense-heavy month" : "Positive month"}
          tone={cashAfterCosts < 0 ? "red" : "success"}
        />
      </section>

      <PropertyCareDashboard
        complianceItems={complianceItems}
        defaultKind="bill"
        description="Focus on electric bills, gas payments, council tax, insurance renewals, service charges, and homeowner costs. Use the plus button to add the exact dates and amounts you need reminding about."
        properties={properties}
        title="Bill reminders by property"
      />

      <YearlyCheckWheel
        className="border-y border-border py-6"
        complianceItems={complianceItems}
        description="Use the timeframe bars to see which annual certificates may hit cashflow soon: gas, EICR, EPC, insurance, licences, and fire checks."
        properties={properties}
        title="Annual checks cash calendar"
      />

      <section className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
        <Panel
          title="Collection trend"
          description="How rent collection is pacing against expected rent over the last six months."
        >
          <div className="grid gap-5 lg:grid-cols-[0.88fr_1.12fr]">
            <div className="rounded-[24px] bg-surface-deep p-5 text-white">
              <p className="font-mono text-xs uppercase tracking-[0.28em] text-white/55">
                Collection pace
              </p>
              <p className="mt-2 text-3xl font-semibold tracking-tight">
                {formatPercent(portfolioSnapshot.collectionRate)}
              </p>
              <p className="mt-2 text-sm leading-6 text-white/70">
                May is partly collected, with arrears concentrated in a small number
                of tenants rather than spread across every property.
              </p>
              <div className="mt-5">
                <Sparkline
                  points={collectionTrend.map((point) => point.collected)}
                  tone="amber"
                />
              </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>

        <Panel
          title="Budget vs actual"
          description="Where landlord costs are under or over the monthly plan."
        >
          <div className="space-y-4">
            {budgetLines.map((line) => {
              const variance = line.actual - line.budget;
              const ratio = (line.actual / line.budget) * 100;

              return (
                <div
                  key={line.name}
                  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">{line.name}</p>
                    <Badge tone={variance > 0 ? "amber" : "success"}>
                      {variance > 0 ? "+" : ""}
                      {formatCurrency(variance)}
                    </Badge>
                  </div>
                  <p className="mt-2 text-sm text-muted">
                    Budget {formatCurrency(line.budget)} · Actual {formatCurrency(line.actual)}
                  </p>
                  <div className="mt-3">
                    <ProgressBar value={ratio} tone={variance > 0 ? "amber" : "teal"} />
                  </div>
                </div>
              );
            })}
          </div>
        </Panel>
      </section>

      <section className="grid gap-6 xl:grid-cols-[0.95fr_1.05fr]">
        <Panel
          title="Delinquency watchlist"
          description="Tenants who need a clear rent nudge or payment-plan conversation."
        >
          <div className="space-y-4">
            {delinquentResidents.map((resident) => (
              <div
                key={resident.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">{resident.name}</p>
                    <p className="text-sm text-muted">
                      {getPropertyName(resident.propertyId)} · {resident.unit}
                    </p>
                  </div>
                  <Badge tone="amber">{formatCurrency(resident.balance)}</Badge>
                </div>
              </div>
            ))}
          </div>
        </Panel>

        <Panel
          title="Property-by-property extras"
          description="Small details that still affect income, access, service charges, and tenant satisfaction."
        >
          <div className="grid gap-4 md:grid-cols-2">
            {properties.map((property) => (
              <div
                key={property.id}
                className="rounded-[22px] border border-border bg-white/72 p-4"
              >
                <p className="font-semibold text-foreground">{property.name}</p>
                <dl className="mt-3 space-y-2 text-sm text-muted">
                  <div className="flex items-center justify-between">
                    <dt>Parking permits</dt>
                    <dd className="font-medium text-foreground">
                      {property.permitsIssued}
                    </dd>
                  </div>
                  <div className="flex items-center justify-between">
                    <dt>EV bays</dt>
                    <dd className="font-medium text-foreground">{property.evBays}</dd>
                  </div>
                  <div className="flex items-center justify-between">
                    <dt>Tenant score</dt>
                    <dd className="font-medium text-foreground">
                      {property.residentScore.toFixed(1)}/5
                    </dd>
                  </div>
                </dl>
              </div>
            ))}
          </div>
        </Panel>
      </section>
    </div>
  );
}
