import type { ComplianceItem, Property } from "@/lib/property-data-uk";
import { daysUntil, formatDate } from "@/lib/property-data-uk";

type YearlyCheckWheelProps = {
  complianceItems: ComplianceItem[];
  properties: Property[];
  title?: string;
  description?: string;
  className?: string;
};

type DeadlineBand = {
  label: string;
  colour: string;
  className: string;
};

const TODAY_LABEL = "14 May 2026";
function joinClasses(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(" ");
}

function getDeadlineBand(days: number): DeadlineBand {
  if (days < 0) {
    return {
      label: "Overdue",
      colour: "#b94d45",
      className: "border-danger/30 bg-danger-soft text-danger",
    };
  }

  if (days <= 30) {
    return {
      label: "0-30 days",
      colour: "#c48a39",
      className: "border-accent/30 bg-accent-soft text-accent",
    };
  }

  if (days <= 90) {
    return {
      label: "31-90 days",
      colour: "#9cab5d",
      className: "border-primary/30 bg-primary-soft text-primary",
    };
  }

  if (days <= 180) {
    return {
      label: "91-180 days",
      colour: "#557690",
      className: "border-border bg-surface-strong text-foreground",
    };
  }

  return {
    label: "Later",
    colour: "#7f8d72",
    className: "border-success/30 bg-success/10 text-success",
  };
}

function getPropertyName(properties: Property[], propertyId: string) {
  return properties.find((property) => property.id === propertyId)?.name ?? propertyId;
}

function getTimeframePercent(days: number) {
  if (days <= 0) {
    return 6;
  }

  return Math.max(8, Math.min(100, (days / 365) * 100));
}

function getDueText(days: number) {
  if (days < 0) {
    return `${Math.abs(days)} days overdue`;
  }

  if (days === 0) {
    return "Due today";
  }

  return `Due in ${days} days`;
}

export function YearlyCheckWheel({
  complianceItems,
  properties,
  title = "Yearly checks timeframe",
  description = "A 12-month bar view of certificates and checks, coloured by how close the deadline is.",
  className,
}: YearlyCheckWheelProps) {
  const activeItems = complianceItems
    .filter((item) => item.status !== "Completed")
    .slice()
    .sort((a, b) => daysUntil(a.dueDate) - daysUntil(b.dueDate));
  const urgentCount = activeItems.filter((item) => daysUntil(item.dueDate) <= 30).length;
  const overdueCount = activeItems.filter((item) => daysUntil(item.dueDate) < 0).length;

  return (
    <section className={joinClasses("border-y border-border py-6", className)}>
      <div className="grid gap-6 xl:grid-cols-[340px_minmax(0,1fr)] xl:items-center">
        <div>
          <p className="font-mono text-xs uppercase tracking-[0.28em] text-primary">
            Annual checks
          </p>
          <h2 className="mt-2 text-2xl font-semibold tracking-tight text-foreground">
            {title}
          </h2>
          <p className="mt-2 text-sm leading-6 text-muted">{description}</p>

          <div className="mt-4 flex flex-wrap gap-2">
            <span className="rounded-full border border-danger/25 bg-danger-soft px-3 py-1 text-xs font-semibold text-danger">
              {overdueCount} overdue
            </span>
            <span className="rounded-full border border-accent/25 bg-accent-soft px-3 py-1 text-xs font-semibold text-accent">
              {urgentCount} due in 30 days
            </span>
            <span className="rounded-full border border-border bg-surface-strong px-3 py-1 text-xs font-semibold text-muted">
              Today: {TODAY_LABEL}
            </span>
          </div>
        </div>

        <div className="grid gap-5 lg:grid-cols-[320px_minmax(0,1fr)] lg:items-start">
          <div
            aria-label="Annual check timeframe bars"
            className="rounded-[28px] border border-border bg-surface-strong p-4"
            role="img"
          >
            <div className="flex items-end justify-between gap-4">
              <div>
                <p className="font-mono text-[10px] uppercase tracking-[0.22em] text-muted">
                  12 months
                </p>
                <p className="mt-1 text-xl font-semibold text-foreground">
                  {activeItems.length} checks
                </p>
              </div>
              <p className="text-xs text-muted">Nearer deadlines fill more of the bar.</p>
            </div>

            <div className="mt-5 grid gap-3">
              {activeItems.slice(0, 6).map((item) => {
                const days = daysUntil(item.dueDate);
                const band = getDeadlineBand(days);
                const propertyName = getPropertyName(properties, item.propertyId);
                const width = `${getTimeframePercent(days)}%`;

                return (
                  <div key={item.id}>
                    <div className="mb-1.5 flex items-center justify-between gap-3">
                      <p className="truncate text-xs font-semibold text-foreground">
                        {item.type}
                      </p>
                      <p className="shrink-0 text-[11px] text-muted">
                        {getDueText(days)}
                      </p>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-background/70">
                      <div
                        className="h-full rounded-full transition-[width] duration-300"
                        style={{ backgroundColor: band.colour, width }}
                      />
                    </div>
                    <p className="mt-1 truncate text-[11px] text-muted">
                      {propertyName} - {formatDate(item.dueDate)}
                    </p>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="grid gap-3">
            {activeItems.slice(0, 8).map((item) => {
              const days = daysUntil(item.dueDate);
              const band = getDeadlineBand(days);
              const dueText = getDueText(days);

              return (
                <article
                  className="grid gap-3 border-b border-border pb-3 last:border-b-0 last:pb-0 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center"
                  key={item.id}
                >
                  <div>
                    <div className="flex flex-wrap items-center gap-2">
                      <span
                        className={joinClasses(
                          "inline-flex rounded-full border px-2.5 py-1 text-[11px] font-bold uppercase tracking-[0.16em]",
                          band.className,
                        )}
                      >
                        {band.label}
                      </span>
                      <span className="text-xs uppercase tracking-[0.18em] text-muted">
                        {item.type}
                      </span>
                    </div>
                    <h3 className="mt-2 text-sm font-semibold text-foreground">
                      {item.title}
                    </h3>
                    <p className="mt-1 text-sm text-muted">
                      {getPropertyName(properties, item.propertyId)} - {item.owner}
                    </p>
                  </div>
                  <div className="text-left sm:text-right">
                    <p className="text-sm font-semibold text-foreground">
                      {formatDate(item.dueDate)}
                    </p>
                    <p className="text-xs text-muted">{dueText}</p>
                  </div>
                </article>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}
