"use client";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { staticIconUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { saveBookingWizardId } from "@/hooks/useBookingWizardId";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type BookingConfigSummary = {
  _id: string;
  name: string;
  services: { title: string }[];
  status: "draft" | "active" | "inactive";
};

function BookingSettingsPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request } = useAxios();
  const [configs, setConfigs] = useState<BookingConfigSummary[] | null>(null);

  const load = () => {
    request<{ configs: BookingConfigSummary[] }>("GET", "/bookings/mine").then(
      (res) => setConfigs(res?.configs || [])
    );
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const openConfig = (config: BookingConfigSummary) => {
    saveBookingWizardId(config._id);
    router.push("/settings/booking/new/services?edit=1");
  };

  const toggleStatus = async (
    e: React.MouseEvent,
    config: BookingConfigSummary
  ) => {
    e.stopPropagation();
    const nextStatus = config.status === "active" ? "inactive" : "active";
    try {
      await request("PATCH", `/bookings/${config._id}/status`, {
        status: nextStatus,
      });
      setConfigs(
        (prev) =>
          prev?.map((c) =>
            c._id === config._id ? { ...c, status: nextStatus } : c
          ) || null
      );
    } catch {
      toast.error(t("shops.unknownError"));
    }
  };

  const statusColor = (status: string) =>
    status === "active"
      ? "#008D0E"
      : status === "inactive"
        ? "#BA4141"
        : "#BFAF19";

  const statusLabel = (status: string) =>
    status === "active"
      ? t("booking.statusActive")
      : status === "inactive"
        ? t("booking.statusInactive")
        : t("booking.statusDraft");

  return (
    <LocalePageShell>
      <Container>
        <div className="flex items-center justify-between">
          <PageTitle>{t("settings.nav.booking")}</PageTitle>
          <Link
            href="/settings/booking/new/name"
            aria-label={t("booking.addNew")}
            className="p-2"
          >
            <Image
              width={24}
              height={24}
              alt=""
              src={staticIconUrl("/images/icons/add.svg")}
              className="dark:brightness-0 dark:invert"
            />
          </Link>
        </div>
        <div className="text-xs md:text-sm">
          <UserDetails />

          <div className="mt-8 flex flex-col gap-3">
            {configs === null ? (
              <p className="py-8 text-center text-gray-500">
                {t("common.loading")}
              </p>
            ) : configs.length === 0 ? (
              <p className="py-8 text-center text-gray-500">
                {t("booking.emptyList")}
              </p>
            ) : (
              configs.map((config) => (
                <button
                  key={config._id}
                  type="button"
                  onClick={() => openConfig(config)}
                  className="flex w-full items-center justify-between rounded-3xl border border-neutral-200 p-4 text-right dark:border-neutral-700"
                >
                  <div>
                    <p className="font-bold">{config.name}</p>
                    <p className="mt-1 text-neutral-500">
                      {t("booking.servicesCount", {
                        count: config.services?.length || 0,
                      })}
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={(e) => toggleStatus(e, config)}
                    disabled={config.status === "draft"}
                    style={{ color: statusColor(config.status) }}
                    className="font-semibold"
                  >
                    {statusLabel(config.status)}
                  </button>
                </button>
              ))
            )}
          </div>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default BookingSettingsPage;
