"use client";

import { useState, useMemo } from "react";
import { trpc } from "~/lib/trpc/client.js";
import { EmptyState } from "~/components/ui/EmptyState.js";
import { DateRangePresets } from "~/components/ui/DateRangePresets.js";
import { BenchResourceCard } from "./BenchResourceCard.js";

function isoToday(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function isoOffsetDays(base: string, days: number): string {
  const d = new Date(base);
  d.setDate(d.getDate() + days);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

export function BenchBoardClient() {
  const today = isoToday();
  const [startDate, setStartDate] = useState(today);
  const [endDate, setEndDate] = useState(isoOffsetDays(today, 90));
  const [minHoursPerDay, setMinHoursPerDay] = useState(2);
  const [roleFilter, setRoleFilter] = useState("");

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const { data, isLoading, refetch } = (trpc.staffing.searchCapacity.useQuery as any)(
    {
      startDate: new Date(startDate),
      endDate: new Date(endDate),
      minHoursPerDay,
      limit: 100,
    },
    { staleTime: 60_000 },
  ) as {
    data: {
      results: Array<{
        id: string;
        name: string;
        eid: string;
        role: string | null;
        chapter: string | null;
        workingDays: number;
        availableHours: number;
        availableHoursPerDay: number;
      }>;
      totalFound: number;
      period: string;
    } | undefined;
    isLoading: boolean;
    refetch: () => void;
  };

  const filtered = useMemo(() => {
    if (!data?.results) return [];
    const q = roleFilter.trim().toLowerCase();
    if (!q) return data.results;
    return data.results.filter(
      (r) =>
        r.role?.toLowerCase().includes(q) ||
        r.name.toLowerCase().includes(q) ||
        r.chapter?.toLowerCase().includes(q),
    );
  }, [data?.results, roleFilter]);

  return (
    <div className="app-page space-y-6">
      <div className="app-page-header">
        <div>
          <h1 className="app-page-title">Bench Board</h1>
          <p className="app-page-subtitle mt-1">
            Resources with available capacity in the selected window — ready to take on new work.
          </p>
        </div>
      </div>

      {/* Filter bar */}
      <div className="app-surface p-4 space-y-3">
        <DateRangePresets onSelect={(s, e) => { setStartDate(s); setEndDate(e); }} />
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex items-center gap-2">
            <label className="text-xs font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap">
              From
            </label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-2 py-1.5 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-1 focus:ring-brand-500"
            />
          </div>
          <div className="flex items-center gap-2">
            <label className="text-xs font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap">
              To
            </label>
            <input
              type="date"
              value={endDate}
              min={startDate}
              onChange={(e) => setEndDate(e.target.value)}
              className="rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-2 py-1.5 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-1 focus:ring-brand-500"
            />
          </div>
          <div className="flex items-center gap-2">
            <label className="text-xs font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap">
              Min. {minHoursPerDay}h/day
            </label>
            <input
              type="range"
              min={0.5}
              max={8}
              step={0.5}
              value={minHoursPerDay}
              onChange={(e) => setMinHoursPerDay(Number(e.target.value))}
              className="w-28 accent-brand-600"
            />
          </div>
          <input
            type="text"
            value={roleFilter}
            onChange={(e) => setRoleFilter(e.target.value)}
            placeholder="Filter by role, name, chapter…"
            className="flex-1 min-w-32 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-3 py-1.5 text-sm text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-1 focus:ring-brand-500"
          />
          <button
            type="button"
            onClick={() => refetch()}
            className="rounded-lg border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
          >
            Refresh
          </button>
        </div>
        {data && (
          <p className="text-xs text-gray-500 dark:text-gray-400">
            {filtered.length} resource{filtered.length !== 1 ? "s" : ""} found
            {roleFilter ? ` matching "${roleFilter}"` : ""}
            {" "}— period: {data.period}
          </p>
        )}
      </div>

      {/* Results grid */}
      {isLoading ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="rounded-xl border border-gray-200 dark:border-gray-700 p-4 space-y-3">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 shimmer-skeleton rounded-full" />
                <div className="flex-1 space-y-1.5">
                  <div className="h-3.5 w-32 shimmer-skeleton rounded" />
                  <div className="h-2.5 w-16 shimmer-skeleton rounded" />
                </div>
              </div>
              <div className="h-2 shimmer-skeleton rounded-full" />
            </div>
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <EmptyState
          title="No resources on bench"
          detail={
            roleFilter
              ? "No resources match your filter. Try a different role or name."
              : "Everyone is fully booked in this period. Try a wider date range or lower the minimum hours threshold."
          }
        />
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filtered.map((resource) => (
            <BenchResourceCard
              key={resource.id}
              id={resource.id}
              name={resource.name}
              eid={resource.eid}
              role={resource.role}
              chapter={resource.chapter}
              workingDays={resource.workingDays}
              availableHours={resource.availableHours}
              availableHoursPerDay={resource.availableHoursPerDay}
            />
          ))}
        </div>
      )}
    </div>
  );
}
