"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { ArrowUp } from "lucide-react";

import { Button } from "@/components/ui/button";
import { ACCOUNT_TYPES } from "@/lib/constants";
import { formatDateTime, getAccountTypeLabel, getRequestStatusLabel } from "@/lib/utils";
import type { MaestroDetail } from "@/lib/maestros";

type UpgradeRequestsSectionProps = {
  maestroID: number;
  accountType: number;
  totalCount: number;
  upgradeRequests: MaestroDetail["upgradeRequests"];
};

const upgradeOptions = [
  { value: ACCOUNT_TYPES.BASIC_20, label: "1만원 (20명)" },
  { value: ACCOUNT_TYPES.STANDARD_50, label: "2만원 (50명)" },
  { value: ACCOUNT_TYPES.PRO_100, label: "3만원 (100명)" },
  { value: ACCOUNT_TYPES.SCHOOL_500, label: "4만원 (500명)" },
  { value: ACCOUNT_TYPES.SCHOOL_1000, label: "5만원 (1,000명)" },
] as const;

const selectClass =
  "h-9 rounded-md border bg-background px-3 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30 disabled:opacity-50";

export function UpgradeRequestsSection({
  maestroID,
  accountType,
  totalCount,
  upgradeRequests,
}: UpgradeRequestsSectionProps) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [isCreating, setIsCreating] = useState(false);
  const [selectedAccountType, setSelectedAccountType] = useState<number | null>(null);
  const [errorMessage, setErrorMessage] = useState("");

  const isUpgradeEnabled =
    selectedAccountType !== null && selectedAccountType > accountType;
  const isDisabled = isCreating || isPending;

  async function handleUpgrade() {
    if (selectedAccountType === null) return;
    if (!window.confirm("업그레이드 신청을 등록하시겠습니까?")) return;

    setIsCreating(true);
    setErrorMessage("");

    try {
      const response = await fetch(
        `/api/maestros/${maestroID}/upgrade-requests`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ requestedAccountType: selectedAccountType }),
        }
      );

      const body = (await response.json().catch(() => null)) as {
        message?: string;
      } | null;

      if (!response.ok) {
        throw new Error(body?.message ?? "업그레이드 신청 등록에 실패했습니다.");
      }

      setSelectedAccountType(null);
      startTransition(() => {
        router.refresh();
      });
    } catch (error) {
      setErrorMessage(
        error instanceof Error
          ? error.message
          : "업그레이드 신청 등록에 실패했습니다."
      );
    } finally {
      setIsCreating(false);
    }
  }

  return (
    <section className="rounded-lg border bg-background p-5">
      <div className="flex items-start justify-between gap-2">
        <div>
          <h2 className="text-base font-semibold">업그레이드 신청 이력</h2>
          <p className="mt-1 text-sm text-muted-foreground">
            전체 {totalCount.toLocaleString()}건 중 최근 20건
          </p>
        </div>
        <div className="flex flex-col items-end gap-1">
          <div className="flex items-center gap-2">
            <select
              className={selectClass}
              disabled={isDisabled}
              onChange={(e) =>
                setSelectedAccountType(
                  e.target.value === "" ? null : Number(e.target.value)
                )
              }
              value={selectedAccountType ?? ""}
            >
              <option value="">요금제 선택</option>
              {upgradeOptions.map((opt) => (
                <option
                  disabled={opt.value <= accountType}
                  key={opt.value}
                  value={opt.value}
                >
                  {opt.label}
                </option>
              ))}
            </select>
            <Button
              disabled={isDisabled || !isUpgradeEnabled}
              onClick={() => void handleUpgrade()}
              size="sm"
              type="button"
              variant="outline"
            >
              <ArrowUp aria-hidden="true" className="size-4" />
              업그레이드
            </Button>
          </div>
          {errorMessage ? (
            <p className="text-xs text-destructive">{errorMessage}</p>
          ) : null}
        </div>
      </div>
      <div className="mt-4 overflow-hidden rounded-lg border">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[560px] border-collapse text-sm">
            <thead className="bg-muted/60">
              <tr className="border-b">
                {["신청ID", "현재", "요청", "신청일시", "상태"].map(
                  (header) => (
                    <th
                      className="h-10 px-3 text-left text-xs font-medium text-muted-foreground"
                      key={header}
                    >
                      {header}
                    </th>
                  )
                )}
              </tr>
            </thead>
            <tbody>
              {upgradeRequests.length > 0 ? (
                upgradeRequests.map((request) => (
                  <tr
                    className="border-b last:border-b-0"
                    key={request.maestroUpgradeID}
                  >
                    <td className="h-11 px-3 align-middle">
                      {request.maestroUpgradeID}
                    </td>
                    <td className="h-11 px-3 align-middle">
                      {getAccountTypeLabel(request.registeredAccountType)}
                    </td>
                    <td className="h-11 px-3 align-middle">
                      {getAccountTypeLabel(request.requestedAccountType)}
                    </td>
                    <td className="h-11 px-3 align-middle">
                      {formatDateTime(request.requestedDateTime)}
                    </td>
                    <td className="h-11 px-3 align-middle">
                      {getRequestStatusLabel(request.status)}
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td
                    className="h-24 px-3 text-center text-sm text-muted-foreground"
                    colSpan={5}
                  >
                    업그레이드 신청 이력이 없습니다.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  );
}
