"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import RoundedInput from "@/components/elements/RoundedInput";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import ToggleSwitch from "@/components/shops/ToggleSwitch";
import TimeSelect from "@/components/shops/TimeSelect";
import useAxios from "@/hooks/useAxios";
import { useShopWizardId } from "@/hooks/useShopWizardId";
import Image from "next/image";
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];

function ShopContactPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const shopId = useShopWizardId();

  const [contact, setContact] = useState({
    landline: "",
    mobile: "",
    telegram: "",
    whatsapp: "",
    instagram: "",
  });

  const [enabledDays, setEnabledDays] = useState<Record<Day, boolean>>({
    sat: false,
    sun: false,
    mon: false,
    tue: false,
    wed: false,
    thu: false,
    fri: false,
  });
  const [times, setTimes] = useState<
    Record<Day, { start: string; end: string }>
  >({
    sat: { start: "", end: "" },
    sun: { start: "", end: "" },
    mon: { start: "", end: "" },
    tue: { start: "", end: "" },
    wed: { start: "", end: "" },
    thu: { start: "", end: "" },
    fri: { start: "", end: "" },
  });

  const toggleDay = (day: Day) => {
    setEnabledDays((prev) => ({ ...prev, [day]: !prev[day] }));
  };

  useEffect(() => {
    if (!shopId) return;
    request<{
      shop: {
        contact?: Record<string, string | null>;
        response_schedule?: { day: Day; start_time: string | null; end_time: string | null }[];
      };
    }>("GET", `/shops/${shopId}`).then((res) => {
      const shop = res?.shop;
      if (!shop) return;
      if (shop.contact) {
        setContact((prev) => ({
          landline: shop.contact?.landline || prev.landline,
          mobile: shop.contact?.mobile || prev.mobile,
          telegram: shop.contact?.telegram || prev.telegram,
          whatsapp: shop.contact?.whatsapp || prev.whatsapp,
          instagram: shop.contact?.instagram || prev.instagram,
        }));
      }
      if (shop.response_schedule?.length) {
        const nextEnabled = { ...enabledDays };
        const nextTimes = { ...times };
        shop.response_schedule.forEach((item) => {
          nextEnabled[item.day] = true;
          nextTimes[item.day] = {
            start: item.start_time || "",
            end: item.end_time || "",
          };
        });
        setEnabledDays(nextEnabled);
        setTimes(nextTimes);
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shopId]);

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

    const hasAnyContact = Object.values(contact).some((v) => v.trim());
    if (!hasAnyContact) {
      toast.error(t("shops.contactRequired"));
      return;
    }

    const response_schedule = DAYS.filter((day) => enabledDays[day]).map(
      (day) => ({
        day,
        start_time: times[day].start || null,
        end_time: times[day].end || null,
      })
    );

    try {
      await request("PATCH", `/shops/${shopId}/contact`, {
        contact,
        response_schedule,
      });
      router.push("/shops/new/preview");
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!shopId) return null;

  const contactFields: {
    key: keyof typeof contact;
    icon: string;
    placeholder: string;
    maxLength?: number;
  }[] = [
    {
      key: "landline",
      icon: "/images/icons/vuesax/bold/call.svg",
      placeholder: t("shops.landlinePlaceholder"),
      maxLength: 11,
    },
    {
      key: "mobile",
      icon: "/images/icons/vuesax/bold/mobile.svg",
      placeholder: t("billboards.form.mobile"),
      maxLength: 11,
    },
    {
      key: "telegram",
      icon: "/images/icons/telegram.svg",
      placeholder: t("billboards.form.telegram"),
    },
    {
      key: "whatsapp",
      icon: "/images/icons/vuesax/bold/whatsapp.svg",
      placeholder: t("billboards.form.whatsapp"),
      maxLength: 11,
    },
    {
      key: "instagram",
      icon: "/images/icons/vuesax/bold/instagram.svg",
      placeholder: t("billboards.form.instagram"),
    },
  ];

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <AuthPageContent>
          <span className="text-xl font-bold mb-4">{t("shops.contactTitle")}</span>

          <div className="flex w-full max-w-sm flex-col gap-2">
            {contactFields.map((field) => (
              <div key={field.key} className="relative">
                <span className="absolute right-4 top-1/2 -translate-y-1/2">
                  <Image src={field.icon} width={20} height={20} alt="" />
                </span>
                <RoundedInput
                  type="text"
                  placeholder={field.placeholder}
                  maxLength={field.maxLength}
                  className="pr-11"
                  value={contact[field.key]}
                  onChange={(e) =>
                    setContact((prev) => ({ ...prev, [field.key]: e.target.value }))
                  }
                />
              </div>
            ))}

            <p className="mt-6 mb-1 text-sm font-bold">
              {t("shops.responseScheduleTitle")}
            </p>
            <div className="flex flex-col gap-2 rounded-3xl border border-neutral-200 p-3 dark:border-neutral-700">
              {DAYS.map((day) => (
                <div
                  key={day}
                  className="flex items-center justify-between gap-2 rounded-2xl border border-neutral-100 p-2.5 dark:border-neutral-800"
                >
                  <div className="flex items-center gap-2">
                    <Image
                      src="/images/icons/vuesax/bold/calendar.svg"
                      width={20}
                      height={20}
                      alt=""
                      className={enabledDays[day] ? "" : "opacity-40 grayscale"}
                    />
                    <span className="w-16 shrink-0 text-sm">
                      {t(`shops.days.${day}`)}
                    </span>
                  </div>

                  {enabledDays[day] && (
                    <div className="flex items-center gap-1">
                      <TimeSelect
                        ariaLabel={t("shops.responseEndTime")}
                        value={times[day].end}
                        onChange={(value) =>
                          setTimes((prev) => ({
                            ...prev,
                            [day]: { ...prev[day], end: value },
                          }))
                        }
                      />
                      <span className="text-xs">-</span>
                      <TimeSelect
                        ariaLabel={t("shops.responseStartTime")}
                        value={times[day].start}
                        onChange={(value) =>
                          setTimes((prev) => ({
                            ...prev,
                            [day]: { ...prev[day], start: value },
                          }))
                        }
                      />
                    </div>
                  )}

                  <ToggleSwitch
                    checked={enabledDays[day]}
                    onChange={() => toggleDay(day)}
                    ariaLabel={t(`shops.days.${day}`)}
                  />
                </div>
              ))}
            </div>
          </div>
        </AuthPageContent>
        <AuthFormFooter>
          <AuthNextButton
            type="button"
            loading={loading}
            disabled={loading}
            onClick={handleSubmit}
          >
            {t("shops.saveAndContinue")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ShopContactPage;
