"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useSite } from "@/contexts/site-context";
import {
  Users,
  UserPlus,
  Clock,
  RefreshCw,
  MapPin,
  X,
  Search,
} from "lucide-react";

// --- Types ---

interface Player {
  id: string;
  firstName?: string;
  lastName?: string;
  walkInName?: string;
  checkedInAt: string;
  sessionId: string;
}

interface Court {
  id: string;
  name: string;
  type: "INDOOR" | "OUTDOOR";
  isOpenPlay: boolean;
  status: "available" | "active" | "booked" | "open_play";
  players: Player[];
  upcomingBooking?: {
    startTime: string;
    clientName: string;
  };
}

interface ClientResult {
  id: string;
  firstName: string;
  lastName: string;
}

// --- Helpers ---

function getStatusConfig(court: Court) {
  if (court.status === "active") {
    return {
      dotColor: "bg-primary-500",
      text: `Active (${court.players.length} player${court.players.length !== 1 ? "s" : ""})`,
      bgColor: "bg-primary-50",
      borderColor: "border-primary-200",
      textColor: "text-primary-500",
    };
  }
  if (court.status === "open_play" && court.players.length === 0) {
    return {
      dotColor: "bg-amber-500",
      text: "Open Play",
      bgColor: "bg-amber-50",
      borderColor: "border-amber-200",
      textColor: "text-amber-500",
    };
  }
  if (court.status === "open_play" && court.players.length > 0) {
    return {
      dotColor: "bg-amber-500",
      text: `Open Play (${court.players.length} player${court.players.length !== 1 ? "s" : ""})`,
      bgColor: "bg-amber-50",
      borderColor: "border-amber-200",
      textColor: "text-amber-500",
    };
  }
  if (court.status === "booked") {
    return {
      dotColor: "bg-purple-500",
      text: "Booked",
      bgColor: "bg-purple-50",
      borderColor: "border-purple-200",
      textColor: "text-purple-500",
    };
  }
  return {
    dotColor: "bg-green-500",
    text: "Available",
    bgColor: "bg-green-50",
    borderColor: "border-green-200",
    textColor: "text-green-500",
  };
}

function formatTime(dateStr: string) {
  return new Date(dateStr).toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
  });
}

function playerName(player: Player) {
  if (player.walkInName) return player.walkInName;
  return [player.firstName, player.lastName].filter(Boolean).join(" ") || "Unknown";
}

function playerInitials(player: Player) {
  const name = playerName(player);
  const parts = name.split(" ");
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return name.slice(0, 2).toUpperCase();
}

// --- Main Page ---

export default function LiveCourtsPage() {
  const { selectedSiteId } = useSite();
  const [courts, setCourts] = useState<Court[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [checkInCourtId, setCheckInCourtId] = useState<string | null>(null);
  const [endSessionCourtId, setEndSessionCourtId] = useState<string | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // --- Data fetching ---

  const fetchCourts = useCallback(async () => {
    try {
      setError(null);
      const url = selectedSiteId
        ? `/api/live?siteId=${selectedSiteId}`
        : "/api/live";
      const response = await fetch(url);
      if (!response.ok) throw new Error("Failed to load court data");
      const data = await response.json();
      setCourts(data.courts ?? data.data ?? []);
      setLastUpdated(new Date());
    } catch (err) {
      console.error("Live courts fetch error:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setIsLoading(false);
    }
  }, [selectedSiteId]);

  useEffect(() => {
    fetchCourts();
    intervalRef.current = setInterval(fetchCourts, 30000);
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [fetchCourts]);

  // --- End session handler ---

  const handleEndSession = async (court: Court) => {
    try {
      await Promise.all(
        court.players.map((p) =>
          fetch(`/api/court-sessions/${p.sessionId}`, { method: "PUT" })
        )
      );
      setEndSessionCourtId(null);
      fetchCourts();
    } catch (err) {
      console.error("End session error:", err);
    }
  };

  // --- Render ---

  const checkInCourt = courts.find((c) => c.id === checkInCourtId) ?? null;
  const endSessionCourt = courts.find((c) => c.id === endSessionCourtId) ?? null;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-primary-800">Live Courts</h1>
          <p className="text-primary-500 mt-1">
            {lastUpdated
              ? `Last updated: ${lastUpdated.toLocaleTimeString()}`
              : "Loading..."}
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => fetchCourts()}
          disabled={isLoading}
        >
          <RefreshCw className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
          Refresh
        </Button>
      </div>

      {/* Error */}
      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">
          {error}
        </div>
      )}

      {/* Loading skeleton */}
      {isLoading && courts.length === 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <Card key={i}>
              <CardHeader className="pb-3">
                <div className="animate-pulse space-y-2">
                  <div className="h-5 bg-primary-100 rounded w-32" />
                  <div className="h-4 bg-primary-100 rounded w-20" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="animate-pulse space-y-3">
                  <div className="h-4 bg-primary-100 rounded w-full" />
                  <div className="h-8 bg-primary-100 rounded w-24" />
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Court grid */}
      {!isLoading && courts.length === 0 && !error && (
        <div className="text-center py-12 text-primary-500">
          <MapPin className="w-12 h-12 mx-auto mb-4 opacity-40" />
          <p className="text-lg font-medium">No courts found</p>
          <p className="text-sm mt-1">Courts will appear here once configured.</p>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {courts.map((court) => {
          const cfg = getStatusConfig(court);
          const earliestCheckIn = court.players.length > 0
            ? court.players.reduce((earliest, p) =>
                new Date(p.checkedInAt) < new Date(earliest.checkedInAt) ? p : earliest
              )
            : null;

          return (
            <Card key={court.id} className={`${cfg.borderColor} border`}>
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-base font-semibold">
                    {court.name}
                  </CardTitle>
                  <div className="flex items-center gap-1.5">
                    <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-primary-100 text-primary-600">
                      {court.type}
                    </span>
                    {court.isOpenPlay && (
                      <span className="text-xs font-medium px-2 py-0.5 rounded-full bg-amber-100 text-amber-700">
                        Open Play
                      </span>
                    )}
                  </div>
                </div>
                {/* Status indicator */}
                <div className="flex items-center gap-2 mt-1">
                  <span className={`inline-block w-2.5 h-2.5 rounded-full ${cfg.dotColor}`} />
                  <span className={`text-sm font-medium ${cfg.textColor}`}>
                    {cfg.text}
                  </span>
                </div>
              </CardHeader>

              <CardContent className="space-y-3">
                {/* Upcoming booking info for booked courts */}
                {court.status === "booked" && court.upcomingBooking && (
                  <div className="text-sm text-purple-600 bg-purple-50 rounded-md px-3 py-2">
                    <Clock className="w-3.5 h-3.5 inline mr-1" />
                    {court.upcomingBooking.clientName} at{" "}
                    {formatTime(court.upcomingBooking.startTime)}
                  </div>
                )}

                {/* Player list */}
                {court.players.length > 0 && (
                  <div className="space-y-2">
                    {court.players.map((player) => (
                      <div
                        key={player.id}
                        className="flex items-center gap-2 text-sm"
                      >
                        <div className="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-semibold shrink-0">
                          {playerInitials(player)}
                        </div>
                        <span className="text-primary-700 truncate">
                          {playerName(player)}
                        </span>
                      </div>
                    ))}
                  </div>
                )}

                {/* Time since first check-in */}
                {earliestCheckIn && (
                  <div className="flex items-center gap-1.5 text-xs text-primary-400">
                    <Clock className="w-3.5 h-3.5" />
                    Since {formatTime(earliestCheckIn.checkedInAt)}
                  </div>
                )}

                {/* Actions */}
                <div className="flex flex-wrap gap-2 pt-1">
                  {(court.status === "available" ||
                    court.status === "active" ||
                    court.status === "open_play") && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCheckInCourtId(court.id)}
                    >
                      <UserPlus className="w-4 h-4 mr-1" />
                      Check In
                    </Button>
                  )}
                  {(court.status === "active" || (court.status === "open_play" && court.players.length > 0)) && (
                    <Button
                      variant="outline"
                      size="sm"
                      className="text-red-600 border-red-200 hover:bg-red-50"
                      onClick={() => setEndSessionCourtId(court.id)}
                    >
                      <X className="w-4 h-4 mr-1" />
                      End Session
                    </Button>
                  )}
                  {court.isOpenPlay && (
                    <Button variant="outline" size="sm">
                      <Users className="w-4 h-4 mr-1" />
                      Schedule Group
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Check In Modal */}
      {checkInCourt && (
        <CheckInModal
          court={checkInCourt}
          onClose={() => setCheckInCourtId(null)}
          onSuccess={() => {
            setCheckInCourtId(null);
            fetchCourts();
          }}
        />
      )}

      {/* End Session Confirm Dialog */}
      {endSessionCourt && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white rounded-lg shadow-xl max-w-sm w-full mx-4 p-6 space-y-4">
            <h2 className="text-lg font-semibold text-primary-800">
              End Session
            </h2>
            <p className="text-sm text-primary-600">
              End session on <strong>{endSessionCourt.name}</strong>? This will
              check out all players.
            </p>
            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setEndSessionCourtId(null)}
              >
                Cancel
              </Button>
              <Button
                variant="destructive"
                size="sm"
                onClick={() => handleEndSession(endSessionCourt)}
              >
                End Session
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// --- Check In Modal Component ---

function CheckInModal({
  court,
  onClose,
  onSuccess,
}: {
  court: Court;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [mode, setMode] = useState<"search" | "walkin">("search");
  const [searchQuery, setSearchQuery] = useState("");
  const [walkInName, setWalkInName] = useState("");
  const [clients, setClients] = useState<ClientResult[]>([]);
  const [selectedClient, setSelectedClient] = useState<ClientResult | null>(null);
  const [isSearching, setIsSearching] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const debounceRef = useRef<NodeJS.Timeout | null>(null);

  // Debounced client search
  useEffect(() => {
    if (searchQuery.length < 2) {
      setClients([]);
      return;
    }
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      setIsSearching(true);
      try {
        const res = await fetch(
          `/api/clients?search=${encodeURIComponent(searchQuery)}`
        );
        if (res.ok) {
          const data = await res.json();
          setClients(data.data ?? data ?? []);
        }
      } catch {
        console.error("Client search failed");
      } finally {
        setIsSearching(false);
      }
    }, 300);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [searchQuery]);

  const handleSubmit = async () => {
    setIsSubmitting(true);
    try {
      const body: Record<string, string> = { courtId: court.id };
      if (mode === "search" && selectedClient) {
        body.clientId = selectedClient.id;
      } else if (mode === "walkin" && walkInName.trim()) {
        body.walkInName = walkInName.trim();
      } else {
        return;
      }

      const res = await fetch("/api/court-sessions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (!res.ok) throw new Error("Check-in failed");
      onSuccess();
    } catch (err) {
      console.error("Check-in error:", err);
    } finally {
      setIsSubmitting(false);
    }
  };

  const canSubmit =
    (mode === "search" && selectedClient !== null) ||
    (mode === "walkin" && walkInName.trim().length > 0);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 p-6 space-y-4">
        {/* Modal header */}
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold text-primary-800">
            Check In &mdash; {court.name}
          </h2>
          <button
            onClick={onClose}
            className="text-primary-400 hover:text-primary-600"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Mode toggle */}
        <div className="flex rounded-lg border border-primary-200 overflow-hidden">
          <button
            className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
              mode === "search"
                ? "bg-primary-100 text-primary-800"
                : "text-primary-500 hover:bg-primary-50"
            }`}
            onClick={() => setMode("search")}
          >
            <Search className="w-4 h-4 inline mr-1" />
            Find Client
          </button>
          <button
            className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
              mode === "walkin"
                ? "bg-primary-100 text-primary-800"
                : "text-primary-500 hover:bg-primary-50"
            }`}
            onClick={() => setMode("walkin")}
          >
            <UserPlus className="w-4 h-4 inline mr-1" />
            Walk-in
          </button>
        </div>

        {/* Search mode */}
        {mode === "search" && (
          <div className="space-y-3">
            <Input
              placeholder="Search by name..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setSelectedClient(null);
              }}
              autoFocus
            />
            {isSearching && (
              <p className="text-sm text-primary-400">Searching...</p>
            )}
            {clients.length > 0 && (
              <div className="max-h-40 overflow-y-auto border border-primary-200 rounded-md divide-y divide-primary-100">
                {clients.map((client) => (
                  <button
                    key={client.id}
                    className={`w-full text-left px-3 py-2 text-sm hover:bg-primary-50 transition-colors ${
                      selectedClient?.id === client.id
                        ? "bg-primary-100 font-medium"
                        : ""
                    }`}
                    onClick={() => setSelectedClient(client)}
                  >
                    {client.firstName} {client.lastName}
                  </button>
                ))}
              </div>
            )}
            {searchQuery.length >= 2 &&
              !isSearching &&
              clients.length === 0 && (
                <p className="text-sm text-primary-400">No clients found.</p>
              )}
            {selectedClient && (
              <div className="flex items-center gap-2 text-sm bg-primary-50 rounded-md px-3 py-2">
                <span className="font-medium text-primary-700">
                  Selected: {selectedClient.firstName} {selectedClient.lastName}
                </span>
              </div>
            )}
          </div>
        )}

        {/* Walk-in mode */}
        {mode === "walkin" && (
          <Input
            placeholder="Enter walk-in name..."
            value={walkInName}
            onChange={(e) => setWalkInName(e.target.value)}
            autoFocus
          />
        )}

        {/* Submit */}
        <div className="flex justify-end gap-2 pt-2">
          <Button variant="outline" size="sm" onClick={onClose}>
            Cancel
          </Button>
          <Button
            size="sm"
            disabled={!canSubmit || isSubmitting}
            onClick={handleSubmit}
          >
            {isSubmitting ? "Checking in..." : "Check In"}
          </Button>
        </div>
      </div>
    </div>
  );
}
