"use client";

import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { useAuth } from "@/core/auth";
import { cn } from "@/shared/lib/utils";
import type { DeskId, DeskReservation } from "../types";
import { getDeskLabel } from "../types";
import { formatDateRo, isDateBookable } from "../services/reservation-service";

const TEAM_NAMES = [
  "Alexandra",
  "Mihaela",
  "Ștefan",
  "Mara",
  "Denisa",
  "Daria",
];

interface ReservationDialogProps {
  open: boolean;
  onClose: () => void;
  deskId: DeskId;
  dateKey: string;
  existingReservation: DeskReservation | undefined;
  onBook: (userName: string, notes: string) => Promise<void>;
  onCancel: (reservationId: string) => Promise<void>;
}

export function ReservationDialog({
  open,
  onClose,
  deskId,
  dateKey,
  existingReservation,
  onBook,
  onCancel,
}: ReservationDialogProps) {
  const [userName, setUserName] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { user } = useAuth();

  // Auto-fill first name from Authentik session
  useEffect(() => {
    if (open && !userName && user?.name) {
      const firstName = user.name.split(" ")[0];
      if (firstName) setUserName(firstName);
    }
  }, [open, user?.name]); // eslint-disable-line react-hooks/exhaustive-deps

  const filteredNames = userName.trim()
    ? TEAM_NAMES.filter((n) =>
        n.toLowerCase().startsWith(userName.toLowerCase()),
      )
    : TEAM_NAMES;

  const bookable = isDateBookable(dateKey);
  const isBooked = !!existingReservation;

  const handleBook = async () => {
    if (!userName.trim()) return;
    setSubmitting(true);
    try {
      await onBook(userName.trim(), "");
      setUserName("");
      onClose();
    } finally {
      setSubmitting(false);
    }
  };

  const handleCancel = async () => {
    if (!existingReservation) return;
    setSubmitting(true);
    try {
      await onCancel(existingReservation.id);
      onClose();
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="sm:max-w-[400px]">
        <DialogHeader>
          <DialogTitle>
            {getDeskLabel(deskId)} — {formatDateRo(dateKey)}
          </DialogTitle>
        </DialogHeader>

        {isBooked ? (
          <div className="space-y-3 py-2">
            <div className="rounded-lg border border-border/50 bg-muted/30 p-3 space-y-1.5">
              <div className="text-sm">
                <span className="text-muted-foreground">Rezervat de: </span>
                <span className="font-medium">
                  {existingReservation.userName}
                </span>
              </div>
            </div>
          </div>
        ) : bookable ? (
          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label htmlFor="userName">Nume</Label>
              <Input
                id="userName"
                placeholder="Numele tău"
                value={userName}
                onChange={(e) => setUserName(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleBook()}
                autoFocus
              />
              <div className="flex flex-wrap gap-1.5">
                {filteredNames.map((name) => (
                  <button
                    key={name}
                    type="button"
                    onClick={() => setUserName(name)}
                    className={cn(
                      "rounded-md border px-2.5 py-1 text-xs transition-colors",
                      userName === name
                        ? "border-primary bg-primary/10 text-primary font-medium"
                        : "border-border/50 bg-muted/30 text-muted-foreground hover:border-primary/40 hover:bg-muted/50",
                    )}
                  >
                    {name}
                  </button>
                ))}
              </div>
            </div>
          </div>
        ) : (
          <div className="py-4 text-center text-sm text-muted-foreground">
            Această dată nu mai este disponibilă pentru rezervări.
          </div>
        )}

        <DialogFooter>
          {isBooked ? (
            <>
              <Button variant="outline" onClick={onClose} disabled={submitting}>
                Închide
              </Button>
              <Button
                variant="destructive"
                onClick={handleCancel}
                disabled={submitting}
              >
                {submitting ? "Se anulează..." : "Anulează rezervarea"}
              </Button>
            </>
          ) : bookable ? (
            <>
              <Button variant="outline" onClick={onClose} disabled={submitting}>
                Renunță
              </Button>
              <Button
                onClick={handleBook}
                disabled={submitting || !userName.trim()}
              >
                {submitting ? "Se rezervă..." : "Rezervă"}
              </Button>
            </>
          ) : (
            <Button variant="outline" onClick={onClose}>
              Închide
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
