"use client";

import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";

import { apiFetch, todayString } from "@/lib/api";
import { useDesktopEditorSupported } from "@/lib/editor-device";
import { StatusBadge } from "@/components/status-badge";
import { Reservation, ReservationListResponse, Room } from "@/lib/types";

const AUTO_REFRESH_INTERVAL_MS = 10000;

export function OperationsDashboard() {
  const desktopEditorSupported = useDesktopEditorSupported();
  const [reservations, setReservations] = useState<Reservation[]>([]);
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdatedAt, setLastUpdatedAt] = useState<string | null>(null);
  const [autoRefreshError, setAutoRefreshError] = useState<string | null>(null);
  const requestControllerRef = useRef<AbortController | null>(null);
  const day = todayString();

  async function loadDashboard({ silent = false }: { silent?: boolean } = {}) {
    if (silent && requestControllerRef.current) {
      return;
    }
    if (!silent) {
      requestControllerRef.current?.abort();
    }
    const controller = new AbortController();
    requestControllerRef.current = controller;

    if (!silent) {
      setLoading(true);
      setError(null);
    }

    try {
      const [reservationResponse, roomResponse] = await Promise.all([
        apiFetch<ReservationListResponse>(`/reservations?reservation_date=${day}`, {
          signal: controller.signal
        }),
        apiFetch<Room[]>("/rooms", {
          signal: controller.signal
        })
      ]);
      setReservations(reservationResponse.items);
      setRooms(roomResponse);
      setLastUpdatedAt(
        new Date().toLocaleTimeString("it-IT", {
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit"
        })
      );
      setAutoRefreshError(null);
      if (silent) {
        setError(null);
      }
    } catch (err) {
      if (err instanceof Error && err.name === "AbortError") {
        return;
      }
      if (silent) {
        setAutoRefreshError("Aggiornamento automatico momentaneamente non riuscito. Riprovo tra pochi secondi.");
      } else {
        setError(err instanceof Error ? err.message : "Impossibile caricare il cruscotto");
      }
    } finally {
      if (!silent) {
        setLoading(false);
      }
      if (requestControllerRef.current === controller) {
        requestControllerRef.current = null;
      }
    }
  }

  useEffect(() => {
    void loadDashboard();
  }, [day]);

  useEffect(() => {
    function refreshVisibleDashboard() {
      if (document.visibilityState === "visible") {
        void loadDashboard({ silent: true });
      }
    }

    const intervalId = window.setInterval(() => {
      if (document.visibilityState === "visible") {
        void loadDashboard({ silent: true });
      }
    }, AUTO_REFRESH_INTERVAL_MS);

    window.addEventListener("focus", refreshVisibleDashboard);
    document.addEventListener("visibilitychange", refreshVisibleDashboard);

    return () => {
      window.clearInterval(intervalId);
      window.removeEventListener("focus", refreshVisibleDashboard);
      document.removeEventListener("visibilitychange", refreshVisibleDashboard);
      requestControllerRef.current?.abort();
    };
  }, [day]);

  const stats = useMemo(() => {
    const counts = reservations.reduce<Record<string, number>>((acc, reservation) => {
      acc[reservation.status] = (acc[reservation.status] || 0) + 1;
      return acc;
    }, {});

    return {
      total: reservations.length,
      unassigned: reservations.filter(
        (reservation) => reservation.assigned_table_id === null && reservation.assigned_combination_id === null
      ).length,
      confirmed: counts.confirmed || 0,
      pending: counts.pending || 0
    };
  }, [reservations]);

  return (
    <main className="grid gap-6 xl:grid-cols-[1.35fr,0.95fr] xl:items-start">
      <div className="space-y-6">
        <div className="panel-strong">
          <div>
            <p className="text-[11px] uppercase tracking-[0.32em] text-stone-600">Panoramica giornaliera</p>
            <h2 className="mt-4 font-display text-4xl text-ink md:text-5xl">
              Il servizio di oggi, letto come una control room.
            </h2>
            <p className="mt-4 max-w-2xl text-sm leading-6 text-stone-600">
              Controlla volumi, conferme, richieste in sospeso e tavoli ancora scoperti prima dell&apos;apertura del
              turno.
            </p>

            <div className="mt-8 grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
              <div className="metric-tile">
                <p>Totale oggi</p>
                <p>{stats.total}</p>
                <span className="mt-2 block text-sm text-stone-600">{day}</span>
              </div>
              <div className="metric-tile">
                <p>Confermate</p>
                <p>{stats.confirmed}</p>
                <span className="mt-2 block text-sm text-stone-600">Pronte per il servizio</span>
              </div>
              <div className="metric-tile">
                <p>In attesa</p>
                <p>{stats.pending}</p>
                <span className="mt-2 block text-sm text-stone-600">Da confermare</span>
              </div>
              <div className="metric-tile">
                <p>Senza tavolo</p>
                <p>{stats.unassigned}</p>
                <span className="mt-2 block text-sm text-stone-600">Da risolvere</span>
              </div>
            </div>
          </div>

          <div className="pointer-events-none absolute inset-0 overflow-hidden">
            <div className="absolute -right-8 top-8 h-40 w-40 rounded-full bg-white/10 blur-3xl" />
            <div className="absolute bottom-0 left-16 h-28 w-56 rounded-full bg-copper/25 blur-3xl" />
          </div>
        </div>

        <div className="panel">
          <div className="mb-6 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
            <div>
              <p className="section-kicker">Timeline operativa</p>
              <h2 className="mt-3 section-title text-3xl md:text-[2.6rem]">Servizio del giorno</h2>
              <p className="mt-3 section-intro">
                Focus sulle prenotazioni di oggi, con stato cliente e assegnazione gia leggibili senza cambiare
                schermata.
              </p>
            </div>
            <Link className="button-primary" href="/reservations/new">
              Nuova prenotazione
            </Link>
          </div>

          {loading ? <p className="text-sm text-stone-500">Caricamento dati...</p> : null}
          {error ? <p className="notice is-error">{error}</p> : null}

          {!loading && !error ? (
            <div className="table-shell">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>Ora</th>
                    <th>Cliente</th>
                    <th>Coperti</th>
                    <th>Stato</th>
                    <th>Assegnazione</th>
                  </tr>
                </thead>
                <tbody>
                  {reservations.map((reservation) => (
                    <tr key={reservation.id}>
                      <td data-label="Ora">
                        <div className="inline-flex rounded-2xl bg-stone-100 px-3 py-2 font-semibold text-slate">
                          {reservation.start_time.slice(0, 5)}
                        </div>
                      </td>
                      <td data-label="Cliente">
                        <div className="font-semibold text-stone-800">{reservation.customer.name}</div>
                        <div className="mt-1 text-xs uppercase tracking-[0.12em] text-stone-500">
                          {reservation.customer.phone}
                        </div>
                      </td>
                      <td data-label="Coperti" className="font-semibold text-stone-700">
                        {reservation.guests}
                      </td>
                      <td data-label="Stato">
                        <StatusBadge status={reservation.status} />
                      </td>
                      <td data-label="Assegnazione">
                        {reservation.assigned_table?.name || reservation.assigned_combination?.name ? (
                          <span className="subtle-pill bg-emerald-50 text-emerald-900">
                            {reservation.assigned_table?.name || reservation.assigned_combination?.name}
                          </span>
                        ) : (
                          <span className="subtle-pill bg-rose-50 text-rose-700">Non assegnata</span>
                        )}
                      </td>
                    </tr>
                  ))}
                  {reservations.length === 0 ? (
                    <tr>
                      <td className="empty-state-cell py-6 text-stone-500" colSpan={5}>
                        Nessuna prenotazione disponibile per oggi.
                      </td>
                    </tr>
                  ) : null}
                </tbody>
              </table>
            </div>
          ) : null}
        </div>
      </div>

      <div className="space-y-6">
        <div className="space-y-4">
          <div className="stat-card">
            <p className="section-kicker">Controllo rapido</p>
            <h3 className="mt-3 font-display text-3xl text-ink">Panoramica aggiornata</h3>
            <p className="mt-3 text-sm leading-6 text-stone-600">
              Aggiorna la vista del giorno per controllare prenotazioni, sale e priorita operative prima del turno.
            </p>
            <p className="mt-4 text-xs uppercase tracking-[0.14em] text-stone-500">
              Aggiornamento automatico attivo ogni 10 secondi
              {lastUpdatedAt ? ` · Ultimo aggiornamento ${lastUpdatedAt}` : ""}
            </p>
            {autoRefreshError ? <p className="notice mt-4">{autoRefreshError}</p> : null}
            <button className="button-primary mt-5 w-full" onClick={() => void loadDashboard()}>
              Aggiorna panoramica
            </button>
          </div>

          <div className="stat-card">
            <p className="section-kicker">Navigazione rapida</p>
            <h3 className="mt-3 font-display text-3xl text-ink">Passaggi chiave</h3>
            <div className="mt-4 grid gap-3">
              <Link href="/reservations" className="button-secondary">
                Gestisci prenotazioni
              </Link>
              {desktopEditorSupported === true ? (
                <Link href="/tables" className="button-secondary">
                  Configura tavoli
                </Link>
              ) : (
                <span className="button-secondary cursor-not-allowed opacity-70">
                  Editor disponibile da PC
                </span>
              )}
              <Link href="/floor-plan" className="button-secondary">
                Apri piantina
              </Link>
              <Link href="/whatsapp" className="button-secondary">
                Apri WhatsApp
              </Link>
            </div>
          </div>
        </div>

        <div className="panel">
          <p className="section-kicker">Sala configurata</p>
          <h2 className="mt-3 section-title text-3xl md:text-[2.4rem]">Spazi attivi</h2>
          <p className="mt-3 section-intro">
            Riepilogo delle sale disponibili nel locale, con spazi gia pronti da leggere e usare durante il servizio.
          </p>

          <div className="mt-6 space-y-4">
            {rooms.map((room) => (
              <div key={room.id} className="soft-card">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="font-semibold text-stone-800">{room.name}</p>
                    <p className="mt-1 text-sm text-stone-500">
                      Area {room.width.toFixed(1)} m × {room.height.toFixed(1)} m
                    </p>
                  </div>
                  <span className="subtle-pill bg-stone-100 text-stone-700">Attiva</span>
                </div>
              </div>
            ))}
            {rooms.length === 0 ? <p className="text-sm text-stone-500">Nessuna sala configurata.</p> : null}
          </div>
        </div>
      </div>
    </main>
  );
}
