"use client";

import LocalePageShell from "@/components/i18n/LocalePageShell";
import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import BoldIcon from "@/components/ui/BoldIcon";
import useAxios from "@/hooks/useAxios";
import { useShopWizardId } from "@/hooks/useShopWizardId";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import { cn } from "@/lib/utils";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Map, { Marker } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const METHOD_ICON: Record<string, string> = {
  post: "send",
  tipax: "truck-fast",
  chapar: "truck-tick",
  intercity_freight: "truck",
  courier: "car",
  own_vehicle: "smart-car",
};

const CONTACT_CHANNELS: {
  key: "mobile" | "landline" | "telegram" | "whatsapp" | "instagram";
  icon: string;
  color: string;
}[] = [
  { key: "mobile", icon: "/images/icons/vuesax/bold/mobile.svg", color: "bg-green-500" },
  { key: "landline", icon: "/images/icons/vuesax/bold/call.svg", color: "bg-orange-500" },
  { key: "telegram", icon: "/images/icons/telegram.svg", color: "bg-sky-500" },
  { key: "whatsapp", icon: "/images/icons/vuesax/bold/whatsapp.svg", color: "bg-emerald-600" },
  {
    key: "instagram",
    icon: "/images/icons/vuesax/bold/instagram.svg",
    color: "bg-gradient-to-tr from-yellow-400 via-pink-500 to-purple-600",
  },
];

type ShopPreview = {
  name: string;
  logo?: string | null;
  shipping_methods?: { method: string; cost: number }[];
  cod_available?: boolean;
  same_day_available?: boolean;
  free_shipping_threshold?: number | null;
  estimated_delivery_text?: string | null;
  has_physical_location?: boolean;
  province?: { name?: string } | null;
  city?: { name?: string } | null;
  neighbourhood?: string | null;
  address?: string | null;
  lat?: string | null;
  lng?: string | null;
  contact?: {
    mobile?: string | null;
    landline?: string | null;
    telegram?: string | null;
    whatsapp?: string | null;
    instagram?: string | null;
  } | null;
  response_schedule?: { day: string; start_time: string | null; end_time: string | null }[];
};

function ShopPreviewPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const shopId = useShopWizardId();
  const [shop, setShop] = useState<ShopPreview | null>(null);

  useEffect(() => {
    if (!shopId) return;
    request<{ shop: ShopPreview }>("GET", `/shops/${shopId}`)
      .then((res) => setShop(res?.shop || null))
      .catch(() => setShop(null));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shopId]);

  const handleSubmit = async () => {
    if (!shopId) return;
    try {
      await request("POST", `/shops/${shopId}/submit`, {});
      if (typeof window !== "undefined") {
        localStorage.removeItem("shop_wizard_shop_id");
      }
      toast.success(t("shops.submitSuccess"));
      router.push("/settings/shop/list");
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!shopId || !shop) return null;

  const orderInfoRows = [
    shop.free_shipping_threshold
      ? {
          key: "minOrder",
          label: t("shops.previewMinOrder"),
          value: `${shop.free_shipping_threshold.toLocaleString()} ${t("settings.toman")}`,
        }
      : null,
    shop.estimated_delivery_text
      ? { key: "delivery", label: t("shops.previewDeliveryTime"), value: shop.estimated_delivery_text }
      : null,
    shop.cod_available
      ? { key: "cod", label: t("shops.codAvailable"), value: t("shops.previewYes") }
      : null,
    shop.same_day_available
      ? { key: "sameDay", label: t("shops.sameDayAvailable"), value: t("shops.previewYes") }
      : null,
  ].filter(Boolean) as { key: string; label: string; value: string }[];

  const hasLocationInfo =
    shop.has_physical_location &&
    (shop.address || shop.neighbourhood || shop.city?.name || shop.province?.name);
  const hasMap = shop.has_physical_location && shop.lat && shop.lng;

  return (
    <LocalePageShell>
      <Container>
        <div className="mx-auto flex w-full max-w-sm flex-col items-center gap-5 rounded-3xl bg-white p-6 text-center shadow-md dark:bg-neutral-900">
          <h1 className="text-xl font-bold">{t("shops.previewTitle")}</h1>

          {shop.logo && (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={IMAGE_BASE_URL + shop.logo}
              alt={shop.name}
              className="h-32 w-32 rounded-2xl object-cover shadow-sm"
            />
          )}

          <p className="text-lg font-bold">{shop.name}</p>

          {shop.shipping_methods && shop.shipping_methods.length > 0 && (
            <div className="flex w-full flex-col gap-2 text-right">
              <p className="text-sm font-semibold">{t("shops.shippingTitle")}</p>
              <div className="flex flex-col gap-1.5 rounded-2xl border border-neutral-200 p-2.5 dark:border-neutral-700">
                {shop.shipping_methods.map((m) => (
                  <div key={m.method} className="flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                      <span className="flex h-8 w-8 items-center justify-center rounded-full bg-neutral-100 dark:bg-neutral-800">
                        <BoldIcon name={METHOD_ICON[m.method] || "box"} size={16} tinted />
                      </span>
                      <span className="text-xs font-medium">
                        {t(`shops.shippingMethods.${m.method}`)}
                      </span>
                    </div>
                    <span className="text-xs text-neutral-500">
                      {m.cost.toLocaleString()} {t("settings.toman")}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {orderInfoRows.length > 0 && (
            <div className="grid w-full grid-cols-2 gap-px overflow-hidden rounded-2xl border border-neutral-200 bg-neutral-200 dark:border-neutral-700 dark:bg-neutral-700">
              {orderInfoRows.map((row) => (
                <div
                  key={row.key}
                  className="flex flex-col items-center gap-0.5 bg-white p-2.5 dark:bg-neutral-900"
                >
                  <span className="text-[11px] text-neutral-400">{row.label}</span>
                  <span className="text-xs font-semibold">{row.value}</span>
                </div>
              ))}
            </div>
          )}

          {shop.contact &&
            CONTACT_CHANNELS.some((ch) => shop.contact?.[ch.key]) && (
              <div className="flex w-full flex-col gap-2 text-right">
                <p className="text-sm font-semibold">{t("shops.contactTitle")}</p>
                <div className="flex flex-wrap justify-center gap-2">
                  {CONTACT_CHANNELS.filter((ch) => shop.contact?.[ch.key]).map((ch) => (
                    <div
                      key={ch.key}
                      className="flex items-center gap-2 rounded-full bg-neutral-50 py-1 pl-3 pr-1 dark:bg-neutral-800"
                    >
                      <span
                        className={cn(
                          "flex h-7 w-7 shrink-0 items-center justify-center rounded-full",
                          ch.color
                        )}
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src={ch.icon} alt="" className="h-3.5 w-3.5 brightness-0 invert" />
                      </span>
                      <span className="text-xs font-medium" dir="ltr">
                        {shop.contact?.[ch.key]}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

          {shop.response_schedule && shop.response_schedule.length > 0 && (
            <div className="flex w-full flex-col gap-2 text-right">
              <p className="text-sm font-semibold">{t("shops.responseScheduleTitle")}</p>
              <div className="flex flex-col gap-1.5 rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                {shop.response_schedule.map((item) => (
                  <div key={item.day} className="flex items-center justify-between text-xs">
                    <span className="text-neutral-500" dir="ltr">
                      {item.start_time || "--:--"} - {item.end_time || "--:--"}
                    </span>
                    <span className="font-medium">{t(`shops.days.${item.day}`)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {hasLocationInfo && (
            <div className="flex w-full flex-col gap-2 text-right">
              {(shop.city?.name || shop.neighbourhood) && (
                <div className="flex flex-wrap justify-center gap-2">
                  {shop.city?.name && (
                    <span className="rounded-full border border-neutral-200 px-3 py-1 text-xs dark:border-neutral-700">
                      {shop.city.name}
                    </span>
                  )}
                  {shop.neighbourhood && (
                    <span className="rounded-full border border-neutral-200 px-3 py-1 text-xs dark:border-neutral-700">
                      {shop.neighbourhood}
                    </span>
                  )}
                </div>
              )}
              {shop.address && (
                <div className="w-full rounded-2xl border border-neutral-200 p-3 text-xs text-neutral-600 dark:border-neutral-700 dark:text-neutral-300">
                  {shop.address}
                </div>
              )}
              {hasMap && (
                <div className="w-full overflow-hidden rounded-2xl">
                  <Map
                    style={{ height: "150px" }}
                    initialViewState={{
                      longitude: Number(shop.lng),
                      latitude: Number(shop.lat),
                      zoom: 12,
                    }}
                    mapboxAccessToken="pk.eyJ1IjoiYWxkZjkyIiwiYSI6ImNscHh5ZG56dTByMXAycnJ2cDNmdDQ5M3YifQ.a_sUt1rLFMfA0jHrETcM7A"
                    mapStyle="mapbox://styles/mapbox/streets-v11"
                    interactive={false}
                  >
                    <Marker latitude={Number(shop.lat)} longitude={Number(shop.lng)} />
                  </Map>
                </div>
              )}
            </div>
          )}

          <RoundedButton
            type="button"
            onClick={handleSubmit}
            disabled={loading}
            className="mt-2 w-full max-w-[220px] border-2 border-neutral-200 bg-white text-neutral-900 dark:border-neutral-700 dark:bg-neutral-900 dark:text-white"
          >
            {loading ? t("common.loading") : t("shops.submitShop")}
          </RoundedButton>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default ShopPreviewPage;
