/**
 * Mawidi Demo Scheduler - Time Slot Picker Component
 * Displays and allows selection of available time slots for a date
 */

"use client";

import React, { useMemo } from "react";
import type { TimeSlot } from "../types/scheduler.types";
import LoadingSpinner from "./LoadingSpinner";

export interface TimeSlotPickerProps {
  /** Available time slots for the selected date */
  timeSlots: TimeSlot[];
  /** Currently selected time slot */
  selectedTime: string | null;
  /** Callback when time slot is selected */
  onSelectTime: (time: string) => void;
  /** Selected date for context */
  selectedDate: Date | null;
  /** Meeting duration for filtering */
  duration: 30 | 60;
  /** Language for labels */
  language?: "en" | "ar";
  /** Custom className for styling */
  className?: string;
  /** Language direction */
  dir?: "ltr" | "rtl";
  /** Loading state */
  loading?: boolean;
}

const timeSlotLabels = {
  en: {
    title: "Select a time",
    description: "Choose from available time slots",
    noSlots: "No available time slots for this date",
    morning: "Morning",
    afternoon: "Afternoon",
    evening: "Evening",
    unavailable: "Unavailable",
    booked: "This time slot is already booked. Please select another time.",
    tooSoon: "This time is too soon. Please book at least 12 hours in advance.",
    outsideHours: "Outside working hours",
  },
  ar: {
    title: "اختر وقتًا",
    description: "اختر من الأوقات المتاحة",
    noSlots: "لا توجد أوقات متاحة لهذا التاريخ",
    morning: "صباحًا",
    afternoon: "ظهرًا",
    evening: "مساءً",
    unavailable: "غير متاح",
    booked: "هذا الوقت محجوز بالفعل. يرجى اختيار وقت آخر.",
    tooSoon: "هذا الوقت مبكر جدًا. يرجى الحجز قبل 12 ساعة على الأقل.",
    outsideHours: "خارج ساعات العمل",
  },
};

/**
 * TimeSlotPicker Component
 *
 * Displays available time slots grouped by time of day
 * Supports selection and shows unavailability reasons
 *
 * @example
 * ```tsx
 * <TimeSlotPicker
 *   timeSlots={slots}
 *   selectedTime="14:00"
 *   onSelectTime={(time) => setSelectedTime(time)}
 *   selectedDate={selectedDate}
 *   duration={30}
 *   language="en"
 * />
 * ```
 */
export default function TimeSlotPicker({
  timeSlots,
  selectedTime,
  onSelectTime,
  duration,
  language = "en",
  className = "",
  dir = "ltr",
  loading = false,
}: TimeSlotPickerProps) {
  const labels = timeSlotLabels[language];

  // Group time slots by time of day
  const groupedSlots = useMemo(() => {
    const groups = {
      morning: [] as TimeSlot[], // 6am - 11:59am
      afternoon: [] as TimeSlot[], // 12pm - 4:59pm
      evening: [] as TimeSlot[], // 5pm - 11:59pm
    };

    timeSlots.forEach((slot) => {
      const [hours] = slot.time.split(":").map(Number);

      if (hours >= 6 && hours < 12) {
        groups.morning.push(slot);
      } else if (hours >= 12 && hours < 17) {
        groups.afternoon.push(slot);
      } else {
        groups.evening.push(slot);
      }
    });

    return groups;
  }, [timeSlots]);

  // Filter to show only non-empty groups
  const visibleGroups = useMemo(() => {
    return Object.entries(groupedSlots).filter(([, slots]) => slots.length > 0);
  }, [groupedSlots]);

  // Format time for display based on language
  const formatTime = (timeString: string): string => {
    const [hours, minutes] = timeString.split(":").map(Number);
    const date = new Date();
    date.setHours(hours, minutes);

    if (language === "ar") {
      // 24-hour format for Arabic
      return timeString;
    } else {
      // 12-hour format for English
      const hour12 = hours % 12 || 12;
      const period = hours < 12 ? "AM" : "PM";
      return `${hour12}:${String(minutes).padStart(2, "0")} ${period}`;
    }
  };

  const getUnavailableReasonText = (
    reason?: TimeSlot["unavailableReason"],
  ): string => {
    switch (reason) {
      case "booked":
        return labels.booked;
      case "too-soon":
        return labels.tooSoon;
      case "outside-hours":
        return labels.outsideHours;
      case "past":
        return labels.unavailable;
      default:
        return labels.unavailable;
    }
  };

  if (loading) {
    return (
      <div className={`${className}`}>
        <LoadingSpinner
          size="md"
          message={
            language === "ar"
              ? "تحميل الأوقات المتاحة..."
              : "Loading available times..."
          }
        />
      </div>
    );
  }

  if (timeSlots.length === 0) {
    return (
      <div className={`space-y-6 ${className}`} dir={dir}>
        <h3 className="text-xl font-semibold text-[#1E293B] dark:text-white">
          {labels.title}
        </h3>
        <div className="flex flex-col items-center justify-center py-12 px-4 text-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700">
          <svg
            className="w-16 h-16 text-slate-300 dark:text-slate-600 mb-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
          <p className="text-[#64748B] dark:text-slate-400">{labels.noSlots}</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-6 ${className}`} dir={dir}>
      {/* Editorial Title and description */}
      <div className="space-y-2">
        <h3 className="text-xl font-semibold text-[#1E293B] dark:text-white">
          {labels.title}
        </h3>
        <p className="text-sm text-[#64748B] dark:text-slate-400">
          {labels.description}
        </p>
      </div>

      {/* Time slot groups - Editorial style */}
      <div className="space-y-8">
        {visibleGroups.map(([period, slots], groupIdx) => (
          <div key={period} className="space-y-4">
            {/* Group header - Editorial style with number */}
            <div className="flex items-center gap-3">
              <span className="text-[#10B981] font-mono text-xs" dir="ltr">
                {String(groupIdx + 1).padStart(2, "0")}
              </span>
              <h4 className="text-sm font-semibold text-[#1E293B] dark:text-slate-200 uppercase tracking-wide">
                {labels[period as "morning" | "afternoon" | "evening"]}
              </h4>
            </div>

            {/* Time slots grid - Editorial style */}
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-px bg-slate-200 dark:bg-slate-700">
              {slots.map((slot) => {
                const isSelected = selectedTime === slot.time;
                const isAvailable = slot.available;

                return (
                  <button
                    key={slot.time}
                    onClick={() => isAvailable && onSelectTime(slot.time)}
                    disabled={!isAvailable}
                    className={`
                      relative
                      px-4
                      py-3
                      font-medium
                      text-sm
                      transition-all
                      duration-200
                      ${
                        isSelected
                          ? "bg-[#10B981] text-white"
                          : isAvailable
                            ? "bg-white dark:bg-slate-900 text-[#1E293B] dark:text-white hover:bg-[#10B981]/10 dark:hover:bg-[#10B981]/20"
                            : "bg-slate-50 dark:bg-slate-800 text-slate-300 dark:text-slate-600 cursor-not-allowed"
                      }
                    `}
                    aria-label={`${formatTime(slot.time)}${!isAvailable ? ` - ${getUnavailableReasonText(slot.unavailableReason)}` : ""}`}
                    title={
                      !isAvailable
                        ? getUnavailableReasonText(slot.unavailableReason)
                        : undefined
                    }
                  >
                    {formatTime(slot.time)}

                    {/* Selection checkmark */}
                    {isSelected && (
                      <svg
                        className="absolute top-1 right-1 w-3 h-3 text-white"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M5 13l4 4L19 7"
                        />
                      </svg>
                    )}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      {/* Selected time summary - Editorial style */}
      {selectedTime && (
        <div className="flex items-start gap-3 p-4 bg-[#10B981]/5 dark:bg-[#10B981]/10 border border-[#10B981]/20 rounded-lg">
          <div className="w-1.5 h-1.5 bg-[#10B981] mt-2 flex-shrink-0" />
          <div className="text-sm">
            <p className="font-semibold text-[#1E293B] dark:text-white">
              {formatTime(selectedTime)}
            </p>
            <p className="text-[#64748B] dark:text-slate-400">
              {duration} {language === "ar" ? "دقيقة" : "minutes"}
            </p>
          </div>
        </div>
      )}

      {/* Timezone info - Editorial style */}
      <div className="flex items-center gap-2 text-xs text-[#64748B] dark:text-slate-500">
        <div className="w-1 h-1 bg-[#64748B] dark:bg-slate-500" />
        <span>
          {language === "ar"
            ? "جميع الأوقات بتوقيت UTC+3 (الرياض)"
            : "All times are in UTC+3 (Riyadh)"}
        </span>
      </div>
    </div>
  );
}
