"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import {
  clearBookingWizardId,
  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";

type PreviewConfig = {
  name: string;
  services: { title: string; price: number }[];
  weeklySchedule: { day: string; ranges: { start_time: string; end_time: string }[] }[];
  holidayDates: string[];
  depositRequired: boolean;
  weeklyRepeatCount?: number | null;
};

function BookingPreviewPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const configId = useBookingWizardId();
  const [config, setConfig] = useState<PreviewConfig | null>(null);

  useEffect(() => {
    if (!configId) return;
    request<{ config: PreviewConfig }>("GET", `/bookings/${configId}`).then(
      (res) => setConfig(res?.config || null)
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [configId]);

  const handleSubmit = async () => {
    if (!configId) return;
    try {
      await request("POST", `/bookings/${configId}/submit`, {});
      clearBookingWizardId();
      toast.success(t("booking.submitSuccess"));
      router.push("/settings/booking");
    } 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 pb-28">
          <AuthPageContent>
            <span className="mb-4 text-xl font-bold">
              {t("booking.previewTitle")}
            </span>

            {!config ? (
              <p className="py-8 text-sm text-neutral-500">
                {t("common.loading")}
              </p>
            ) : (
              <div className="flex w-full max-w-sm flex-col gap-4 text-sm">
                <div className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                  <p className="text-xs text-neutral-500">
                    {t("booking.nameTitle")}
                  </p>
                  <p className="font-bold">{config.name}</p>
                </div>

                <div className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                  <p className="mb-2 text-xs text-neutral-500">
                    {t("booking.servicesTitle")}
                  </p>
                  {config.services.map((s) => (
                    <div key={s.title} className="flex justify-between py-1">
                      <span>{s.title}</span>
                      <span className="text-neutral-500">
                        {Number(s.price).toLocaleString()} {t("settings.toman")}
                      </span>
                    </div>
                  ))}
                </div>

                <div className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                  <p className="mb-2 text-xs text-neutral-500">
                    {t("booking.scheduleTitle")}
                  </p>
                  {config.weeklySchedule.map((entry) => (
                    <div key={entry.day} className="py-1">
                      <span className="font-semibold">
                        {t(`shops.days.${entry.day}`)}:
                      </span>{" "}
                      {entry.ranges
                        .map((r) => `${r.start_time}-${r.end_time}`)
                        .join("، ")}
                    </div>
                  ))}
                  {config.holidayDates.length > 0 && (
                    <p className="mt-2 text-xs text-neutral-500">
                      {t("booking.holidaysTitle")}: {config.holidayDates.join("، ")}
                    </p>
                  )}
                  {config.weeklyRepeatCount ? (
                    <p className="mt-2 text-xs text-neutral-500">
                      {t("booking.weeklyRepeatCountTitle")}: {config.weeklyRepeatCount}
                    </p>
                  ) : null}
                  <p className="mt-2 text-xs text-neutral-500">
                    {t("booking.depositTitle")}:{" "}
                    {config.depositRequired ? t("common.yes") : t("common.no")}
                  </p>
                </div>
              </div>
            )}
          </AuthPageContent>
          <AuthFormFooter className="sticky bottom-[calc(5.5rem+env(safe-area-inset-bottom))] z-20 mt-0 bg-background/95 py-3 backdrop-blur-sm">
            <AuthNextButton
              type="button"
              loading={loading}
              disabled={loading || !config}
              onClick={handleSubmit}
            >
              {t("booking.submitConfig")}
            </AuthNextButton>
          </AuthFormFooter>
        </div>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default BookingPreviewPage;
