"use client";

import { useEffect, useState, useMemo } from "react";
import {
  Calendar,
  Mail,
  Phone,
  Clock,
  Search,
  X,
  ChevronLeft,
  ChevronRight,
  Video,
} from "lucide-react";

interface DemoBooking {
  id: string;
  fullName: string;
  email: string;
  telephone: string;
  appointmentDate: string;
  appointmentTime: string;
  duration: string;
  specialRequirements: string | null;
  language: string;
  status: string;
  meetingLink: string | null;
  assignedTo: string | null;
  contactedAt: string | null;
  createdAt: string;
}

interface User {
  id: string;
  role: string;
}

export default function DemoBookingsList({ user }: { user: User }) {
  const [bookings, setBookings] = useState<DemoBooking[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState({
    status: "all",
    search: "",
    dateRange: "all",
  });
  const [selectedBooking, setSelectedBooking] = useState<DemoBooking | null>(
    null,
  );
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);

  const fetchBookings = async () => {
    try {
      const params = new URLSearchParams();
      if (filter.status !== "all") params.append("status", filter.status);
      if (filter.search) params.append("search", filter.search);
      if (filter.dateRange !== "all")
        params.append("dateRange", filter.dateRange);

      const response = await fetch(`/api/staff/dashboard/demos?${params}`);
      if (response.ok) {
        const data = await response.json();
        setBookings(data.bookings);
      }
    } catch (error) {
      console.error("Failed to fetch bookings:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBookings();
  }, [filter]);

  const handleStatusUpdate = async (bookingId: string, newStatus: string) => {
    try {
      const response = await fetch("/api/staff/dashboard/demos/update", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ bookingId, status: newStatus }),
      });

      if (response.ok) {
        fetchBookings();
      }
    } catch (error) {
      console.error("Failed to update status:", error);
    }
  };

  const handleAddMeetingLink = async (bookingId: string, link: string) => {
    try {
      const response = await fetch("/api/staff/dashboard/demos/update", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ bookingId, meetingLink: link }),
      });

      if (response.ok) {
        fetchBookings();
        setSelectedBooking(null);
      }
    } catch (error) {
      console.error("Failed to add meeting link:", error);
    }
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      pending: "bg-yellow-100 text-yellow-800",
      confirmed: "bg-green-100 text-green-800",
      cancelled: "bg-red-100 text-red-800",
    };

    return (
      <span
        className={`px-2 py-1 rounded-full text-xs font-semibold ${styles[status] || "bg-gray-100 text-gray-800"}`}
      >
        {status}
      </span>
    );
  };

  // Calendar helpers
  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDayOfWeek = firstDay.getDay();

    const days: (Date | null)[] = [];

    // Add empty slots for days before the first day of the month
    for (let i = 0; i < startingDayOfWeek; i++) {
      days.push(null);
    }

    // Add all days of the month
    for (let day = 1; day <= daysInMonth; day++) {
      days.push(new Date(year, month, day));
    }

    return days;
  };

  const bookingsByDate = useMemo(() => {
    const map = new Map<string, DemoBooking[]>();
    bookings.forEach((booking) => {
      const dateKey = new Date(booking.appointmentDate).toDateString();
      if (!map.has(dateKey)) {
        map.set(dateKey, []);
      }
      map.get(dateKey)!.push(booking);
    });
    return map;
  }, [bookings]);

  const getBookingsForDate = (date: Date) => {
    return bookingsByDate.get(date.toDateString()) || [];
  };

  const filteredBookings = useMemo(() => {
    if (!selectedDate) return bookings;
    return bookings.filter(
      (b) =>
        new Date(b.appointmentDate).toDateString() ===
        selectedDate.toDateString(),
    );
  }, [bookings, selectedDate]);

  const upcomingBookings = useMemo(() => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    return bookings
      .filter(
        (b) => new Date(b.appointmentDate) >= now && b.status !== "cancelled",
      )
      .sort(
        (a, b) =>
          new Date(a.appointmentDate).getTime() -
          new Date(b.appointmentDate).getTime(),
      );
  }, [bookings]);

  const days = getDaysInMonth(currentMonth);
  const monthName = currentMonth.toLocaleString("default", {
    month: "long",
    year: "numeric",
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading bookings...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {/* Search */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search by name or email..."
              value={filter.search}
              onChange={(e) => setFilter({ ...filter, search: e.target.value })}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
            />
          </div>

          {/* Status Filter */}
          <select
            value={filter.status}
            onChange={(e) => setFilter({ ...filter, status: e.target.value })}
            className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
          >
            <option value="all">All Status</option>
            <option value="pending">Pending</option>
            <option value="confirmed">Confirmed</option>
            <option value="cancelled">Cancelled</option>
          </select>

          {/* Date Range */}
          <select
            value={filter.dateRange}
            onChange={(e) =>
              setFilter({ ...filter, dateRange: e.target.value })
            }
            className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
          >
            <option value="all">All Time</option>
            <option value="today">Today</option>
            <option value="week">This Week</option>
            <option value="month">This Month</option>
          </select>

          {/* Clear Filters */}
          <button
            onClick={() => {
              setFilter({ status: "all", search: "", dateRange: "all" });
              setSelectedDate(null);
            }}
            className="flex items-center justify-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
          >
            <X className="w-4 h-4" />
            Clear
          </button>
        </div>
      </div>

      {/* Main Content - Split Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Side - Meetings List */}
        <div className="lg:col-span-2 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-brand-ink">
              {selectedDate
                ? `Meetings on ${selectedDate.toLocaleDateString()}`
                : "All Meetings"}
            </h2>
            <div className="flex items-center gap-4">
              <p className="text-sm text-gray-600">
                {filteredBookings.length} booking
                {filteredBookings.length !== 1 ? "s" : ""}
              </p>
              <button
                onClick={fetchBookings}
                className="text-sm text-brand-green hover:underline"
              >
                Refresh
              </button>
            </div>
          </div>

          {/* Bookings List */}
          <div className="space-y-4 max-h-[calc(100vh-320px)] overflow-y-auto pr-2">
            {filteredBookings.length > 0 ? (
              filteredBookings.map((booking) => (
                <div
                  key={booking.id}
                  className="bg-white rounded-xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <h3 className="text-base font-semibold text-brand-ink">
                          {booking.fullName}
                        </h3>
                        {getStatusBadge(booking.status)}
                      </div>
                      <div className="space-y-1 text-sm text-gray-600">
                        <div className="flex items-center gap-2">
                          <Mail className="w-4 h-4" />
                          <a
                            href={`mailto:${booking.email}`}
                            className="hover:text-brand-green"
                          >
                            {booking.email}
                          </a>
                        </div>
                        <div className="flex items-center gap-2">
                          <Phone className="w-4 h-4" />
                          <a
                            href={`tel:${booking.telephone}`}
                            className="hover:text-brand-green"
                          >
                            {booking.telephone}
                          </a>
                        </div>
                        <div className="flex items-center gap-2">
                          <Calendar className="w-4 h-4" />
                          {new Date(
                            booking.appointmentDate,
                          ).toLocaleDateString()}{" "}
                          at {booking.appointmentTime}
                        </div>
                        <div className="flex items-center gap-2">
                          <Clock className="w-4 h-4" />
                          {booking.duration} | {booking.language.toUpperCase()}
                        </div>
                      </div>
                      {booking.specialRequirements && (
                        <div className="mt-3 p-2 bg-gray-50 rounded-lg">
                          <p className="text-xs text-gray-600">
                            {booking.specialRequirements}
                          </p>
                        </div>
                      )}
                      {booking.meetingLink && (
                        <div className="mt-3 flex items-center gap-2">
                          <Video className="w-4 h-4 text-blue-600" />
                          <a
                            href={booking.meetingLink}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-sm text-blue-600 hover:underline"
                          >
                            Join Meeting
                          </a>
                        </div>
                      )}
                    </div>

                    {/* Actions */}
                    <div className="flex flex-col gap-2 ml-4">
                      {booking.status === "pending" && (
                        <>
                          <button
                            onClick={() =>
                              handleStatusUpdate(booking.id, "confirmed")
                            }
                            className="px-3 py-1.5 bg-brand-green text-white text-xs rounded-lg hover:bg-green-700 transition"
                          >
                            Confirm
                          </button>
                          <button
                            onClick={() => setSelectedBooking(booking)}
                            className="px-3 py-1.5 bg-blue-600 text-white text-xs rounded-lg hover:bg-blue-700 transition"
                          >
                            Add Link
                          </button>
                        </>
                      )}
                      {booking.status !== "cancelled" && (
                        <button
                          onClick={() =>
                            handleStatusUpdate(booking.id, "cancelled")
                          }
                          className="px-3 py-1.5 bg-red-100 text-red-700 text-xs rounded-lg hover:bg-red-200 transition"
                        >
                          Cancel
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
                <Calendar className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">
                  No meetings found
                </h3>
                <p className="text-gray-600 text-sm">
                  {selectedDate
                    ? "No meetings scheduled for this date"
                    : "No demo bookings yet"}
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Right Side - Calendar */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 sticky top-4">
            {/* Calendar Header */}
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-brand-ink">
                {monthName}
              </h2>
              <div className="flex items-center gap-2">
                <button
                  onClick={() =>
                    setCurrentMonth(
                      new Date(
                        currentMonth.getFullYear(),
                        currentMonth.getMonth() - 1,
                      ),
                    )
                  }
                  className="p-1.5 hover:bg-gray-100 rounded-lg transition"
                >
                  <ChevronLeft className="w-5 h-5 text-gray-600" />
                </button>
                <button
                  onClick={() => setCurrentMonth(new Date())}
                  className="px-2 py-1 text-xs text-brand-green hover:bg-green-50 rounded-lg transition"
                >
                  Today
                </button>
                <button
                  onClick={() =>
                    setCurrentMonth(
                      new Date(
                        currentMonth.getFullYear(),
                        currentMonth.getMonth() + 1,
                      ),
                    )
                  }
                  className="p-1.5 hover:bg-gray-100 rounded-lg transition"
                >
                  <ChevronRight className="w-5 h-5 text-gray-600" />
                </button>
              </div>
            </div>

            {/* Calendar Grid */}
            <div className="grid grid-cols-7 gap-1 mb-2">
              {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day) => (
                <div
                  key={day}
                  className="text-center text-xs font-medium text-gray-500 py-2"
                >
                  {day}
                </div>
              ))}
            </div>

            <div className="grid grid-cols-7 gap-1">
              {days.map((day, index) => {
                if (!day) {
                  return (
                    <div key={`empty-${index}`} className="aspect-square" />
                  );
                }

                const dayBookings = getBookingsForDate(day);
                const hasBookings = dayBookings.length > 0;
                const isToday =
                  day.toDateString() === new Date().toDateString();
                const isSelected =
                  selectedDate?.toDateString() === day.toDateString();
                const confirmedCount = dayBookings.filter(
                  (b) => b.status === "confirmed",
                ).length;
                const pendingCount = dayBookings.filter(
                  (b) => b.status === "pending",
                ).length;

                return (
                  <button
                    key={day.toISOString()}
                    onClick={() => setSelectedDate(isSelected ? null : day)}
                    className={`
                      aspect-square p-1 rounded-lg text-sm relative transition-all
                      ${isToday ? "ring-2 ring-brand-green" : ""}
                      ${isSelected ? "bg-brand-green text-white" : hasBookings ? "bg-green-50 hover:bg-green-100" : "hover:bg-gray-100"}
                    `}
                  >
                    <span className={`${isSelected ? "font-bold" : ""}`}>
                      {day.getDate()}
                    </span>
                    {hasBookings && (
                      <div className="absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-0.5">
                        {confirmedCount > 0 && (
                          <span
                            className={`w-1.5 h-1.5 rounded-full ${isSelected ? "bg-white" : "bg-green-500"}`}
                          />
                        )}
                        {pendingCount > 0 && (
                          <span
                            className={`w-1.5 h-1.5 rounded-full ${isSelected ? "bg-yellow-200" : "bg-yellow-500"}`}
                          />
                        )}
                      </div>
                    )}
                  </button>
                );
              })}
            </div>

            {/* Legend */}
            <div className="mt-4 pt-4 border-t border-gray-200">
              <div className="flex items-center gap-4 text-xs text-gray-600">
                <div className="flex items-center gap-1.5">
                  <span className="w-2 h-2 rounded-full bg-green-500" />
                  Confirmed
                </div>
                <div className="flex items-center gap-1.5">
                  <span className="w-2 h-2 rounded-full bg-yellow-500" />
                  Pending
                </div>
              </div>
            </div>

            {/* Upcoming Appointments */}
            <div className="mt-4 pt-4 border-t border-gray-200">
              <h3 className="text-sm font-semibold text-brand-ink mb-3">
                Upcoming
              </h3>
              <div className="space-y-2 max-h-48 overflow-y-auto">
                {upcomingBookings.slice(0, 5).map((booking) => (
                  <div
                    key={booking.id}
                    onClick={() => {
                      setSelectedDate(new Date(booking.appointmentDate));
                    }}
                    className="p-2 bg-gray-50 rounded-lg cursor-pointer hover:bg-gray-100 transition"
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-brand-ink truncate">
                        {booking.fullName}
                      </span>
                      {getStatusBadge(booking.status)}
                    </div>
                    <div className="text-xs text-gray-500 mt-1">
                      {new Date(booking.appointmentDate).toLocaleDateString()} •{" "}
                      {booking.appointmentTime}
                    </div>
                  </div>
                ))}
                {upcomingBookings.length === 0 && (
                  <p className="text-sm text-gray-500 text-center py-2">
                    No upcoming meetings
                  </p>
                )}
                {upcomingBookings.length > 5 && (
                  <p className="text-xs text-gray-500 text-center">
                    +{upcomingBookings.length - 5} more
                  </p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Meeting Link Modal */}
      {selectedBooking && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
            <h3 className="text-xl font-bold text-brand-ink mb-4">
              Add Meeting Link
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              For: {selectedBooking.fullName}
            </p>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                const link = formData.get("meetingLink") as string;
                handleAddMeetingLink(selectedBooking.id, link);
              }}
            >
              <input
                type="url"
                name="meetingLink"
                placeholder="https://zoom.us/j/..."
                required
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent mb-4"
              />
              <div className="flex gap-3">
                <button
                  type="button"
                  onClick={() => setSelectedBooking(null)}
                  className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700"
                >
                  Save Link
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
