"use client";

import { useState, useEffect } from "react";
import {
  Calendar,
  Clock,
  User,
  Video,
  FileText,
  MoreVertical,
} from "lucide-react";
import { useAppTheme } from "@/components/ThemeProvider";

interface User {
  ID: number;
  CreatedAt?: string;
  UpdatedAt?: string;
  DeletedAt?: string | null;
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  location: string;
  date_of_birth?: string;
  is_admin?: boolean;
  bookings?: null;
}

interface Booking {
  ID: number;
  CreatedAt: string;
  UpdatedAt: string;
  DeletedAt: string | null;
  user_id: number;
  user: User;
  scheduled_at: string;
  duration: number;
  status: string;
  jitsi_room_id: string;
  jitsi_room_url: string;
  payment_id: string;
  payment_status: string;
  amount: number;
  notes: string;
}

interface BookingsResponse {
  bookings: Booking[];
  limit: number;
  offset: number;
  total: number;
}

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

  useEffect(() => {
    // Simulate API call
    const fetchBookings = async () => {
      setLoading(true);
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Mock API response
      const mockData: BookingsResponse = {
        bookings: [
          {
            ID: 1,
            CreatedAt: "2025-11-06T11:33:45.704633Z",
            UpdatedAt: "2025-11-06T11:33:45.707543Z",
            DeletedAt: null,
            user_id: 3,
            user: {
              ID: 3,
              CreatedAt: "2025-11-06T10:43:01.299311Z",
              UpdatedAt: "2025-11-06T10:43:48.427284Z",
              DeletedAt: null,
              first_name: "John",
              last_name: "Smith",
              email: "john.doe@example.com",
              phone: "+1234567891",
              location: "Los Angeles, CA",
              date_of_birth: "0001-01-01T00:00:00Z",
              is_admin: true,
              bookings: null,
            },
            scheduled_at: "2025-11-07T10:00:00Z",
            duration: 60,
            status: "scheduled",
            jitsi_room_id: "booking-1-1762428825-22c92ced2870c17c",
            jitsi_room_url:
              "https://meet.jit.si/booking-1-1762428825-22c92ced2870c17c",
            payment_id: "",
            payment_status: "pending",
            amount: 52,
            notes: "Initial consultation session",
          },
        ],
        limit: 50,
        offset: 0,
        total: 1,
      };

      setBookings(mockData.bookings);
      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 "cancelled":
          return "bg-red-500/20 text-red-200";
        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 "cancelled":
        return "bg-red-100 text-red-700";
      case "pending":
        return "bg-yellow-100 text-yellow-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  const getPaymentStatusColor = (status: string) => {
    const normalized = status.toLowerCase();
    if (isDark) {
      switch (normalized) {
        case "paid":
          return "bg-green-500/20 text-green-200";
        case "pending":
          return "bg-yellow-500/20 text-yellow-200";
        case "failed":
          return "bg-red-500/20 text-red-200";
        default:
          return "bg-gray-700 text-gray-200";
      }
    }
    switch (normalized) {
      case "paid":
        return "bg-green-100 text-green-700";
      case "pending":
        return "bg-yellow-100 text-yellow-700";
      case "failed":
        return "bg-red-100 text-red-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  const filteredBookings = bookings.filter(
    (booking) =>
      booking.user.first_name
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      booking.user.last_name
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      booking.user.email.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 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>
            <button className={`w-full sm:w-auto px-3 sm:px-4 py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors ${
              isDark ? "bg-rose-500 text-white hover:bg-rose-600" : "bg-gray-900 text-white hover:bg-gray-800"
            }`}>
              + New Booking
            </button>
          </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>
          ) : filteredBookings.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"
                  : "Create a new booking to get started"}
              </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"}`}>
                        Payment
                      </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"}`}>
                        Amount
                      </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"}`}>
                    {filteredBookings.map((booking) => (
                      <tr
                        key={booking.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"}`}>
                                {booking.user.first_name} {booking.user.last_name}
                              </div>
                              <div className={`text-xs sm:text-sm truncate hidden sm:block ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                                {booking.user.email}
                              </div>
                              <div className={`text-xs sm:hidden mt-0.5 ${isDark ? "text-gray-400" : "text-gray-500"}`}>
                                {formatDate(booking.scheduled_at)}
                              </div>
                            </div>
                          </div>
                        </td>
                        <td className="px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap hidden md:table-cell">
                          <div className={`text-xs sm:text-sm ${isDark ? "text-white" : "text-gray-900"}`}>
                            {formatDate(booking.scheduled_at)}
                          </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(booking.scheduled_at)}
                          </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"}`}>
                          {booking.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(
                              booking.status
                            )}`}
                          >
                            {booking.status}
                          </span>
                        </td>
                        <td className="px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap hidden lg:table-cell">
                          <span
                            className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getPaymentStatusColor(
                              booking.payment_status
                            )}`}
                          >
                            {booking.payment_status}
                          </span>
                        </td>
                        <td className={`px-3 sm:px-4 md:px-6 py-4 whitespace-nowrap text-xs sm:text-sm font-medium hidden xl:table-cell ${isDark ? "text-white" : "text-gray-900"}`}>
                          ${booking.amount}
                        </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">
                            {booking.jitsi_room_url && (
                              <a
                                href={booking.jitsi_room_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>
                            )}
                            {booking.notes && (
                              <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="View Notes"
                              >
                                <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>
  );
}

