"use client";

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

import { apiFetch, todayString } from "@/lib/api";
import { useDesktopEditorSupported } from "@/lib/editor-device";
import { FloorPlanResponse, Room, TableFloorState } from "@/lib/types";

export default function FloorPlanPage() {
  const desktopEditorSupported = useDesktopEditorSupported();
  const [rooms, setRooms] = useState<Room[]>([]);
  const [roomId, setRoomId] = useState("");
  const [date, setDate] = useState(todayString());
  const [data, setData] = useState<FloorPlanResponse | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    async function loadRooms() {
      try {
        const roomResults = await apiFetch<Room[]>("/rooms");
        setRooms(roomResults);
        if (roomResults[0]) {
          setRoomId(String(roomResults[0].id));
        }
      } catch (err) {
        setMessage(err instanceof Error ? err.message : "Impossibile caricare le sale");
      }
    }

    void loadRooms();
  }, []);

  useEffect(() => {
    if (!roomId) {
      return;
    }

    async function loadFloorPlan() {
      try {
        const result = await apiFetch<FloorPlanResponse>(`/floor-plan?date=${date}&room_id=${roomId}`);
        setData(result);
      } catch (err) {
        setMessage(err instanceof Error ? err.message : "Impossibile caricare la piantina");
      }
    }

    void loadFloorPlan();
  }, [date, roomId]);

  const stateMap = useMemo(() => {
    const map = new Map<number, TableFloorState>();
    data?.table_states.forEach((state) => map.set(state.table_id, state));
    return map;
  }, [data]);

  const joins = data?.reservations.filter((reservation) => reservation.requires_table_join) ?? [];

  return (
    <main className="space-y-6">
      <section className="grid gap-4 xl:grid-cols-[1.3fr,1fr]">
        <div className="panel">
          <p className="section-kicker">Vista spaziale</p>
          <h2 className="mt-3 section-title">Piantina operativa</h2>
          <p className="mt-3 section-intro">
            Mappa visuale della sala con tavoli posizionati, assegnazioni del giorno e stato occupazione leggibile in
            un colpo d'occhio.
          </p>
          <div className="mt-5 flex flex-wrap gap-3">
            {desktopEditorSupported === true ? (
              <Link className="button-primary" href="/tables">
                Metti in modifica
              </Link>
            ) : (
              <span className="button-primary cursor-not-allowed opacity-70">
                Editor disponibile da PC
              </span>
            )}
            <span className="subtle-pill bg-stone-100 text-stone-700">
              {desktopEditorSupported === true
                ? "Modifica misure, entrata, banco e tavoli nell'editor"
                : "Per modificare misure, entrata, banco e tavoli usa un PC"}
            </span>
          </div>
        </div>

        <div className="panel">
          <div className="grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Data</span>
              <input className="field" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Sala</span>
              <select className="field" value={roomId} onChange={(e) => setRoomId(e.target.value)}>
                <option value="">Seleziona sala</option>
                {rooms.map((room) => (
                  <option key={room.id} value={room.id}>
                    {room.name}
                  </option>
                ))}
              </select>
            </label>
          </div>
          {message ? <p className="notice is-error mt-4">{message}</p> : null}
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[1.55fr,1fr]">
        <div className="panel">
          {data ? (
            <div className="floor-plan-shell">
              <div
                className="floor-plan-canvas relative overflow-hidden rounded-[30px] border border-stone-200 shadow-inner"
                style={{ aspectRatio: `${data.room.width} / ${data.room.height}` }}
              >
                <div className="floor-plan-room-outline" />
                {data.room.background_image_data_url ? (
                  <div
                    className="floor-plan-background"
                    style={{ backgroundImage: `url(${data.room.background_image_data_url})` }}
                  />
                ) : null}
                {data.room.entrance_visible &&
                data.room.entrance_x !== null &&
                data.room.entrance_y !== null &&
                data.room.entrance_width !== null &&
                data.room.entrance_height !== null ? (
                  <div
                    className="floor-plan-entrance"
                    style={{
                      left: `${(data.room.entrance_x / data.room.width) * 100}%`,
                      top: `${(data.room.entrance_y / data.room.height) * 100}%`,
                      width: `${(data.room.entrance_width / data.room.width) * 100}%`,
                      height: `${(data.room.entrance_height / data.room.height) * 100}%`
                    }}
                  >
                    {data.room.entrance_name || "Entrata"}
                  </div>
                ) : null}
                {data.room.counter_visible && data.room.counter_x !== null && data.room.counter_y !== null && data.room.counter_width !== null && data.room.counter_height !== null ? (
                  <div
                    className="floor-plan-bar"
                    style={{
                      left: `${(data.room.counter_x / data.room.width) * 100}%`,
                      top: `${(data.room.counter_y / data.room.height) * 100}%`,
                      width: `${(data.room.counter_width / data.room.width) * 100}%`,
                      height: `${(data.room.counter_height / data.room.height) * 100}%`
                    }}
                  >
                    {data.room.counter_name || "Banco"}
                  </div>
                ) : null}
                {data.tables.map((table) => {
                  const tableState = stateMap.get(table.id);
                  const firstWindow = tableState?.occupancy_windows[0];
                  const occupied = Boolean(tableState && tableState.occupancy_windows.length > 0);
                  const isRoundTable = table.shape === "round";
                  return (
                    <div
                      key={table.id}
                      className={`floor-plan-table text-xs ${
                        tableState?.is_occupied_now
                          ? "is-current"
                          : occupied
                            ? "is-upcoming"
                            : "is-free"
                      } ${isRoundTable ? "rounded-full" : "rounded-[26px]"}`}
                      style={{
                        left: `${(table.x / data.room.width) * 100}%`,
                        top: `${(table.y / data.room.height) * 100}%`,
                        width: `${(table.width / data.room.width) * 100}%`,
                        height: `${(table.height / data.room.height) * 100}%`,
                        transform: `rotate(${table.rotation_degrees}deg)`
                      }}
                    >
                      <div className="font-semibold text-stone-800">{table.name}</div>
                      <div className="text-[11px] uppercase tracking-[0.15em] text-stone-500">{table.max_seats} posti</div>
                      {firstWindow ? (
                        <div className="mt-2 text-[11px] leading-4 text-stone-700">
                          <div>{firstWindow.customer_name}</div>
                          <div>
                            {firstWindow.start_time.slice(0, 5)} · {firstWindow.guests} pax
                          </div>
                        </div>
                      ) : (
                        <div className="mt-2 text-[11px] text-stone-500">Libero</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ) : (
            <p className="text-sm text-stone-500">Seleziona una sala per visualizzare la piantina.</p>
          )}
        </div>

        <div className="space-y-6">
          <div className="panel">
            <p className="section-kicker">Operazioni di sala</p>
            <h3 className="mt-3 font-display text-3xl text-ink">Unioni tavoli</h3>
            <div className="mt-4 space-y-3">
              {joins.map((reservation) => (
                <div key={reservation.reservation_id} className="rounded-[24px] border border-amber-200 bg-amber-50 p-4">
                  <div className="flex items-center justify-between gap-3">
                    <p className="font-semibold text-stone-800">{reservation.customer_name}</p>
                    <span className="subtle-pill bg-amber-200 text-amber-900">Unione</span>
                  </div>
                  <p className="mt-2 text-sm text-stone-700">
                    {reservation.start_time.slice(0, 5)} · {reservation.guests} coperti · {reservation.assignment_label}
                  </p>
                  {reservation.service_summary ? <p className="mt-2 text-sm text-stone-700">{reservation.service_summary}</p> : null}
                  <div className="mt-3 space-y-2 text-sm text-stone-600">
                    {reservation.service_steps.map((step) => (
                      <div key={step} className="floor-plan-step">
                        {step}
                      </div>
                    ))}
                  </div>
                </div>
              ))}
              {joins.length === 0 ? <p className="text-sm text-stone-500">Nessuna unione tavoli richiesta per questa data.</p> : null}
            </div>
          </div>

          <div className="panel">
            <p className="section-kicker">Occupazione tavoli</p>
            <h3 className="mt-3 font-display text-3xl text-ink">Stato area</h3>
            <div className="mt-4 space-y-3">
              {data?.table_states.map((state) => (
                <div key={state.table_id} className="soft-card">
                  <div className="flex items-center justify-between gap-3">
                    <p className="font-semibold">{state.table_name}</p>
                    <span
                      className={`subtle-pill ${
                        state.is_occupied_now
                          ? "bg-rose-100 text-rose-800"
                          : state.occupancy_windows.length > 0
                            ? "bg-amber-100 text-amber-900"
                            : "bg-emerald-100 text-emerald-900"
                      }`}
                    >
                      {state.is_occupied_now ? "Occupato ora" : state.occupancy_windows.length > 0 ? "Prenotato" : "Libero"}
                    </span>
                  </div>
                  <div className="mt-3 space-y-2 text-sm text-stone-600">
                    {state.occupancy_windows.map((window) => (
                      <div key={window.reservation_id} className="floor-plan-step">
                        {window.start_time.slice(0, 5)}-{window.end_time.slice(0, 5)} · {window.customer_name} · {window.guests} coperti
                      </div>
                    ))}
                    {state.occupancy_windows.length === 0 ? <p>Nessuna prenotazione su questo tavolo per la data selezionata.</p> : null}
                  </div>
                </div>
              ))}
              {!data ? <p className="text-sm text-stone-500">Nessuna sala caricata.</p> : null}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}
