"use client";

import { useState, useMemo, useCallback } from "react";
import { Card, CardContent } from "@/shared/components/ui/card";
import { useReservations } from "../hooks/use-reservations";
import { DeskRoomLayout } from "./desk-room-layout";
import { DeskCalendar } from "./desk-calendar";
import { ReservationDialog } from "./reservation-dialog";
import type { DeskId } from "../types";
import { DESKS } from "../types";
import {
  toDateKey,
  getMonday,
  getReservationsForDate,
  getReservationForDesk,
  getUnbookedCurrentWeekDays,
  formatDateRo,
  formatDateShort,
  MAX_ADVANCE_DAYS,
} from "../services/reservation-service";
import { cn } from "@/shared/lib/utils";

export function HotDeskModule() {
  const { reservations, loading, addReservation, cancelReservation } =
    useReservations();

  const today = useMemo(() => {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    return d;
  }, []);

  const todayKey = useMemo(() => toDateKey(today), [today]);

  const [selectedDate, setSelectedDate] = useState(todayKey);
  const [weekStartDate, setWeekStartDate] = useState(() => getMonday(today));

  // Dialog state
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogDeskId, setDialogDeskId] = useState<DeskId>("desk-1");

  // --- Week navigation ---
  const currentMonday = useMemo(() => getMonday(today), [today]);

  const maxDate = useMemo(() => {
    const d = new Date(today);
    d.setDate(d.getDate() + MAX_ADVANCE_DAYS);
    return d;
  }, [today]);

  const canGoPrev = useMemo(() => {
    return weekStartDate > currentMonday;
  }, [weekStartDate, currentMonday]);

  const canGoNext = useMemo(() => {
    const nextMonday = new Date(weekStartDate);
    nextMonday.setDate(nextMonday.getDate() + 7);
    return nextMonday <= maxDate;
  }, [weekStartDate, maxDate]);

  const handlePrevWeek = useCallback(() => {
    setWeekStartDate((prev) => {
      const d = new Date(prev);
      d.setDate(d.getDate() - 7);
      if (d < currentMonday) return currentMonday;
      return d;
    });
  }, [currentMonday]);

  const handleNextWeek = useCallback(() => {
    setWeekStartDate((prev) => {
      const d = new Date(prev);
      d.setDate(d.getDate() + 7);
      return d;
    });
  }, []);

  // --- Stats ---
  const todayReservations = useMemo(
    () => getReservationsForDate(todayKey, reservations),
    [todayKey, reservations],
  );

  const selectedDayReservations = useMemo(
    () => getReservationsForDate(selectedDate, reservations),
    [selectedDate, reservations],
  );

  const unbookedDays = useMemo(
    () => getUnbookedCurrentWeekDays(reservations),
    [reservations],
  );

  // --- Desk click ---
  const handleDeskClick = useCallback((deskId: DeskId) => {
    setDialogDeskId(deskId);
    setDialogOpen(true);
  }, []);

  const handleBook = useCallback(
    async (userName: string, notes: string) => {
      await addReservation(dialogDeskId, selectedDate, userName, notes);
    },
    [addReservation, dialogDeskId, selectedDate],
  );

  const handleCancelReservation = useCallback(
    async (reservationId: string) => {
      await cancelReservation(reservationId);
    },
    [cancelReservation],
  );

  const existingReservation = useMemo(
    () => getReservationForDesk(dialogDeskId, selectedDate, reservations),
    [dialogDeskId, selectedDate, reservations],
  );

  if (loading) {
    return (
      <div className="flex min-h-[30vh] items-center justify-center">
        <p className="text-sm text-muted-foreground">Se încarcă...</p>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Subtle alert for unbooked work days */}
      {unbookedDays.length > 0 && (
        <div className="flex items-start gap-2.5 rounded-lg border border-amber-500/20 bg-amber-500/5 px-3.5 py-2.5">
          <div className="mt-0.5 h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500/60" />
          <p className="text-xs text-amber-600/80 dark:text-amber-400/70">
            {unbookedDays.length === 1
              ? `${formatDateShort(unbookedDays[0] ?? "")} nu are nicio rezervare.`
              : `${unbookedDays.length} zile din această săptămână nu au rezervări: ${unbookedDays.map((d) => formatDateShort(d)).join(", ")}.`}
          </p>
        </div>
      )}

      {/* Stats row */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Birouri" value={DESKS.length} sub="total cameră" />
        <StatCard
          label="Azi ocupate"
          value={todayReservations.length}
          sub={`din ${DESKS.length}`}
          highlight={todayReservations.length === DESKS.length}
        />
        <StatCard
          label="Azi libere"
          value={DESKS.length - todayReservations.length}
          sub="disponibile"
        />
        <StatCard
          label="Săpt. curentă"
          value={unbookedDays.length === 0 ? "✓" : unbookedDays.length}
          sub={unbookedDays.length === 0 ? "acoperit" : "zile neacoperite"}
          warn={unbookedDays.length > 0}
        />
      </div>

      {/* Main content: calendar + room layout */}
      <div className="grid gap-5 lg:grid-cols-[1fr_380px]">
        {/* Left: Calendar */}
        <Card className="border-border/50">
          <CardContent className="p-4 space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold">Calendar</h3>
              <span className="text-xs text-muted-foreground">
                {formatDateRo(selectedDate)}
              </span>
            </div>

            <DeskCalendar
              weekStart={weekStartDate}
              selectedDate={selectedDate}
              reservations={reservations}
              onSelectDate={setSelectedDate}
              onPrevWeek={handlePrevWeek}
              onNextWeek={handleNextWeek}
              canGoPrev={canGoPrev}
              canGoNext={canGoNext}
            />

            {/* Day detail table */}
            {selectedDayReservations.length > 0 ? (
              <div className="space-y-2">
                <h4 className="text-xs font-medium text-muted-foreground">
                  Rezervări — {formatDateRo(selectedDate)}
                </h4>
                <div className="rounded-lg border border-border/40 overflow-hidden">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border/30 bg-muted/30">
                        <th className="px-3 py-1.5 text-left text-xs font-medium text-muted-foreground">
                          Birou
                        </th>
                        <th className="px-3 py-1.5 text-left text-xs font-medium text-muted-foreground">
                          Persoana
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedDayReservations.map((r) => (
                        <tr
                          key={r.id}
                          className="border-b border-border/20 last:border-0 hover:bg-muted/20 cursor-pointer transition-colors"
                          onClick={() => handleDeskClick(r.deskId)}
                        >
                          <td className="px-3 py-1.5 text-xs font-medium">
                            {DESKS.find((d) => d.id === r.deskId)?.label ??
                              r.deskId}
                          </td>
                          <td className="px-3 py-1.5 text-xs">{r.userName}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            ) : (
              <p className="text-xs text-muted-foreground/60 text-center py-2">
                Nicio rezervare în {formatDateRo(selectedDate)}.
              </p>
            )}
          </CardContent>
        </Card>

        {/* Right: Room layout */}
        <Card className="border-border/50">
          <CardContent className="p-4 space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold">Cameră</h3>
              <span className="text-xs text-muted-foreground">
                {selectedDayReservations.length}/{DESKS.length} ocupate
              </span>
            </div>
            <DeskRoomLayout
              selectedDate={selectedDate}
              reservations={reservations}
              onDeskClick={handleDeskClick}
            />
            <p className="text-[11px] text-muted-foreground/50 text-center">
              Click pe un birou pentru a rezerva sau anula
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Reservation dialog */}
      <ReservationDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        deskId={dialogDeskId}
        dateKey={selectedDate}
        existingReservation={existingReservation}
        onBook={handleBook}
        onCancel={handleCancelReservation}
      />
    </div>
  );
}

// --- Stat Card ---

interface StatCardProps {
  label: string;
  value: string | number;
  sub: string;
  highlight?: boolean;
  warn?: boolean;
}

function StatCard({ label, value, sub, highlight, warn }: StatCardProps) {
  return (
    <Card
      className={cn(
        "border-border/40",
        highlight && "border-primary/30 bg-primary/5",
        warn && "border-amber-500/20 bg-amber-500/5",
      )}
    >
      <CardContent className="p-3">
        <p className="text-[11px] font-medium text-muted-foreground">{label}</p>
        <p
          className={cn(
            "text-xl font-bold",
            highlight && "text-primary",
            warn && "text-amber-600 dark:text-amber-400",
          )}
        >
          {value}
        </p>
        <p className="text-[10px] text-muted-foreground/60">{sub}</p>
      </CardContent>
    </Card>
  );
}
