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

type VariantRow = {
  color: string | null;
  size: string | null;
  weight: string | null;
  price: string;
  discountPrice: string;
  stock: string;
};

function parseOptions(value: string): string[] {
  return value
    .split(",")
    .map((v) => v.trim())
    .filter(Boolean);
}

function rowKey(color: string | null, size: string | null, weight: string | null): string {
  return `${color || ""}|${size || ""}|${weight || ""}`;
}

function buildCombinations(
  colors: string[],
  sizes: string[],
  weights: string[]
): { color: string | null; size: string | null; weight: string | null }[] {
  const colorOptions = colors.length > 0 ? colors : [null];
  const sizeOptions = sizes.length > 0 ? sizes : [null];
  const weightOptions = weights.length > 0 ? weights : [null];

  const rows: { color: string | null; size: string | null; weight: string | null }[] = [];
  for (const color of colorOptions) {
    for (const size of sizeOptions) {
      for (const weight of weightOptions) {
        rows.push({ color, size, weight });
      }
    }
  }
  return rows;
}

function discountPercent(price: string, discountPrice: string): number | null {
  const original = Number(price);
  const discount = Number(discountPrice);
  if (!original || !discount || discount >= original) return null;
  return Math.round(((original - discount) / original) * 100);
}

function ProductVariantsPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ shopId: string }>();
  const shopId = params.shopId;
  const { request, loading } = useAxios();
  const listingId = useProductWizardId(shopId);

  const [colorsInput, setColorsInput] = useState("");
  const [sizesInput, setSizesInput] = useState("");
  const [weightsInput, setWeightsInput] = useState("");
  const [rows, setRows] = useState<VariantRow[]>([]);

  useEffect(() => {
    if (!listingId) return;
    request<{
      listing: {
        variants: {
          color: string | null;
          size: string | null;
          weight: string | null;
          price: number;
          discount_price: number | null;
          stock: number;
        }[];
      };
    }>("GET", `/shop-products/${listingId}`).then((res) => {
      const existing = res?.listing?.variants || [];
      if (existing.length === 0) return;
      setRows(
        existing.map((v) => ({
          color: v.color,
          size: v.size,
          weight: v.weight,
          price: String(v.price),
          discountPrice: v.discount_price ? String(v.discount_price) : "",
          stock: String(v.stock),
        }))
      );
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [listingId]);

  const handleGenerate = () => {
    const colors = parseOptions(colorsInput);
    const sizes = parseOptions(sizesInput);
    const weights = parseOptions(weightsInput);
    const combinations = buildCombinations(colors, sizes, weights);

    setRows((prev) => {
      const existingKeys = new Set(prev.map((r) => rowKey(r.color, r.size, r.weight)));
      const newRows = combinations
        .filter((c) => !existingKeys.has(rowKey(c.color, c.size, c.weight)))
        .map((c) => ({ ...c, price: "", discountPrice: "", stock: "" }));
      return [...prev, ...newRows];
    });

    setColorsInput("");
    setSizesInput("");
    setWeightsInput("");
  };

  const updateRow = (
    index: number,
    field: "price" | "discountPrice" | "stock",
    value: string
  ) => {
    setRows((prev) =>
      prev.map((row, i) => (i === index ? { ...row, [field]: value } : row))
    );
  };

  const removeRow = (index: number) => {
    setRows((prev) => prev.filter((_, i) => i !== index));
  };

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

    const variants = rows
      .filter((row) => row.price && Number(row.price) > 0)
      .map((row) => ({
        color: row.color,
        size: row.size,
        weight: row.weight,
        price: Number(row.price),
        discount_price:
          row.discountPrice && Number(row.discountPrice) < Number(row.price)
            ? Number(row.discountPrice)
            : null,
        stock: Number(row.stock) || 0,
      }));

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

    try {
      await request("PATCH", `/shop-products/${listingId}`, { variants });
      clearProductWizardId(shopId);
      toast.success(t("shops.productSaved"));
      router.push(`/shops/${shopId}`);
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!listingId) return null;

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

          <div className="flex w-full max-w-sm flex-col gap-2">
            <RoundedInput
              type="text"
              placeholder={t("shops.colorsPlaceholder")}
              value={colorsInput}
              onChange={(e) => setColorsInput(e.target.value)}
            />
            <RoundedInput
              type="text"
              placeholder={t("shops.sizesPlaceholder")}
              value={sizesInput}
              onChange={(e) => setSizesInput(e.target.value)}
            />
            <RoundedInput
              type="text"
              placeholder={t("shops.weightsPlaceholder")}
              value={weightsInput}
              onChange={(e) => setWeightsInput(e.target.value)}
            />
            <AuthNextButton type="button" className="mt-2" onClick={handleGenerate}>
              {t("shops.generateVariants")}
            </AuthNextButton>

            {rows.length > 0 && (
              <div className="mt-4 overflow-hidden rounded-2xl border border-neutral-200 dark:border-neutral-700">
                <div className="grid grid-cols-4 gap-1 bg-neutral-50 px-2 py-2 text-center text-[11px] font-bold dark:bg-neutral-800">
                  <span>{t("shops.colorColumn")}</span>
                  <span>{t("shops.sizeColumn")}</span>
                  <span>{t("shops.weightColumn")}</span>
                  <span>{t("shops.priceColumn")}</span>
                </div>

                {rows.map((row, index) => {
                  const percent = discountPercent(row.price, row.discountPrice);
                  return (
                    <div
                      key={rowKey(row.color, row.size, row.weight) + index}
                      className="border-t border-neutral-200 p-2 dark:border-neutral-700"
                    >
                      <div className="grid grid-cols-4 items-center gap-1">
                        <span className="truncate text-center text-xs">
                          {row.color || t("shops.defaultVariant")}
                        </span>
                        <span className="truncate text-center text-xs">
                          {row.size || t("shops.defaultVariant")}
                        </span>
                        <span className="truncate text-center text-xs">
                          {row.weight || "-"}
                        </span>
                        <button
                          type="button"
                          onClick={() => removeRow(index)}
                          aria-label={t("shops.removeVariant")}
                          className="mx-auto text-[10px] text-red-500"
                        >
                          {t("shops.removeVariant")}
                        </button>
                      </div>

                      <div className="mt-2 flex items-center gap-1.5">
                        <RoundedInput
                          type="number"
                          inputMode="numeric"
                          placeholder={t("shops.pricePlaceholder")}
                          className="text-xs"
                          value={row.price}
                          onChange={(e) => updateRow(index, "price", e.target.value)}
                        />
                        <RoundedInput
                          type="number"
                          inputMode="numeric"
                          placeholder={t("shops.discountPricePlaceholder")}
                          className="text-xs"
                          value={row.discountPrice}
                          onChange={(e) =>
                            updateRow(index, "discountPrice", e.target.value)
                          }
                        />
                        <RoundedInput
                          type="number"
                          inputMode="numeric"
                          placeholder={t("shops.stockPlaceholder")}
                          className="text-xs"
                          value={row.stock}
                          onChange={(e) => updateRow(index, "stock", e.target.value)}
                        />
                      </div>
                      {percent != null && (
                        <span className="mt-1 inline-block rounded-md bg-red-50 px-1.5 py-0.5 text-[10px] font-bold text-red-600 dark:bg-red-500/10">
                          {t("shops.discountPercentLabel", { percent })}
                        </span>
                      )}
                    </div>
                  );
                })}

                <div className="border-t border-neutral-200 bg-neutral-50 px-2 py-2 text-center text-xs font-bold dark:border-neutral-700 dark:bg-neutral-800">
                  {t("shops.totalVariantsLabel", { count: rows.length })}
                </div>
              </div>
            )}
          </div>
        </AuthPageContent>
        <AuthFormFooter>
          <AuthNextButton
            type="button"
            loading={loading}
            disabled={loading || rows.length === 0}
            onClick={handleSubmit}
          >
            {t("shops.saveProduct")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ProductVariantsPage;
