/**
 * DateTimePicker Extended Component
 * Date and time picker with business hours and weekend exclusion for GCC
 */

"use client";

import { useState, useMemo } from "react";
import { UI, type Lang } from "@/lib/config";

interface DateTimePickerProps {
  selectedDate: string | null;
  selectedTime: string | null;
  onDateChange: (date: string) => void;
  onTimeChange: (time: string) => void;
  language: Lang;
  timezone?: string;
}

// Business hours: 9:00 AM - 5:00 PM (30-min intervals)
const generateTimeSlots = (): string[] => {
  const slots: string[] = [];
  for (let hour = 9; hour <= 16; hour++) {
    for (let minute = 0; minute < 60; minute += 30) {
      const time = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
      slots.push(time);
    }
  }
  // Add 5:00 PM slot
  slots.push("17:00");
  return slots;
};

const TIME_SLOTS = generateTimeSlots();

export default function DateTimePickerExtended({
  selectedDate,
  selectedTime,
  onDateChange,
  onTimeChange,
  language,
  timezone = "Asia/Qatar",
}: DateTimePickerProps) {
  const t = UI[language].t;
  const dir = UI[language].dir;
  const [currentMonth, setCurrentMonth] = useState(new Date());

  // Generate available dates (next 14 days, excluding weekends)
  const availableDates = useMemo(() => {
    const dates: Date[] = [];
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    let daysAdded = 0;
    let currentDate = new Date(today);

    while (daysAdded < 14) {
      const dayOfWeek = currentDate.getDay();
      // Exclude Friday (5) and Saturday (6) for GCC weekends
      if (dayOfWeek !== 5 && dayOfWeek !== 6) {
        dates.push(new Date(currentDate));
        daysAdded++;
      }
      currentDate.setDate(currentDate.getDate() + 1);
    }

    return dates;
  }, []);

  // Calendar grid generation
  const calendarDays = useMemo(() => {
    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const startingDayOfWeek = firstDay.getDay();
    const totalDays = lastDay.getDate();

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

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

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

    return days;
  }, [currentMonth]);

  const isDateAvailable = (date: Date): boolean => {
    return availableDates.some(
      (availableDate) => availableDate.toDateString() === date.toDateString(),
    );
  };

  const isDateSelected = (date: Date): boolean => {
    if (!selectedDate) return false;
    return new Date(selectedDate).toDateString() === date.toDateString();
  };

  const formatTime = (time: string): string => {
    const [hours, minutes] = time.split(":").map(Number);
    const period =
      hours >= 12
        ? language === "ar"
          ? "مساءً"
          : "PM"
        : language === "ar"
          ? "صباحاً"
          : "AM";
    const displayHour = hours > 12 ? hours - 12 : hours === 0 ? 12 : hours;
    return `${displayHour}:${minutes.toString().padStart(2, "0")} ${period}`;
  };

  const goToPreviousMonth = () => {
    setCurrentMonth(
      new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1),
    );
  };

  const goToNextMonth = () => {
    setCurrentMonth(
      new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1),
    );
  };

  const weekDays =
    language === "ar"
      ? [
          "الأحد",
          "الاثنين",
          "الثلاثاء",
          "الأربعاء",
          "الخميس",
          "الجمعة",
          "السبت",
        ]
      : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

  const monthName = currentMonth.toLocaleDateString(
    language === "ar" ? "ar-SA" : "en-US",
    {
      month: "long",
      year: "numeric",
    },
  );

  return (
    <div className="space-y-8" dir={dir}>
      {/* Date Picker */}
      <div>
        <label className="block text-lg font-semibold text-brand-ink dark:text-white mb-4">
          {t.interviewScheduleDateLabel}
        </label>

        {/* Info Banner */}
        <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg">
          <p className="text-sm text-blue-800 dark:text-blue-200">
            {t.datePickerNextDays} • {t.datePickerWeekendNote}
          </p>
        </div>

        {/* Calendar Header */}
        <div className="bg-white dark:bg-brand-ink rounded-xl shadow-lg p-6">
          <div className="flex items-center justify-between mb-6">
            <button
              onClick={goToPreviousMonth}
              className="p-2 hover:bg-brand-ink/5 dark:hover:bg-white/5 rounded-lg transition-colors"
              aria-label={language === "ar" ? "الشهر السابق" : "Previous month"}
            >
              <svg
                className={`w-5 h-5 text-brand-ink dark:text-white ${dir === "rtl" ? "rotate-180" : ""}`}
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 19l-7-7 7-7"
                />
              </svg>
            </button>

            <h3 className="text-lg font-semibold text-brand-ink dark:text-white">
              {monthName}
            </h3>

            <button
              onClick={goToNextMonth}
              className="p-2 hover:bg-brand-ink/5 dark:hover:bg-white/5 rounded-lg transition-colors"
              aria-label={language === "ar" ? "الشهر التالي" : "Next month"}
            >
              <svg
                className={`w-5 h-5 text-brand-ink dark:text-white ${dir === "rtl" ? "rotate-180" : ""}`}
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </button>
          </div>

          {/* Week Days */}
          <div className="grid grid-cols-7 gap-2 mb-2">
            {weekDays.map((day) => (
              <div
                key={day}
                className="text-center text-sm font-medium text-brand-ink/60 dark:text-white/60 py-2"
              >
                {day}
              </div>
            ))}
          </div>

          {/* Calendar Grid */}
          <div className="grid grid-cols-7 gap-2">
            {calendarDays.map((date, index) => {
              if (!date) {
                return <div key={`empty-${index}`} className="aspect-square" />;
              }

              const available = isDateAvailable(date);
              const selected = isDateSelected(date);

              return (
                <button
                  key={date.toISOString()}
                  onClick={() =>
                    available && onDateChange(date.toISOString().split("T")[0])
                  }
                  disabled={!available}
                  className={`
                    aspect-square
                    rounded-lg
                    text-sm
                    font-medium
                    transition-all
                    ${
                      selected
                        ? "bg-brand-green text-white ring-2 ring-brand-green ring-offset-2"
                        : available
                          ? "bg-brand-ink/5 dark:bg-white/5 text-brand-ink dark:text-white hover:bg-brand-green/10 hover:text-brand-green"
                          : "bg-transparent text-brand-ink/20 dark:text-white/20 cursor-not-allowed"
                    }
                  `}
                >
                  {date.getDate()}
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Time Picker */}
      {selectedDate && (
        <div>
          <label className="block text-lg font-semibold text-brand-ink dark:text-white mb-4">
            {t.interviewScheduleTimeLabel}
          </label>

          {/* Business Hours Info */}
          <div className="mb-4 p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 rounded-lg">
            <p className="text-sm text-green-800 dark:text-green-200">
              {t.datePickerBusinessHours} ({timezone})
            </p>
          </div>

          {/* Time Slots Grid */}
          <div className="bg-white dark:bg-brand-ink rounded-xl shadow-lg p-6">
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
              {TIME_SLOTS.map((time) => {
                const isSelected = selectedTime === time;
                const hour = parseInt(time.split(":")[0]);
                const isMorning = hour < 12;

                return (
                  <button
                    key={time}
                    onClick={() => onTimeChange(time)}
                    className={`
                      px-4
                      py-3
                      rounded-lg
                      text-sm
                      font-medium
                      transition-all
                      ${
                        isSelected
                          ? "bg-brand-green text-white ring-2 ring-brand-green ring-offset-2"
                          : "bg-brand-ink/5 dark:bg-white/5 text-brand-ink dark:text-white hover:bg-brand-green/10 hover:text-brand-green"
                      }
                    `}
                  >
                    <div className="flex flex-col items-center gap-1">
                      <span>{formatTime(time)}</span>
                      <span className="text-xs opacity-70">
                        {isMorning ? t.timeSlotMorning : t.timeSlotAfternoon}
                      </span>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
