import { EmptyState, Panel } from "@/components/shared/panel";
import type {
  DashboardSessionHeatmap,
  DashboardSessionHeatmaps,
  SummaryLoadState,
} from "./types";
import { threeMonthPeriodEnd } from "./heatmap-period";
import { SessionStartWeekNavigator } from "./session-start-week-navigator";

const DAYS = [
  { short: "Mon", full: "Monday" },
  { short: "Tue", full: "Tuesday" },
  { short: "Wed", full: "Wednesday" },
  { short: "Thu", full: "Thursday" },
  { short: "Fri", full: "Friday" },
  { short: "Sat", full: "Saturday" },
  { short: "Sun", full: "Sunday" },
];

const numberFormat = new Intl.NumberFormat("id-ID", {
  maximumFractionDigits: 2,
});

function formatDate(value: string) {
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    timeZone: "UTC",
  }).format(new Date(`${value}T00:00:00.000Z`));
}

function formatValue(value: number, average: boolean) {
  const formatted = numberFormat.format(value);
  return average ? `${formatted} average sessions` : `${formatted} sessions`;
}

function formatSlotDuration(minutes: number) {
  return minutes % 60 === 0
    ? `${minutes / 60}-hour slots`
    : `${minutes}-minute slots`;
}

function contrastTextColor(backgroundColor: string) {
  const linearChannel = (offset: number) => {
    const channel = parseInt(backgroundColor.slice(offset, offset + 2), 16) / 255;
    return channel <= 0.04045
      ? channel / 12.92
      : ((channel + 0.055) / 1.055) ** 2.4;
  };
  const luminance =
    0.2126 * linearChannel(1) +
    0.7152 * linearChannel(3) +
    0.0722 * linearChannel(5);
  return luminance > 0.179 ? "#000000" : "#FFFFFF";
}

function SessionStartHeatmapCard({
  report,
  title,
  selectedPeriodStart,
  latestSelectableDate,
  queryKey,
  granularity,
}: {
  report: SummaryLoadState<DashboardSessionHeatmap>;
  title: string;
  selectedPeriodStart: string;
  latestSelectableDate: string;
  queryKey: string;
  granularity: "week" | "three-month";
}) {
  const heatmap = report.data;
  const average = heatmap?.valueKind === "average-sessions";
  const cellsByPosition = new Map(
    (heatmap?.cells ?? []).map((cell) => [
      `${cell.dayIndex}:${cell.slotIndex}`,
      cell,
    ]),
  );
  const displayedPeriodStart = average
    ? selectedPeriodStart
    : heatmap?.periodStart;
  const displayedPeriodEnd = average
    ? threeMonthPeriodEnd(selectedPeriodStart) ?? heatmap?.periodEnd
    : heatmap?.periodEnd;
  const description = heatmap
    ? [
        `${formatDate(displayedPeriodStart ?? heatmap.periodStart)} – ${formatDate(displayedPeriodEnd ?? heatmap.periodEnd)}`,
        formatSlotDuration(heatmap.slotMinutes),
        heatmap.timezone,
      ].join(" · ")
    : "Session counts by day and time of day.";

  return (
    <Panel
      title={title}
      description={description}
      actions={
        <SessionStartWeekNavigator
          value={selectedPeriodStart}
          maxDate={latestSelectableDate}
          queryKey={queryKey}
          chartTitle={title}
          granularity={granularity}
        />
      }
    >
      {report.error ? (
        <EmptyState title="Heatmap unavailable" description={report.error} />
      ) : !heatmap ? (
        <EmptyState
          title="No heatmap data"
          description="The session heatmap returned no data."
        />
      ) : (
        <div className="overflow-x-auto">
          <table
            className="w-full min-w-[720px] table-fixed border-separate border-spacing-px text-xs"
            aria-label={title}
          >
            <thead>
              <tr>
                <th
                  scope="col"
                  className="w-28 px-2 pb-2 text-left font-medium text-muted-foreground"
                >
                  Time
                </th>
                {heatmap.dayLabels.map((label, index) => (
                  <th
                    key={`${index}-${label}`}
                    scope="col"
                    className="px-2 pb-2 text-center font-medium text-muted-foreground"
                  >
                    {DAYS[index]?.short ?? label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {heatmap.timeSlots.map((slot, slotIndex) => (
                <tr key={slot.key}>
                  <th
                    scope="row"
                    className="whitespace-nowrap px-2 py-1 text-left font-normal text-muted-foreground"
                  >
                    {slot.label}
                  </th>
                  {heatmap.dayLabels.map((dayLabel, dayIndex) => {
                    const cell = cellsByPosition.get(`${dayIndex}:${slotIndex}`);
                    const value = cell?.value ?? 0;
                    const dayName = DAYS[dayIndex]?.full ?? dayLabel;
                    const label = `${dayName}, ${slot.label}: ${formatValue(value, average)}`;
                    return (
                      <td key={`${dayIndex}-${slotIndex}`} className="p-0">
                        <div
                          className="flex h-9 items-center justify-center rounded-[3px] px-1 text-[11px] font-semibold tabular-nums text-foreground ring-1 ring-inset ring-border/50 sm:h-10 sm:text-xs"
                          style={
                            cell?.color
                              ? {
                                  backgroundColor: cell.color,
                                  color: contrastTextColor(cell.color),
                                }
                              : undefined
                          }
                          title={label}
                        >
                          {numberFormat.format(value)}
                        </div>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Panel>
  );
}

export function SessionStartHeatmaps({
  heatmaps,
}: {
  heatmaps: DashboardSessionHeatmaps;
}) {
  return (
    <div className="space-y-6">
      <SessionStartHeatmapCard
        report={heatmaps.weekly}
        title="Session Starts by Time & Day"
        selectedPeriodStart={heatmaps.selectedPeriodStarts.weekly}
        latestSelectableDate={heatmaps.latestSelectableDate}
        queryKey="session_week_start"
        granularity="week"
      />
      <SessionStartHeatmapCard
        report={heatmaps.average}
        title="Average Session Starts by Time & Day"
        selectedPeriodStart={heatmaps.selectedPeriodStarts.average}
        latestSelectableDate={heatmaps.latestSelectableDate}
        queryKey="average_session_period_start"
        granularity="three-month"
      />
    </div>
  );
}
