"use client";

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

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

type ExtensionRequestsSectionProps = {
  maestroID: number;
  accountType: number;
  totalCount: number;
  extensionRequests: MaestroDetail["extensionRequests"];
};

export function ExtensionRequestsSection({
  maestroID,
  accountType,
  totalCount,
  extensionRequests,
}: ExtensionRequestsSectionProps) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [isCreating, setIsCreating] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  const isPaidAccount = (PAID_ACCOUNT_TYPE_VALUES as readonly number[]).includes(accountType);
  const isDisabled = isCreating || isPending;

  async function handleCreate() {
    if (!window.confirm("연장 신청을 등록하시겠습니까?")) return;

    setIsCreating(true);
    setErrorMessage("");

    try {
      const response = await fetch(
        `/api/maestros/${maestroID}/extension-requests`,
        { method: "POST" }
      );

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

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

      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">
          <Button
            disabled={isDisabled || !isPaidAccount}
            onClick={() => void handleCreate()}
            size="sm"
            type="button"
            variant="outline"
          >
            <Plus aria-hidden="true" className="size-4" />
            연장
          </Button>
          {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>
              {extensionRequests.length > 0 ? (
                extensionRequests.map((request) => (
                  <tr
                    className="border-b last:border-b-0"
                    key={request.maestroExtensionID}
                  >
                    <td className="h-11 px-3 align-middle">
                      {request.maestroExtensionID}
                    </td>
                    <td className="h-11 px-3 align-middle">
                      {getAccountTypeLabel(request.accountType)}
                    </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={4}
                  >
                    연장 신청 이력이 없습니다.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  );
}
