"use client";

import { useState, useEffect } from "react";
import {
  Calendar,
  Clock,
  User,
  Video,
  FileText,
  MoreVertical,
  Search,
} from "lucide-react";
import { useAppTheme } from "@/components/ThemeProvider";
import { listAppointments } from "@/lib/actions/appointments";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import type { Appointment } from "@/lib/models/appointments";

export default function Booking() {
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const { theme } = useAppTheme();
  const isDark = theme === "dark";

  useEffect(() => {
    const fetchBookings = async () => {
      setLoading(true);
      try {
        const data = await listAppointments();
        console.log("Fetched appointments:", data);
        console.log("Appointments count:", data?.length);
        setAppointments(data || []);
      } catch (error) {
        console.error("Failed to fetch appointments:", error);
        toast.error("Failed to load appointments. Please try again.");
        setAppointments([]);
      } finally {
        setLoading(false);
      }
    };

    fetchBookings();
  }, []);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleTimeString("en-US", {
      hour: "numeric",
      minute: "2-digit",
      hour12: true,
    });
  };

  const getStatusColor = (status: string) => {
    const normalized = status.toLowerCase();
    if (isDark) {
      switch (normalized) {
        case "scheduled":
          return "bg-blue-500/20 text-blue-200";
        case "completed":
          return "bg-green-500/20 text-green-200";
        case "rejected":
        case "cancelled":
          return "bg-red-500/20 text-red-200";
        case "pending_review":
        case "pending":
          return "bg-yellow-500/20 text-yellow-200";
        default:
          return "bg-gray-700 text-gray-200";
      }
    }
    switch (normalized) {
      case "scheduled":
        return "bg-blue-100 text-blue-700";
      case "completed":
        return "bg-green-100 text-green-700";
      case "rejected":
      case "cancelled":
        return "bg-red-100 text-red-700";
      case "pending_review":
      case "pending":
        return "bg-yellow-100 text-yellow-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  const formatStatus = (status: string) => {
    return status.replace("_", " ").replace(/\b\w/g, (l) => l.toUpperCase());
  };

  const filteredAppointments = appointments.filter(
    (appointment) =>
      appointment.first_name
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      appointment.last_name
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      appointment.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (appointment.phone && appointment.phone.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  return (
    <div className={`min-h-screen ${isDark ? "bg-gray-900" : "bg-gray-50"}`}>

      {/* Main Content */}
      <main className="p-3 sm:p-4 md:p-6 lg:p-8">
          {/* Page Header */}
          <div className="mb-4 sm:mb-6 flex flex-col gap-3 sm:gap-4">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
              <div>
                <h1 className={`text-xl sm:text-2xl font-semibold mb-1 ${isDark ? "text-white" : "text-gray-900"}`}>
                  Bookings
                </h1>
                <p className={`text-xs sm:text-sm ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                  Manage and view all appointment bookings
                </p>
              </div>
            </div>
            {/* Search Bar */}
            <div className="relative">
              <Search className={`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${isDark ? "text-gray-400" : "text-gray-500"}`} />
              <Input
                type="text"
                placeholder="Search by name, email, or phone..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className={`pl-10 ${isDark ? "bg-gray-800 border-gray-700 text-white placeholder:text-gray-400" : "bg-white border-gray-200 text-gray-900 placeholder:text-gray-500"}`}
              />
            </div>
          </div>

          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${isDark ? "border-gray-600" : "border-gray-400"}`}></div>
            </div>
          ) : filteredAppointments.length === 0 ? (
            <div className={`rounded-lg border p-12 text-center ${isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"}`}>
              <Calendar className={`w-12 h-12 mx-auto mb-4 ${isDark ? "text-gray-500" : "text-gray-400"}`} />
              <p className={`font-medium mb-1 ${isDark ? "text-gray-200" : "text-gray-600"}`}>No bookings found</p>
              <p className={`text-sm ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                {searchTerm
                  ? "Try adjusting your search terms"
                  : "No appointments have been created yet"}
              </p>
            </div>
          ) : (
            <div className={`rounded-lg border overflow-hidden ${isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"}`}>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className={`${isDark ? "bg-gray-800 border-b border-gray-700" : "bg-gray-50 border-b border-gray-200"}`}>
                    <tr>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-left text-xs font-medium uppercase tracking-wider ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Patient
                      </th>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-left text-xs font-medium uppercase tracking-wider hidden md:table-cell ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Date & Time
                      </th>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-left text-xs font-medium uppercase tracking-wider hidden lg:table-cell ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Duration
                      </th>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-left text-xs font-medium uppercase tracking-wider ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Status
                      </th>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-left text-xs font-medium uppercase tracking-wider hidden lg:table-cell ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Preferred Dates
                      </th>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-left text-xs font-medium uppercase tracking-wider hidden xl:table-cell ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Created
                      </th>
                      <th className={`px-3 sm:px-4 md:px-6 py-3 text-right text-xs font-medium uppercase tracking-wider ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody className={`${isDark ? "bg-gray-800 divide-gray-700" : "bg-white divide-gray-200"}`}>
                    {filteredAppointments.map((appointment) => (
                      <tr
                        key={appointment.id}
                        className={`transition-colors ${isDark ? "hover:bg-gray-700" : "hover:bg-gray-50"}`}
                      >
                        <td className="px-3 sm:px-4 md:px-6 py-4">
                          <div className="flex items-center">
                            <div className={`shrink-0 h-8 w-8 sm:h-10 sm:w-10 rounded-full flex items-center justify-center ${isDark ? "bg-gray-700" : "bg-gray-100"}`}>
                              <User className={`w-4 h-4 sm:w-5 sm:h-5 ${isDark ? "text-gray-200" : "text-gray-600"}`} />
                            </div>
                            <div className="ml-2 sm:ml-4 min-w-0">
                              <div className={`text-xs sm:text-sm font-medium truncate ${isDark ? "text-white" : "text-gray-900"}`}>
                                {appointment.first_name} {appointment.last_name}
                              </div>
                              <div className={`text-xs sm:text-sm truncate hidden sm:block ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                                {appointment.email}
                              </div>
                              {appointment.phone && (
                                <div className={`text-xs truncate hidden sm:block ${isDark ? "text-gray-500" : "text-gray-400"}`}>
                                  {appointment.phone}
                                </div>
                              )}
                              {appointment.scheduled_datetime && (
                                <div className={`text-xs sm:hidden mt-0.5 ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                                  {formatDate(appointment.scheduled_datetime)}
                                </div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap hidden md:table-cell">
                          {appointment.scheduled_datetime ? (
                            <>
                              <div className={`text-xs sm:text-sm ${isDark ? "text-white" : "text-gray-900"}`}>
                                {formatDate(appointment.scheduled_datetime)}
                              </div>
                              <div className={`text-xs sm:text-sm flex items-center gap-1 ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                                <Clock className="w-3 h-3" />
                                {formatTime(appointment.scheduled_datetime)}
                              </div>
                            </>
                          ) : (
                            <div className={`text-xs sm:text-sm ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                              Not scheduled
                            </div>
                          )}
                        </td>
                        <td className={`px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap text-xs sm:text-sm hidden lg:table-cell ${isDark ? "text-white" : "text-gray-900"}`}>
                          {appointment.scheduled_duration ? `${appointment.scheduled_duration} min` : "-"}
                        </td>
                        <td className="px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap">
                          <span
                            className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(
                              appointment.status
                            )}`}
                          >
                            {formatStatus(appointment.status)}
                          </span>
                        </td>
                        <td className={`px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap text-xs sm:text-sm hidden lg:table-cell ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                          {appointment.preferred_dates && appointment.preferred_dates.length > 0 ? (
                            <div className="flex flex-col gap-1">
                              {appointment.preferred_dates.slice(0, 2).map((date, idx) => (
                                <span key={idx}>{formatDate(date)}</span>
                              ))}
                              {appointment.preferred_dates.length > 2 && (
                                <span className="text-xs">+{appointment.preferred_dates.length - 2} more</span>
                              )}
                            </div>
                          ) : (
                            "-"
                          )}
                        </td>
                        <td className={`px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap text-xs sm:text-sm hidden xl:table-cell ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                          {formatDate(appointment.created_at)}
                        </td>
                        <td className="px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <div className="flex items-center justify-end gap-1 sm:gap-2">
                            {appointment.jitsi_meet_url && (
                              <a
                                href={appointment.jitsi_meet_url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className={`p-1.5 sm:p-2 rounded-lg transition-colors ${isDark ? "text-gray-300 hover:text-white hover:bg-gray-700" : "text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`}
                                title="Join Meeting"
                              >
                                <Video className="w-4 h-4" />
                              </a>
                            )}
                            {appointment.reason && (
                              <button
                                className={`p-1.5 sm:p-2 rounded-lg transition-colors ${isDark ? "text-gray-300 hover:text-white hover:bg-gray-700" : "text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`}
                                title={appointment.reason}
                              >
                                <FileText className="w-4 h-4" />
                              </button>
                            )}
                            <button className={`p-1.5 sm:p-2 rounded-lg transition-colors ${isDark ? "text-gray-300 hover:text-white hover:bg-gray-700" : "text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`}>
                              <MoreVertical className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </main>
    </div>
  );
}

