import { Button, Divider, message } from "antd";
import BackIcon from "components/Icons/BackIcon.tsx";
import NextIcon from "components/Icons/NextIcon.tsx";
import dayjs from "dayjs";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useAppSelector } from "redux/hooks";
import { ProGray1 } from "ThemeConstants";
import { SERVER_DATE_FORMAT } from "utils/constants.ts";
import styles from "./TimeEstimateCard.module.css";

const timeSlots = [
  "12:00",
  "1:00",
  "2:00",
  "3:00",
  "4:00",
  "5:00",
  "6:00",
  "7:00",
  "8:00",
  "9:00",
  "10:00",
  "11:00",
];
interface EstimateTimeContentProps {
  onSave: (date: string, time: string) => void;
  onClose: () => void;
}

export default function Content({ onSave, onClose }: EstimateTimeContentProps) {
  const { t } = useTranslation();
  const [selectedDate, setSelectedDate] = useState<string>(dayjs().format(SERVER_DATE_FORMAT));
  const [selectedTime, setSelectedTime] = useState<string>();
  const [isAM, setIsAM] = useState(true);
  const { isRTL } = useAppSelector((state) => state.locale);

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

  const goToPreviousDay = () => {
    const newDate = dayjs(selectedDate).subtract(1, "d");
    const today = dayjs().startOf("day");
    const newDateStart = newDate.startOf("day");
    
    // Check if the new date would be before today
    if (newDateStart.isBefore(today)) {
      message.warning(t("cart.cannotSelectPastDate"));
      return;
    }
    
    setSelectedDate(newDate.format(SERVER_DATE_FORMAT));
  };

  const goToNextDay = () => {
    const newDate = dayjs(selectedDate).add(1, "d");
    setSelectedDate(newDate.format(SERVER_DATE_FORMAT));
  };

  const handleTimeSelect = (time: string) => {
    setSelectedTime(time);
  };

  const handleSave = () => {
    onSave(
      dayjs(selectedDate).format(SERVER_DATE_FORMAT),
      formatSelectedTime(selectedTime, isAM),
    );
    onClose();
  };

  // covert from 12 to 24 hours system
  const formatSelectedTime = (time: string | undefined, am: boolean) => {
    const fallback = "12:00";
    if (!time) return fallback;

    if (am) {
      return time === "12:00" ? "00:00" : time.padStart(5, "0");
    }

    const [rawHour, minute = "00"] = time.split(":");
    const hour = Number(rawHour);
    if (Number.isNaN(hour)) {
      return fallback;
    }

    const convertedHour = hour === 12 ? 12 : hour + 12;
    return `${convertedHour.toString().padStart(2, "0")}:${minute}`;
  };

  return (
    <div style={{ padding: "0 20px", marginTop: 30 }}>
      {/* Day Selection */}
      <div style={{ marginBottom: 30 }}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginBottom: 20,
          }}
        >
          <Button
            type="text"
            icon={
              isRTL ? (
                <NextIcon className={styles.nextIcon} />
              ) : (
                <BackIcon className={styles.backIcon} />
              )
            }
            onClick={isRTL ? goToNextDay : goToPreviousDay}
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          />

          <div
            style={{
              flex: 1,
              textAlign: "center",
              padding: "0 20px",
            }}
          >
            <div
              style={{
                fontSize: 20,
                fontWeight: 600,
                color: ProGray1,
                marginBottom: 4,
              }}
            >
              {formatDate(dayjs(selectedDate).toDate())}
            </div>
          </div>

          <Button
            type="text"
            icon={
              isRTL ? (
                <BackIcon className={styles.backIcon} />
              ) : (
                <NextIcon className={styles.nextIcon} />
              )
            }
            onClick={isRTL ? goToPreviousDay : goToNextDay}
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          />
        </div>
      </div>

      {/* Time Selection */}
      <div>
        {/* AM/PM Toggle */}
        <div
          style={{
            display: "flex",
            justifyContent: isRTL ? "start" : "end",
            marginBottom: 20,
            gap: 10,
          }}
        >
          <Button
            onClick={() => setIsAM(true)}
            className={styles.toggleButton + " " + (isAM ? styles.active : "")}
          >
            {t("cart.am")}
          </Button>
          <Button
            onClick={() => setIsAM(false)}
            className={styles.toggleButton + " " + (!isAM ? styles.active : "")}
          >
            {t("cart.pm")}
          </Button>
        </div>

        {/* Time Slots Grid */}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gap: 12,
            marginBottom: 30,
          }}
        >
          {timeSlots.map((time) => (
            <Button
              key={time}
              onClick={() => handleTimeSelect(time)}
              className={
                styles.timeButton +
                " " +
                (selectedTime === time ? styles.active : "")
              }
            >
              {time}
            </Button>
          ))}
        </div>

        <Divider />

        {/* Save Button */}
        <Button
          type="primary"
          onClick={handleSave}
          style={{
            width: "100%",
            height: 50,
            fontSize: 16,
            fontWeight: 600,
            backgroundColor: "var(--primary)",
            border: "none",
          }}
        >
          {t("cart.confirmTime")}
        </Button>
      </div>
    </div>
  );
}
