"use client";

import { useState, type FormEvent } from "react";
import { BottomToast } from "@/components/bottom-toast";
import type {
  DomainSetupPromotionDiscountType,
  KavenixDomainSetupPromotionCodeRow,
} from "@/lib/domain-setup-promotions";

const inputClassName =
  "h-10 w-full rounded-[10px] border border-[#dbe5f7] bg-white px-3 text-[13px] text-[#1a2943] outline-none placeholder:text-[#97a7c2] focus:border-[#bcd1ff]";

function formatDate(value: string | null) {
  if (!value) return "제한 없음";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";
  return new Intl.DateTimeFormat("ko-KR", {
    dateStyle: "short",
    timeStyle: "short",
  }).format(date);
}

function discountLabel(row: KavenixDomainSetupPromotionCodeRow) {
  return row.discountType === "percent"
    ? `${row.discountValue}% 할인`
    : `${row.discountValue.toLocaleString("ko-KR")}원 할인`;
}

export function KavenixPromotionCodeDashboard({
  initialCodes,
}: {
  initialCodes: KavenixDomainSetupPromotionCodeRow[];
}) {
  const [codes, setCodes] = useState(initialCodes);
  const [code, setCode] = useState("");
  const [label, setLabel] = useState("");
  const [discountType, setDiscountType] =
    useState<DomainSetupPromotionDiscountType>("percent");
  const [discountValue, setDiscountValue] = useState("100");
  const [usageLimit, setUsageLimit] = useState("");
  const [perUserLimit, setPerUserLimit] = useState("1");
  const [startsAt, setStartsAt] = useState("");
  const [expiresAt, setExpiresAt] = useState("");
  const [saving, setSaving] = useState(false);
  const [updatingId, setUpdatingId] = useState<number | null>(null);
  const [toast, setToast] = useState<{ message: string; tone: "error" | "success" } | null>(null);

  const handleCreate = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (saving) return;
    setSaving(true);

    try {
      const response = await fetch("/api/kavenix/promotion-codes", {
        body: JSON.stringify({
          code,
          discountType,
          discountValue,
          expiresAt: expiresAt ? new Date(expiresAt).toISOString() : "",
          label,
          perUserLimit,
          startsAt: startsAt ? new Date(startsAt).toISOString() : "",
          usageLimit,
        }),
        headers: { "Content-Type": "application/json" },
        method: "POST",
      });
      const payload = (await response.json().catch(() => null)) as {
        codes?: KavenixDomainSetupPromotionCodeRow[];
        message?: string;
      } | null;

      if (!response.ok || !payload?.codes) {
        throw new Error(payload?.message || "프로모션 코드 발급에 실패했습니다.");
      }

      setCodes(payload.codes);
      setCode("");
      setLabel("");
      setToast({ message: "프로모션 코드를 발급했습니다.", tone: "success" });
    } catch (error) {
      setToast({
        message: error instanceof Error ? error.message : "프로모션 코드 발급에 실패했습니다.",
        tone: "error",
      });
    } finally {
      setSaving(false);
    }
  };

  const toggleCode = async (row: KavenixDomainSetupPromotionCodeRow) => {
    if (updatingId !== null) return;
    setUpdatingId(row.id);

    try {
      const response = await fetch(`/api/kavenix/promotion-codes/${row.id}`, {
        body: JSON.stringify({ isActive: !row.isActive }),
        headers: { "Content-Type": "application/json" },
        method: "PATCH",
      });
      const payload = (await response.json().catch(() => null)) as {
        codes?: KavenixDomainSetupPromotionCodeRow[];
        message?: string;
      } | null;

      if (!response.ok || !payload?.codes) {
        throw new Error(payload?.message || "프로모션 코드 상태 변경에 실패했습니다.");
      }

      setCodes(payload.codes);
      setToast({
        message: row.isActive ? "프로모션 코드를 중지했습니다." : "프로모션 코드를 다시 활성화했습니다.",
        tone: "success",
      });
    } catch (error) {
      setToast({
        message: error instanceof Error ? error.message : "프로모션 코드 상태 변경에 실패했습니다.",
        tone: "error",
      });
    } finally {
      setUpdatingId(null);
    }
  };

  return (
    <>
      <form onSubmit={handleCreate} className="border-b border-[#edf1f6] px-3 py-5 sm:px-4 lg:px-8">
        <div className="mb-4">
          <h2 className="text-[14px] font-semibold text-[#263957]">새 코드 발급</h2>
          <p className="mt-1 text-[12px] leading-5 text-[#70819d]">
            도메인 연결 설정 대행비에만 적용되며 신청 접수 시 사용량이 예약됩니다.
          </p>
        </div>
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <label>
            <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">코드</span>
            <input
              required
              value={code}
              maxLength={64}
              onChange={(event) => setCode(event.target.value.toUpperCase())}
              placeholder="PARTNER100"
              className={`${inputClassName} font-semibold uppercase tracking-[0.03em]`}
            />
          </label>
          <label>
            <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">관리용 이름</span>
            <input required value={label} onChange={(event) => setLabel(event.target.value)} placeholder="공유오피스 제휴 혜택" className={inputClassName} />
          </label>
          <div className="grid grid-cols-[110px_minmax(0,1fr)] gap-2">
            <label>
              <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">할인 방식</span>
              <select value={discountType} onChange={(event) => setDiscountType(event.target.value as DomainSetupPromotionDiscountType)} className={inputClassName}>
                <option value="fixed">정액</option>
                <option value="percent">정률</option>
              </select>
            </label>
            <label>
              <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">할인값</span>
              <input required type="number" min="1" max={discountType === "percent" ? 100 : 1000000} value={discountValue} onChange={(event) => setDiscountValue(event.target.value)} className={inputClassName} />
            </label>
          </div>
          <div className="grid grid-cols-2 gap-2">
            <label>
              <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">전체 한도</span>
              <input type="number" min="1" value={usageLimit} onChange={(event) => setUsageLimit(event.target.value)} placeholder="무제한" className={inputClassName} />
            </label>
            <label>
              <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">계정당 한도</span>
              <input required type="number" min="1" value={perUserLimit} onChange={(event) => setPerUserLimit(event.target.value)} className={inputClassName} />
            </label>
          </div>
          <label>
            <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">사용 시작</span>
            <input type="datetime-local" value={startsAt} onChange={(event) => setStartsAt(event.target.value)} className={inputClassName} />
          </label>
          <label>
            <span className="mb-1.5 block text-[12px] font-semibold text-[#5d7195]">사용 종료</span>
            <input type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} className={inputClassName} />
          </label>
          <div className="flex items-end md:col-span-2">
            <button type="submit" disabled={saving} className="om-btn-primary h-10 cursor-pointer rounded-[10px] px-4 text-[13px] shadow-none disabled:cursor-not-allowed disabled:opacity-60">
              {saving ? "발급 중..." : "프로모션 코드 발급"}
            </button>
          </div>
        </div>
      </form>

      <div className="overflow-x-auto">
        <table className="w-full min-w-[980px] border-collapse text-left">
          <thead>
            <tr className="border-b border-[#edf1f6] text-[12px] font-semibold text-[#7a8ba8]">
              <th className="py-3 pl-3 pr-3 sm:pl-4 lg:pl-8">코드</th>
              <th className="px-3 py-3">혜택</th>
              <th className="px-3 py-3">사용량</th>
              <th className="px-3 py-3">계정당</th>
              <th className="px-3 py-3">사용 기간</th>
              <th className="px-3 py-3">상태</th>
              <th className="py-3 pl-3 pr-3 text-right sm:pr-4 lg:pr-8">관리</th>
            </tr>
          </thead>
          <tbody>
            {codes.length === 0 ? (
              <tr><td colSpan={7} className="px-4 py-14 text-center text-[13px] text-[#7b8ca8]">발급된 프로모션 코드가 없습니다.</td></tr>
            ) : null}
            {codes.map((row) => (
              <tr key={row.id} className="border-b border-[#edf1f6] text-[13px] text-[#30425f] last:border-b-0 hover:bg-[#fafcff]">
                <td className="py-3 pl-3 pr-3 sm:pl-4 lg:pl-8"><p className="font-semibold tracking-[0.03em] text-[#16233c]">{row.code}</p><p className="mt-1 text-[12px] text-[#70819d]">{row.label}</p></td>
                <td className="px-3 py-3 font-semibold text-[#2f6df6]">{discountLabel(row)}</td>
                <td className="px-3 py-3">{row.redeemedCount.toLocaleString("ko-KR")}회 사용 · {row.reservedCount.toLocaleString("ko-KR")}회 예약 / {row.usageLimit?.toLocaleString("ko-KR") ?? "무제한"}</td>
                <td className="px-3 py-3">{row.perUserLimit.toLocaleString("ko-KR")}회</td>
                <td className="px-3 py-3 text-[#70819d]">{formatDate(row.startsAt)}<br />~ {formatDate(row.expiresAt)}</td>
                <td className={`px-3 py-3 font-semibold ${row.isActive ? "text-[#238653]" : "text-[#8a94a8]"}`}>{row.isActive ? "사용 중" : "중지"}</td>
                <td className="py-3 pl-3 pr-3 text-right sm:pr-4 lg:pr-8">
                  <button type="button" disabled={updatingId !== null} onClick={() => void toggleCode(row)} className={`h-8 cursor-pointer rounded-[8px] px-2.5 text-[12px] font-semibold disabled:cursor-not-allowed disabled:opacity-50 ${row.isActive ? "text-[#d64a5f] hover:bg-[#fff1f3]" : "text-[#2f6df6] hover:bg-[#edf4ff]"}`}>{row.isActive ? "사용 중지" : "다시 활성화"}</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {toast ? <BottomToast key={`${toast.tone}-${toast.message}`} notice={toast} onClose={() => setToast(null)} /> : null}
    </>
  );
}
