"use client";

import * as React from "react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import type { CommandCenterData } from "@/lib/queries/command-center";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { Tooltip } from "@/components/ui/primitives";

const CELL: Record<string, string> = { occupied: "bg-info-500", reserved: "bg-positive-500/80", blocked: "bg-[repeating-linear-gradient(45deg,var(--color-negative-500)_0_2px,transparent_2px_5px)]", available: "bg-surface-3" };
const LABEL: Record<string, string> = { occupied: "Occupied", reserved: "Reserved", blocked: "Blocked", available: "Available" };

export function Forecast({ forecast, heatmap }: { forecast: CommandCenterData["forecast"]; heatmap: CommandCenterData["heatmap"] }) {
  const windows: { key: keyof typeof forecast; label: string }[] = [
    { key: "today", label: "Today" },
    { key: "tomorrow", label: "Tomorrow" },
    { key: "d7", label: "7 days" },
    { key: "d14", label: "14 days" },
    { key: "d30", label: "30 days" },
  ];
  const [sel, setSel] = React.useState<keyof typeof forecast>("d7");
  const f = forecast[sel];
  return (
    <Card>
      <CardHeader title="Occupancy forecast" description="Where the gaps are in the next weeks" action={<Link href="/calendar" className="text-xs font-medium text-primary hover:underline">Open calendar</Link>} />
      <CardContent className="space-y-4">
        <div className="grid grid-cols-5 gap-1">
          {windows.map((w) => (
            <button key={w.key} type="button" onClick={() => setSel(w.key)} className={cn("rounded-lg border px-1 py-2 text-center transition", sel === w.key ? "border-primary bg-primary/5" : "border-border hover:border-border-strong")}>
              <span className="block text-2xs text-fg-muted">{w.label}</span>
              <span className="block text-base font-semibold tabular">{forecast[w.key].occupancy}%</span>
            </button>
          ))}
        </div>
        <div>
          <div className="flex h-2.5 w-full overflow-hidden rounded-full bg-surface-3">
            {(["occupied", "reserved", "blocked", "available"] as const).map((k) => (
              <div key={k} className={cn("h-full transition-all duration-500", CELL[k])} style={{ width: `${(f[k] / f.total) * 100}%` }} title={`${LABEL[k]} ${f[k]}`} />
            ))}
          </div>
          <div className="mt-2 grid grid-cols-4 gap-2 text-2xs">
            {(["occupied", "reserved", "available", "blocked"] as const).map((k) => (
              <span key={k} className="flex items-center gap-1 text-fg-muted">
                <span className={cn("size-2 rounded-sm", CELL[k])} /> {f[k]} {LABEL[k].toLowerCase()}
              </span>
            ))}
          </div>
        </div>
        <div>
          <p className="mb-1.5 text-2xs font-semibold uppercase tracking-wider text-fg-subtle">Heatmap · next 14 nights</p>
          <div className="overflow-x-auto scrollbar-none">
            <table className="w-full border-separate border-spacing-0.5">
              <thead>
                <tr>
                  <th className="w-10" />
                  {heatmap.days.map((d, i) => (
                    <th key={d.key} className={cn("text-center text-[9px] font-medium text-fg-subtle", i === 0 && "text-primary")}>
                      {d.label.split(" ")[1]}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {heatmap.rows.map((r) => (
                  <tr key={r.id}>
                    <td className="pr-1 font-mono text-[10px] font-semibold text-fg-muted">
                      <Link href={`/apartments/${r.id}?tab=timeline`} className="hover:text-primary">
                        {r.code}
                      </Link>
                    </td>
                    {r.cells.map((c, i) => (
                      <td key={i}>
                        <Tooltip content={`${r.code} · ${heatmap.days[i].label} · ${LABEL[c]}`}>
                          <Link href={`/calendar?start=${heatmap.days[i].key}`} className={cn("block h-3.5 w-full rounded-[3px] transition hover:ring-2 hover:ring-primary/40", CELL[c])} />
                        </Tooltip>
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
