"use client";
import React, { useState, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Clock, Calendar, CalendarDays, Repeat } from "lucide-react";
import { Input } from "@/components/ui/input";

interface SchedulingComponentProps {
  onChange?: (payload: any) => void;
  onHideDeliveryTime?: (shouldHide: boolean) => void;
}

const SchedulingComponent: React.FC<SchedulingComponentProps> = ({ onChange, onHideDeliveryTime }) => {
  const [subscriptionType, setSubscriptionType] = useState("once");
  const [weeklyDays, setWeeklyDays] = useState<string[]>([]);
  const [monthlyDates, setMonthlyDates] = useState<number[]>([]);
  const [orderTime, setOrderTime] = useState("");

  useEffect(() => {
    const savedType = localStorage.getItem("subscription_type");
    if (savedType) {
      setSubscriptionType(savedType);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("subscription_type", subscriptionType);
  }, [subscriptionType]);

  const weekDays = [
    { label: "Mon", value: "Monday" },
    { label: "Tue", value: "Tuesday" },
    { label: "Wed", value: "Wednesday" },
    { label: "Thu", value: "Thursday" },
    { label: "Fri", value: "Friday" },
    { label: "Sat", value: "Saturday" },
    { label: "Sun", value: "Sunday" },
  ];

  const subscriptionOptions = [
    { value: "once", label: "Once", icon: Clock },
    { value: "daily", label: "Daily", icon: CalendarDays },
    { value: "weekly", label: "Weekly", icon: Calendar },
    { value: "monthly", label: "Monthly", icon: Repeat },
  ];

  const toggleWeeklyDay = (day: string) => {
    setWeeklyDays((prev) =>
      prev.includes(day) ? prev.filter((d) => d !== day) : [...prev, day]
    );
  };

  const toggleMonthlyDate = (date: number) => {
    setMonthlyDates((prev) =>
      prev.includes(date) ? prev.filter((d) => d !== date) : [...prev, date]
    );
  };

  const getUTCOrderTime = () => {
    if (!orderTime) return "";

    const now = new Date();
    const [hours, minutes] = orderTime.split(":").map(Number);

    const localDateTime = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate(),
      hours,
      minutes
    );

    return localDateTime.toISOString();
  };

  const getPayload = () => {
    if (subscriptionType === "once") {
      return {
        subscription_type: undefined,
        subscription_weekly: undefined,
        subscription_monthly: undefined,
        order_time: undefined,
      };
    }
    return {
      subscription_type: subscriptionType,
      subscription_weekly: subscriptionType === "weekly" ? weeklyDays : [],
      subscription_monthly: subscriptionType === "monthly" ? monthlyDates : [],
      order_time: getUTCOrderTime(),
    };
  };

  // Payload update
  useEffect(() => {
    onChange?.(getPayload());
  }, [subscriptionType, weeklyDays, monthlyDates, orderTime]);

  // Hide delivery time only when type changes
  useEffect(() => {
    onHideDeliveryTime?.(subscriptionType !== "once");
  }, [subscriptionType]);

  return (
    <Card className="border-gray-100 shadow-sm overflow-hidden">
      <div className="p-5">
        <h3 className="font-semibold text-gray-900 mb-4 text-base">
          Place order on
        </h3>

        {/* Subscription Type Selection */}
        <div className="grid grid-cols-2 gap-3 mb-4">
          {subscriptionOptions.map((option) => {
            const Icon = option.icon;
            const isSelected = subscriptionType === option.value;
            return (
              <div
                key={option.value}
                onClick={() => setSubscriptionType(option.value)}
                className={`cursor-pointer border rounded-xl p-4 flex flex-col items-center justify-center gap-2 transition-all ${isSelected
                  ? "border-primary bg-brand-50 text-primary"
                  : "border-gray-200 hover:border-brand-200 text-gray-600"
                  }`}
              >
                <Icon size={20} />
                <span className="text-sm font-medium">{option.label}</span>
              </div>
            );
          })}
        </div>

        {/* Weekly Selection */}
        {subscriptionType === "weekly" && (
          <div className="mt-5 pt-5 border-t border-gray-100">
            <h4 className="text-sm font-medium mb-3 text-gray-800">
              Select days
            </h4>
            <div className="flex flex-wrap gap-2">
              {weekDays.map((day) => (
                <Button
                  key={day.value}
                  type="button"
                  onClick={() => toggleWeeklyDay(day.value)}
                  className={`w-12 h-12 flex items-center justify-center rounded-lg text-xs font-medium transition-all
            ${weeklyDays.includes(day.value)
                      ? "bg-primary text-white hover:bg-primary/90 shadow-sm"
                      : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                    }`}
                >
                  {day.label}
                </Button>
              ))}
            </div>
          </div>
        )}


        {/* Monthly Selection */}
        {subscriptionType === "monthly" && (
          <div className="mt-5 pt-5 border-t border-gray-100">
            <h4 className="text-sm font-medium mb-3 text-gray-800">
              Select dates
            </h4>
            <div className="grid grid-cols-7 gap-2">
              {Array.from({ length: 31 }, (_, i) => i + 1).map((date) => (
                <Button
                  key={date}
                  type="button"
                  onClick={() => toggleMonthlyDate(date)}
                  className={`w-10 h-10 flex items-center justify-center rounded-lg text-xs font-medium transition-all
            ${monthlyDates.includes(date)
                      ? "bg-primary text-white hover:bg-primary/90 shadow-sm"
                      : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                    }`}
                >
                  {date}
                </Button>
              ))}
            </div>
          </div>
        )}

        {/* Order Time */}
        {subscriptionType !== "once" && (
          <div className="mt-5 pt-5 border-t border-gray-100">
            <h4 className="text-sm font-medium mb-3 text-gray-800">
              Select Order Time
            </h4>
            <div className="relative max-w-[200px]">
              <Input
                type="time"
                value={orderTime}
                onChange={(e) => setOrderTime(e.target.value)}
                className="w-full h-11 text-sm rounded-lg border border-gray-300 focus:border-primary focus:ring-2 focus:ring-primary/40"
              />
            </div>
          </div>
        )}
      </div>
    </Card>
  );
};

export default SchedulingComponent;
