"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import TimeSelect from "@/components/shops/TimeSelect";
import ToggleSwitch from "@/components/shops/ToggleSwitch";
import useAxios from "@/hooks/useAxios";
import { useBookingWizardId } from "@/hooks/useBookingWizardId";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const DAYS = ["sat", "sun", "mon", "tue", "wed", "thu", "fri"] as const;
type Day = (typeof DAYS)[number];

type TimeRange = { start_time: string; end_time: string };

type WeeklyScheduleEntry = { day: Day; ranges: TimeRange[] };

function BookingSchedulePage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const configId = useBookingWizardId();

  const [enabledDays, setEnabledDays] = useState<Record<Day, boolean>>(
    () => Object.fromEntries(DAYS.map((d) => [d, false])) as Record<Day, boolean>
  );
  const [ranges, setRanges] = useState<Record<Day, TimeRange[]>>(
    () =>
      Object.fromEntries(
        DAYS.map((d): [Day, TimeRange[]] => [d, []])
      ) as Record<Day, TimeRange[]>
  );
  const [holidayDates, setHolidayDates] = useState<string[]>([]);
  const [newHoliday, setNewHoliday] = useState("");
  const [depositRequired, setDepositRequired] = useState(true);
  const [weeklyRepeatCount, setWeeklyRepeatCount] = useState("");

  useEffect(() => {
    if (!configId) return;
    request<{
      config: {
        weeklySchedule?: WeeklyScheduleEntry[];
        holidayDates?: string[];
        depositRequired?: boolean;
        weeklyRepeatCount?: number | null;
      };
    }>("GET", `/bookings/${configId}`).then((res) => {
      const config = res?.config;
      if (!config) return;
      if (config.weeklySchedule?.length) {
        const nextEnabled = { ...enabledDays };
        const nextRanges = { ...ranges };
        config.weeklySchedule.forEach((entry) => {
          nextEnabled[entry.day] = true;
          nextRanges[entry.day] = entry.ranges || [];
        });
        setEnabledDays(nextEnabled);
        setRanges(nextRanges);
      }
      if (config.holidayDates?.length) {
        setHolidayDates(
          config.holidayDates.map((d) => new Date(d).toISOString().slice(0, 10))
        );
      }
      setDepositRequired(Boolean(config.depositRequired));
      setWeeklyRepeatCount(
        config.weeklyRepeatCount ? String(config.weeklyRepeatCount) : ""
      );
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [configId]);

  const toggleDay = (day: Day, checked: boolean) => {
    setEnabledDays((prev) => ({ ...prev, [day]: checked }));
    if (checked && ranges[day].length === 0) {
      setRanges((prev) => ({ ...prev, [day]: [{ start_time: "", end_time: "" }] }));
    }
  };

  const addRange = (day: Day) => {
    setRanges((prev) => ({
      ...prev,
      [day]: [...prev[day], { start_time: "", end_time: "" }],
    }));
  };

  const removeRange = (day: Day, index: number) => {
    setRanges((prev) => ({
      ...prev,
      [day]: prev[day].filter((_, i) => i !== index),
    }));
  };

  const updateRange = (
    day: Day,
    index: number,
    field: "start_time" | "end_time",
    value: string
  ) => {
    setRanges((prev) => ({
      ...prev,
      [day]: prev[day].map((r, i) => (i === index ? { ...r, [field]: value } : r)),
    }));
  };

  const addHoliday = () => {
    if (!newHoliday || holidayDates.includes(newHoliday)) return;
    setHolidayDates((prev) => [...prev, newHoliday].sort());
    setNewHoliday("");
  };

  const removeHoliday = (date: string) => {
    setHolidayDates((prev) => prev.filter((d) => d !== date));
  };

  const handleSubmit = async () => {
    if (!configId) return;

    const weeklySchedule: WeeklyScheduleEntry[] = DAYS.filter(
      (day) => enabledDays[day] && ranges[day].length > 0
    ).map((day) => ({
      day,
      ranges: ranges[day].filter((r) => r.start_time && r.end_time),
    })).filter((entry) => entry.ranges.length > 0);

    if (weeklySchedule.length === 0) {
      toast.error(t("booking.scheduleRequired"));
      return;
    }

    const trimmedRepeatCount = weeklyRepeatCount.trim();
    if (trimmedRepeatCount && (!/^\d+$/.test(trimmedRepeatCount) || Number(trimmedRepeatCount) < 1)) {
      toast.error(t("booking.weeklyRepeatCountInvalid"));
      return;
    }

    try {
      await request("PATCH", `/bookings/${configId}/schedule`, {
        weeklySchedule,
        holidayDates,
        depositRequired,
        weeklyRepeatCount: trimmedRepeatCount ? Number(trimmedRepeatCount) : null,
      });
      router.push("/settings/booking/new/preview");
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <div className="flex w-full flex-1 flex-col items-center overflow-y-auto pb-28">
          <AuthPageContent>
            <span className="mb-4 text-xl font-bold">
              {t("booking.scheduleTitle")}
            </span>

            <div className="flex w-full max-w-sm flex-col gap-3">
              {DAYS.map((day) => (
                <div
                  key={day}
                  className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700"
                >
                  <div className="flex items-center justify-between">
                    <span className="font-semibold">{t(`shops.days.${day}`)}</span>
                    <ToggleSwitch
                      checked={enabledDays[day]}
                      onChange={(checked) => toggleDay(day, checked)}
                      ariaLabel={t(`shops.days.${day}`)}
                    />
                  </div>

                  {enabledDays[day] && (
                    <div className="mt-3 flex flex-col gap-2">
                      {ranges[day].map((range, index) => (
                        <div key={index} className="flex items-center gap-2">
                          <TimeSelect
                            value={range.start_time}
                            onChange={(v) => updateRange(day, index, "start_time", v)}
                            ariaLabel={t("booking.startTime")}
                          />
                          <span>{t("booking.until")}</span>
                          <TimeSelect
                            value={range.end_time}
                            onChange={(v) => updateRange(day, index, "end_time", v)}
                            ariaLabel={t("booking.endTime")}
                          />
                          <button
                            type="button"
                            onClick={() => removeRange(day, index)}
                            className="mr-1 text-xs text-red-500"
                          >
                            {t("booking.removeRange")}
                          </button>
                        </div>
                      ))}
                      <button
                        type="button"
                        onClick={() => addRange(day)}
                        className="self-start text-xs font-semibold text-[#0095f6]"
                      >
                        + {t("booking.addRange")}
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>

            <div className="mt-6 w-full max-w-sm rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
              <span className="font-semibold">{t("booking.weeklyRepeatCountTitle")}</span>
              <p className="mt-1 text-xs text-neutral-500">
                {t("booking.weeklyRepeatCountHint")}
              </p>
              <input
                type="number"
                min={1}
                inputMode="numeric"
                value={weeklyRepeatCount}
                onChange={(e) => setWeeklyRepeatCount(e.target.value)}
                placeholder={t("booking.weeklyRepeatCountPlaceholder")}
                className="mt-2 w-24 rounded-xl border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-50"
              />
            </div>

            <div className="mt-6 w-full max-w-sm">
              <span className="mb-2 block font-semibold">
                {t("booking.holidaysTitle")}
              </span>
              <div className="flex items-center gap-2">
                <input
                  type="date"
                  value={newHoliday}
                  onChange={(e) => setNewHoliday(e.target.value)}
                  className="flex-1 rounded-xl border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-50"
                />
                <button
                  type="button"
                  onClick={addHoliday}
                  className="rounded-xl bg-neutral-100 px-3 py-2 text-sm font-semibold dark:bg-neutral-800"
                >
                  {t("common.add")}
                </button>
              </div>
              {holidayDates.length > 0 && (
                <div className="mt-2 flex flex-wrap gap-2">
                  {holidayDates.map((date) => (
                    <span
                      key={date}
                      className="flex items-center gap-1 rounded-full bg-neutral-100 px-3 py-1 text-xs dark:bg-neutral-800"
                    >
                      {date}
                      <button
                        type="button"
                        onClick={() => removeHoliday(date)}
                        className="text-red-500"
                      >
                        ×
                      </button>
                    </span>
                  ))}
                </div>
              )}
            </div>

            <div className="mt-6 flex w-full max-w-sm items-center justify-between rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
              <span className="font-semibold">{t("booking.depositTitle")}</span>
              <ToggleSwitch
                checked={depositRequired}
                onChange={setDepositRequired}
                ariaLabel={t("booking.depositTitle")}
              />
            </div>
            {depositRequired && (
              <p className="mt-2 max-w-sm text-xs text-neutral-500">
                {t("booking.depositHint")}
              </p>
            )}
          </AuthPageContent>
          <AuthFormFooter className="fixed inset-x-0 bottom-[calc(5.5rem+env(safe-area-inset-bottom))] z-20 mx-auto mt-0 w-full max-w-xl bg-background/95 px-4 py-3 backdrop-blur-sm">
            <AuthNextButton
              type="button"
              loading={loading}
              disabled={loading || !configId}
              onClick={handleSubmit}
            >
              {t("shops.saveAndContinue")}
            </AuthNextButton>
          </AuthFormFooter>
        </div>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default BookingSchedulePage;
