"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { Check, X } from "lucide-react";
import { useState, useTransition } from "react";

import { Button, buttonVariants } from "@/components/ui/button";
import { REQUEST_STATUSES } from "@/lib/constants";
import type { ExtensionRequestListItem } from "@/lib/extension-requests";
import {
  formatDate,
  getAccountTypeLabel,
  getActivateStatusLabel,
  getRequestStatusLabel,
} from "@/lib/utils";

type ExtensionRequestsTableProps = {
  data: ExtensionRequestListItem[];
};

export function ExtensionRequestsTable({ data }: ExtensionRequestsTableProps) {
  return (
    <div className="overflow-hidden rounded-lg border bg-background">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[960px] border-collapse text-sm">
          <thead className="bg-muted/60">
            <tr className="border-b">
              <HeaderCell>신청ID</HeaderCell>
              <HeaderCell>마에스트로</HeaderCell>
              <HeaderCell>요청 계정</HeaderCell>
              <HeaderCell>현재 계정</HeaderCell>
              <HeaderCell>현재 상태</HeaderCell>
              <HeaderCell>신청일시</HeaderCell>
              <HeaderCell>만료일</HeaderCell>
              <HeaderCell>처리 상태</HeaderCell>
              <HeaderCell>처리</HeaderCell>
            </tr>
          </thead>
          <tbody>
            {data.length > 0 ? (
              data.map((request) => (
                <tr
                  className="border-b last:border-b-0"
                  key={request.maestroExtensionID}
                >
                  <BodyCell>
                    <span className="font-mono text-xs tabular-nums">
                      {request.maestroExtensionID}
                    </span>
                  </BodyCell>
                  <BodyCell>
                    <Link
                      className={buttonVariants({
                        variant: "link",
                        size: "sm",
                        className: "h-auto p-0 font-medium",
                      })}
                      href={`/maestros/${request.maestroID}`}
                    >
                      {request.maestroName}
                    </Link>
                    <p className="mt-1 text-xs text-muted-foreground">
                      MaestroID {request.maestroID}
                    </p>
                  </BodyCell>
                  <BodyCell>
                    {getAccountTypeLabel(request.requestedAccountType)}
                  </BodyCell>
                  <BodyCell>
                    {getAccountTypeLabel(request.currentAccountType)}
                  </BodyCell>
                  <BodyCell>
                    {getActivateStatusLabel(request.activateStatus)}
                  </BodyCell>
                  <BodyCell>{formatDate(request.requestedDateTime)}</BodyCell>
                  <BodyCell>
                    {formatDate(request.availableActivateDateTime)}
                  </BodyCell>
                  <BodyCell>{getRequestStatusLabel(request.status)}</BodyCell>
                  <BodyCell>
                    <ExtensionRequestActions request={request} />
                  </BodyCell>
                </tr>
              ))
            ) : (
              <tr>
                <td
                  className="h-28 px-3 text-center text-sm text-muted-foreground"
                  colSpan={9}
                >
                  조건에 맞는 연장 신청이 없습니다.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ExtensionRequestActions({
  request,
}: {
  request: ExtensionRequestListItem;
}) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [errorMessage, setErrorMessage] = useState("");
  const [emailWarning, setEmailWarning] = useState(false);
  const isRequested = request.status === REQUEST_STATUSES.REQUESTED;

  if (!isRequested && !emailWarning) {
    return <span className="text-xs text-muted-foreground">처리 완료</span>;
  }

  async function submitAction(action: "approve" | "cancel") {
    const actionLabel = action === "approve" ? "승인" : "취소";
    if (!window.confirm(`${request.maestroName} 연장 신청을 ${actionLabel}하시겠습니까?`)) {
      return;
    }

    setErrorMessage("");

    try {
      const response = await fetch(
        `/api/extension-requests/${request.maestroExtensionID}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ action }),
        }
      );

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

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

      if (action === "approve" && body?.emailSent === false) {
        setEmailWarning(true);
      }

      startTransition(() => {
        router.refresh();
      });
    } catch (error) {
      setErrorMessage(
        error instanceof Error
          ? error.message
          : "연장 신청 처리에 실패했습니다."
      );
    }
  }

  return (
    <div className="space-y-2">
      {isRequested ? (
        <div className="flex items-center gap-2">
          <Button
            disabled={isPending}
            onClick={() => void submitAction("approve")}
            size="sm"
            type="button"
          >
            <Check className="size-4" aria-hidden="true" />
            승인
          </Button>
          <Button
            disabled={isPending}
            onClick={() => void submitAction("cancel")}
            size="sm"
            type="button"
            variant="outline"
          >
            <X className="size-4" aria-hidden="true" />
            취소
          </Button>
        </div>
      ) : (
        <span className="text-xs text-muted-foreground">처리 완료</span>
      )}
      {emailWarning ? (
        <p className="max-w-56 text-xs text-amber-600 dark:text-amber-400">
          이메일 발송 실패 — 수동 확인 필요
        </p>
      ) : null}
      {errorMessage ? (
        <p className="max-w-56 text-xs text-destructive">{errorMessage}</p>
      ) : null}
    </div>
  );
}

function HeaderCell({ children }: { children: React.ReactNode }) {
  return (
    <th className="h-10 px-3 text-left text-xs font-medium text-muted-foreground">
      {children}
    </th>
  );
}

function BodyCell({ children }: { children: React.ReactNode }) {
  return <td className="h-12 px-3 align-middle">{children}</td>;
}
