"use client";

import { useState } from "react";
import { useI18n } from "@/translations/provider";
import {
  type CheckDiscountResult,
  useValidateDiscountMutation,
} from "@/hooks/marriage/use-validate-discount";

export interface DiscountWidgetProps {
  objectId: number | string;
  service?: string;
  onDiscountApplied?: (result: CheckDiscountResult) => void;
  onDiscountCleared?: () => void;
  className?: string;
}

export function DiscountWidget({
  objectId,
  service = "marriagesubscriptionplan",
  onDiscountApplied,
  onDiscountCleared,
  className = "",
}: DiscountWidgetProps) {
  const { dictionary: t } = useI18n();
  const [isExpanded, setIsExpanded] = useState(false);
  const [code, setCode] = useState("");
  const [discountStatus, setDiscountStatus] = useState<
    "initial" | "empty" | "loading" | "success" | "failed"
  >("initial");
  const [discountResult, setDiscountResult] =
    useState<CheckDiscountResult | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const validateMutation = useValidateDiscountMutation();

  const handleApply = async () => {
    const trimmed = code.trim();
    if (!trimmed) {
      setDiscountStatus("empty");
      setErrorMessage(t["This field is required"] || "This field is required");
      return;
    }

    setDiscountStatus("loading");
    setErrorMessage(null);

    try {
      const result = await validateMutation.mutateAsync({
        code: trimmed,
        objectId,
        service,
      });

      if (result.valid) {
        setDiscountStatus("success");
        setDiscountResult(result);
        setErrorMessage(null);
        onDiscountApplied?.(result);
      } else {
        setDiscountStatus("failed");
        setDiscountResult(null);
        setErrorMessage(result.message || "Invalid discount code");
      }
    } catch (err: any) {
      setDiscountStatus("failed");
      setDiscountResult(null);
      setErrorMessage(
        err?.response?.data?.detail || err?.message || "Invalid discount code",
      );
    }
  };

  const handleClear = () => {
    setCode("");
    setDiscountStatus("initial");
    setDiscountResult(null);
    setErrorMessage(null);
    onDiscountCleared?.();
  };

  const getBorderAndRing = () => {
    switch (discountStatus) {
      case "success":
        return "border-[#00AC78] ring-1 ring-[#00AC78]";
      case "failed":
      case "empty":
        return "border-[#F0445B] ring-1 ring-[#F0445B]";
      default:
        return "border-[#D0D5DD] hover:border-[#98A2B3] focus-within:border-[#F0445B] focus-within:ring-1 focus-within:ring-[#F0445B]";
    }
  };

  return (
    <div className={`w-full ${className}`}>
      {/* ── Collapsible Header ── */}
      <button
        type="button"
        onClick={() => setIsExpanded((prev) => !prev)}
        className="flex w-full items-center justify-between py-3.5 text-left transition-colors cursor-pointer select-none"
      >
        <div className="flex items-center gap-3">
          {/* Coupon icon */}
          <svg
            width="18"
            height="18"
            viewBox="0 0 18 18"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            className={`shrink-0 transition-colors ${
              isExpanded ? "text-[#747474]" : "text-[#F0445B]"
            }`}
          >
            <path
              fillRule="evenodd"
              clipRule="evenodd"
              d="M1.60714 3.21429C1.60714 2.94686 1.82314 2.73214 2.08671 2.73214H15.9133C16.1769 2.73214 16.3929 2.94686 16.3929 3.21429V5.91943C15.8137 6.19949 15.3252 6.6371 14.9834 7.18208C14.6416 7.72706 14.4603 8.35734 14.4603 9.00064C14.4603 9.64395 14.6416 10.2742 14.9834 10.8192C15.3252 11.3642 15.8137 11.8018 16.3929 12.0819V14.7857C16.393 14.8489 16.3808 14.9114 16.3567 14.9698C16.3327 15.0282 16.2975 15.0813 16.2529 15.1261C16.2084 15.1709 16.1555 15.2064 16.0972 15.2308C16.0389 15.2551 15.9764 15.2677 15.9133 15.2679H2.08671C2.02357 15.2677 1.96107 15.2551 1.9028 15.2308C1.84452 15.2064 1.79161 15.1709 1.74707 15.1261C1.70254 15.0813 1.66726 15.0282 1.64325 14.9698C1.61924 14.9114 1.60697 14.8489 1.60714 14.7857V12.0909C2.19152 11.8129 2.68514 11.3751 3.03076 10.828C3.37637 10.2809 3.55982 9.64709 3.55982 9C3.55982 8.3529 3.37637 7.71907 3.03076 7.172C2.68514 6.62493 2.19152 6.18705 1.60714 5.90914V3.21429ZM2.08671 1.125C0.933429 1.125 0 2.06229 0 3.21429V6.46714C0 6.83229 0.246857 7.15114 0.599143 7.24371C0.987519 7.34535 1.33125 7.57285 1.57657 7.89063C1.82189 8.20841 1.95496 8.59855 1.95496 9C1.95496 9.40145 1.82189 9.79159 1.57657 10.1094C1.33125 10.4271 0.987519 10.6546 0.599143 10.7563C0.427554 10.8014 0.275728 10.9021 0.167347 11.0426C0.0589657 11.183 0.000124048 11.3554 0 11.5329L0 14.7857C0 15.939 0.933429 16.875 2.08671 16.875H15.9133C17.0666 16.875 18 15.939 18 14.7857V11.5277C18 11.3514 17.9419 11.1799 17.8348 11.0398C17.7277 10.8997 17.5775 10.7987 17.4073 10.7524C17.0222 10.6483 16.6822 10.4202 16.4398 10.1034C16.1973 9.78667 16.066 9.39889 16.066 9C16.066 8.60111 16.1973 8.21333 16.4398 7.89658C16.6822 7.57983 17.0222 7.35174 17.4073 7.24757C17.5775 7.20129 17.7277 7.10032 17.8348 6.96021C17.9419 6.8201 18 6.64865 18 6.47229V3.21429C18 2.06229 17.0666 1.125 15.9133 1.125H2.08671ZM12.7826 5.21743C12.708 5.14279 12.6194 5.08358 12.5218 5.04318C12.4243 5.00279 12.3198 4.98199 12.2143 4.98199C12.1087 4.98199 12.0042 5.00279 11.9067 5.04318C11.8092 5.08358 11.7206 5.14279 11.646 5.21743L5.21743 11.646C5.1428 11.7206 5.0836 11.8092 5.04321 11.9067C5.00282 12.0042 4.98204 12.1087 4.98204 12.2143C4.98204 12.3198 5.00282 12.4243 5.04321 12.5218C5.0836 12.6193 5.1428 12.7079 5.21743 12.7826C5.29206 12.8572 5.38065 12.9164 5.47816 12.9568C5.57567 12.9972 5.68017 13.018 5.78571 13.018C5.89125 13.018 5.99576 12.9972 6.09327 12.9568C6.19077 12.9164 6.27937 12.8572 6.354 12.7826L12.7826 6.354C12.8572 6.27938 12.9164 6.19078 12.9568 6.09328C12.9972 5.99577 13.018 5.89126 13.018 5.78571C13.018 5.68017 12.9972 5.57566 12.9568 5.47815C12.9164 5.38064 12.8572 5.29205 12.7826 5.21743ZM4.98214 6.42857C4.98214 6.23862 5.01956 6.05054 5.09225 5.87505C5.16494 5.69956 5.27148 5.54011 5.40579 5.40579C5.54011 5.27148 5.69956 5.16494 5.87505 5.09225C6.05054 5.01956 6.23862 4.98214 6.42857 4.98214C6.61852 4.98214 6.80661 5.01956 6.9821 5.09225C7.15758 5.16494 7.31704 5.27148 7.45135 5.40579C7.58566 5.54011 7.69221 5.69956 7.7649 5.87505C7.83759 6.05054 7.875 6.23862 7.875 6.42857C7.875 6.81219 7.72261 7.18009 7.45135 7.45135C7.18009 7.72261 6.81219 7.875 6.42857 7.875C6.04495 7.875 5.67705 7.72261 5.40579 7.45135C5.13453 7.18009 4.98214 6.81219 4.98214 6.42857ZM11.5714 10.125C11.1878 10.125 10.8199 10.2774 10.5486 10.5486C10.2774 10.8199 10.125 11.1878 10.125 11.5714C10.125 11.955 10.2774 12.3229 10.5486 12.5942C10.8199 12.8655 11.1878 13.0179 11.5714 13.0179C11.955 13.0179 12.3229 12.8655 12.5942 12.5942C12.8655 12.3229 13.0179 11.955 13.0179 11.5714C13.0179 11.1878 12.8655 10.8199 12.5942 10.5486C12.3229 10.2774 11.955 10.125 11.5714 10.125Z"
              fill="currentColor"
            />
          </svg>

          <span
            className={`text-[14px] font-bold transition-colors ${
              isExpanded ? "text-[#747474]" : "text-[#F0445B]"
            }`}
          >
            {t["Do you have a discount code?"] ||
              "Do you have a discount code?"}
          </span>
        </div>

        {/* Arrow expand icon */}
        <svg
          aria-hidden="true"
          className={`size-5 transition-transform duration-300 ${
            isExpanded ? "rotate-180 text-[#747474]" : "rotate-0 text-[#F0445B]"
          }`}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth={2.5}
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </button>

      {/* ── Expanded Form Body ── */}
      {isExpanded && (
        <div className="pt-1 pb-2 w-full">
          <div
            className={`flex h-[52px] w-full items-center rounded-[12px] border bg-white px-4 transition-all ${getBorderAndRing()}`}
          >
            <input
              type="text"
              dir="ltr"
              value={code}
              disabled={discountStatus === "loading" || discountResult !== null}
              onChange={(e) => {
                setCode(e.target.value);
                if (discountStatus !== "initial") {
                  setDiscountStatus("initial");
                  setErrorMessage(null);
                }
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" && discountResult === null) {
                  e.preventDefault();
                  handleApply();
                }
              }}
              placeholder={
                t["Enter discount code..."] || "Enter discount code..."
              }
              className="h-full flex-1 bg-transparent text-[15px] font-medium text-[#181818] outline-none placeholder:text-[#98A2B3] disabled:opacity-70 min-w-0"
            />

            {discountStatus === "loading" ? (
              <div className="shrink-0 pl-3">
                <div className="size-4.5 animate-spin rounded-full border-2 border-[#F0445B] border-t-transparent" />
              </div>
            ) : discountResult !== null ? (
              <button
                type="button"
                onClick={handleClear}
                className="shrink-0 pl-3 text-[15px] font-semibold text-[#F0445B] hover:opacity-80 transition-opacity cursor-pointer"
              >
                {t["Clear"] || "Clear"}
              </button>
            ) : (
              <button
                type="button"
                onClick={handleApply}
                className="shrink-0 pl-3 text-[15px] font-semibold text-[#F0445B] hover:opacity-80 transition-opacity cursor-pointer"
              >
                {t["Apply"] || "Apply"}
              </button>
            )}
          </div>

          {/* Status Message */}
          {errorMessage && (
            <p className="mt-2 text-start text-[13px] font-medium text-[#D44747] leading-normal">
              {errorMessage}
            </p>
          )}

          {discountStatus === "success" && discountResult?.message && (
            <p className="mt-2 text-start text-[13px] font-medium text-[#00AC78] leading-normal">
              {discountResult.message}
            </p>
          )}
        </div>
      )}
    </div>
  );
}
