"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 BoldIcon from "@/components/ui/BoldIcon";
import useAxios from "@/hooks/useAxios";
import { useShopWizardId } from "@/hooks/useShopWizardId";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const DELIVERY_METHODS = [
  "post",
  "tipax",
  "chapar",
  "intercity_freight",
  "courier",
  "own_vehicle",
] as const;

const METHOD_ICON: Record<(typeof DELIVERY_METHODS)[number], string> = {
  post: "send",
  tipax: "truck-fast",
  chapar: "truck-tick",
  intercity_freight: "truck",
  courier: "car",
  own_vehicle: "smart-car",
};

type DeliveryMethod = (typeof DELIVERY_METHODS)[number];

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

  const [enabledMethods, setEnabledMethods] = useState<Record<DeliveryMethod, boolean>>({
    post: false,
    tipax: false,
    chapar: false,
    intercity_freight: false,
    courier: false,
    own_vehicle: false,
  });
  const [costs, setCosts] = useState<Record<DeliveryMethod, string>>({
    post: "",
    tipax: "",
    chapar: "",
    intercity_freight: "",
    courier: "",
    own_vehicle: "",
  });
  const [codAvailable, setCodAvailable] = useState(false);
  const [sameDayAvailable, setSameDayAvailable] = useState(false);
  const [freeShippingThreshold, setFreeShippingThreshold] = useState("");
  const [estimatedDeliveryText, setEstimatedDeliveryText] = useState("");

  useEffect(() => {
    if (!shopId) return;
    request<{
      shop: {
        shipping_methods?: { method: DeliveryMethod; cost: number }[];
        cod_available?: boolean;
        same_day_available?: boolean;
        free_shipping_threshold?: number | null;
        estimated_delivery_text?: string | null;
      };
    }>("GET", `/shops/${shopId}`).then((res) => {
      const shop = res?.shop;
      if (!shop) return;
      if (shop.shipping_methods?.length) {
        const nextEnabled = { ...enabledMethods };
        const nextCosts = { ...costs };
        shop.shipping_methods.forEach((m) => {
          nextEnabled[m.method] = true;
          nextCosts[m.method] = String(m.cost || "");
        });
        setEnabledMethods(nextEnabled);
        setCosts(nextCosts);
      }
      setCodAvailable(Boolean(shop.cod_available));
      setSameDayAvailable(Boolean(shop.same_day_available));
      if (shop.free_shipping_threshold) {
        setFreeShippingThreshold(String(shop.free_shipping_threshold));
      }
      if (shop.estimated_delivery_text) {
        setEstimatedDeliveryText(shop.estimated_delivery_text);
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shopId]);

  const toggleMethod = (method: DeliveryMethod) => {
    setEnabledMethods((prev) => ({ ...prev, [method]: !prev[method] }));
  };

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

    const shipping_methods = DELIVERY_METHODS.filter(
      (method) => enabledMethods[method]
    ).map((method) => ({
      method,
      cost: Number(costs[method]) || 0,
      enabled: true,
    }));

    if (shipping_methods.length === 0) {
      toast.error(t("shops.shippingMethodRequired"));
      return;
    }

    try {
      await request("PATCH", `/shops/${shopId}/shipping`, {
        shipping_methods,
        cod_available: codAvailable,
        same_day_available: sameDayAvailable,
        free_shipping_threshold: freeShippingThreshold
          ? Number(freeShippingThreshold)
          : null,
        estimated_delivery_text: estimatedDeliveryText || null,
      });
      router.push("/shops/new/location");
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!shopId) return null;

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

          <div className="flex w-full max-w-sm flex-col gap-3">
            <div className="rounded-3xl border border-neutral-200 p-3 dark:border-neutral-700">
              <p className="mb-3 flex items-center gap-2 text-sm font-semibold">
                <BoldIcon name="box" size={18} tinted />
                {t("shops.activeShippingMethods")}
              </p>
              <div className="flex flex-col gap-2">
                {DELIVERY_METHODS.map((method) => (
                  <div
                    key={method}
                    className="flex flex-col gap-2 rounded-2xl border border-neutral-100 p-2.5 dark:border-neutral-800"
                  >
                    <div className="flex items-center justify-between">
                      <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[method]} size={18} tinted />
                        </span>
                        <span className="text-sm font-medium">
                          {t(`shops.shippingMethods.${method}`)}
                        </span>
                      </div>
                      <ToggleSwitch
                        checked={enabledMethods[method]}
                        onChange={() => toggleMethod(method)}
                        ariaLabel={t(`shops.shippingMethods.${method}`)}
                      />
                    </div>
                    {enabledMethods[method] && (
                      <div className="flex items-center gap-2">
                        <RoundedInput
                          type="number"
                          inputMode="numeric"
                          placeholder={t("shops.shippingCostPlaceholder")}
                          className="flex-1 text-sm"
                          value={costs[method]}
                          onChange={(e) =>
                            setCosts((prev) => ({ ...prev, [method]: e.target.value }))
                          }
                        />
                        <span className="text-xs text-neutral-500">
                          {t("settings.toman")}
                        </span>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>

            <div className="rounded-3xl border border-neutral-200 p-3 dark:border-neutral-700">
              <p className="mb-3 text-sm font-semibold">
                {t("shops.supplementarySettings")}
              </p>
              <div className="flex flex-col gap-2">
                <div className="flex items-center justify-between rounded-2xl border border-neutral-100 p-3 dark:border-neutral-800">
                  <span className="text-sm">{t("shops.codAvailable")}</span>
                  <ToggleSwitch
                    checked={codAvailable}
                    onChange={setCodAvailable}
                    ariaLabel={t("shops.codAvailable")}
                  />
                </div>
                <div className="flex items-center justify-between rounded-2xl border border-neutral-100 p-3 dark:border-neutral-800">
                  <span className="text-sm">{t("shops.sameDayAvailable")}</span>
                  <ToggleSwitch
                    checked={sameDayAvailable}
                    onChange={setSameDayAvailable}
                    ariaLabel={t("shops.sameDayAvailable")}
                  />
                </div>

                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  className="mt-1"
                  placeholder={t("shops.freeShippingThresholdPlaceholder")}
                  value={freeShippingThreshold}
                  onChange={(e) => setFreeShippingThreshold(e.target.value)}
                />
                <RoundedInput
                  type="text"
                  placeholder={t("shops.estimatedDeliveryPlaceholder")}
                  value={estimatedDeliveryText}
                  onChange={(e) => setEstimatedDeliveryText(e.target.value)}
                />
              </div>
            </div>
          </div>
        </AuthPageContent>
        <AuthFormFooter>
          <AuthNextButton
            type="button"
            loading={loading}
            disabled={loading}
            onClick={handleSubmit}
          >
            {t("shops.saveAndContinue")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ShopShippingPage;
