"use client";

import { useEffect, useRef, useState } from "react";
import type {
  DomainSetupAssistancePaymentStatus,
  DomainSetupAssistanceStatus,
  KavenixDomainSetupAssistanceRow,
} from "@/lib/domain-setup-assistance";
import { getDomainSetupAssistanceNetAmount } from "@/lib/pricing";

type Credentials = {
  accountIdentifier: string;
  accountPassword: string;
  domain: string;
  provider: string;
};

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 paymentStatusLabel(status: DomainSetupAssistancePaymentStatus) {
  if (status === "paid") return "결제 완료";
  if (status === "processing") return "결제 중";
  if (status === "failed") return "결제 실패";
  if (status === "cancelled") return "결제 취소";
  if (status === "not_applicable") return "결제 없음";
  return "완료 시 결제";
}

function paymentStatusClassName(status: DomainSetupAssistancePaymentStatus) {
  if (status === "paid") return "text-[#238653]";
  if (status === "failed") return "text-[#d64a5f]";
  if (status === "processing") return "text-[#2f6df6]";
  return "text-[#70819d]";
}

function statusLabel(status: DomainSetupAssistanceStatus) {
  if (status === "in_progress") {
    return "진행 중";
  }

  if (status === "completed") {
    return "완료";
  }

  if (status === "cancelled") {
    return "취소";
  }

  return "접수";
}

function statusClassName(status: DomainSetupAssistanceStatus) {
  if (status === "in_progress") {
    return "bg-[#edf4ff] text-[#2f6df6]";
  }

  if (status === "completed") {
    return "bg-[#ecf9f1] text-[#238653]";
  }

  if (status === "cancelled") {
    return "bg-[#f3f5f8] text-[#7c879b]";
  }

  return "bg-[#fff7e8] text-[#a76500]";
}

function formatAssistanceFee(chargeAmount: number) {
  if (chargeAmount === 0) {
    return "0원";
  }

  return `${getDomainSetupAssistanceNetAmount(chargeAmount).toLocaleString("ko-KR")}원(VAT 별도)`;
}

export function KavenixDomainAssistanceDashboard({
  initialRows,
}: {
  initialRows: KavenixDomainSetupAssistanceRow[];
}) {
  const [rows, setRows] = useState(initialRows);
  const [selectedRow, setSelectedRow] = useState<KavenixDomainSetupAssistanceRow | null>(null);
  const [credentials, setCredentials] = useState<Credentials | null>(null);
  const [adminNote, setAdminNote] = useState("");
  const [loadingCredentials, setLoadingCredentials] = useState(false);
  const [savingStatus, setSavingStatus] = useState(false);
  const [message, setMessage] = useState("");
  const credentialsPanelRef = useRef<HTMLDivElement>(null);
  const adminNoteRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    if (!credentials) {
      return;
    }

    credentialsPanelRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  }, [credentials]);

  const openRequest = (row: KavenixDomainSetupAssistanceRow) => {
    setSelectedRow(row);
    setCredentials(null);
    setAdminNote(row.adminNote ?? "");
    setMessage("");
  };

  const loadCredentials = async () => {
    if (!selectedRow || loadingCredentials) {
      return;
    }

    if (credentials) {
      setCredentials(null);
      setMessage("");
      return;
    }

    setLoadingCredentials(true);
    setMessage("");

    try {
      const response = await fetch(`/api/kavenix/domain-assistance/${selectedRow.id}`, {
        cache: "no-store",
      });
      const payload = (await response.json().catch(() => null)) as {
        credentials?: Credentials;
        message?: string;
      } | null;

      if (!response.ok || !payload?.credentials) {
        throw new Error(payload?.message || "계정정보를 불러오지 못했습니다.");
      }

      setCredentials(payload.credentials);
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "계정정보를 불러오지 못했습니다.");
    } finally {
      setLoadingCredentials(false);
    }
  };

  const updateStatus = async (status: DomainSetupAssistanceStatus) => {
    if (!selectedRow || savingStatus) {
      return;
    }

    if (status === "cancelled" && !adminNote.trim()) {
      setMessage("신청자에게 안내할 취소 사유를 관리자 처리 메모에 입력해주세요.");
      adminNoteRef.current?.focus();
      return;
    }

    if (
      status === "completed" &&
      !window.confirm(
        selectedRow.feeAmount === 0
          ? `${selectedRow.domain} 연결을 완료합니다. 프로모션 전액 할인으로 카드 결제는 발생하지 않습니다. 계속할까요?`
          : `${selectedRow.domain} 연결을 완료하고 등록된 결제수단으로 설정 대행비 ${formatAssistanceFee(selectedRow.feeAmount)}를 결제합니다. 계속할까요?`,
      )
    ) {
      return;
    }

    setSavingStatus(true);
    setMessage("");

    try {
      const response = await fetch(`/api/kavenix/domain-assistance/${selectedRow.id}`, {
        body: JSON.stringify({ adminNote, status }),
        headers: { "Content-Type": "application/json" },
        method: "PATCH",
      });
      const payload = (await response.json().catch(() => null)) as {
        message?: string;
        notificationSent?: boolean | null;
        request?: {
          chargedAt: string | null;
          paymentErrorMessage: string | null;
          paymentStatus: DomainSetupAssistancePaymentStatus;
          status: DomainSetupAssistanceStatus;
        };
      } | null;

      if (!response.ok) {
        throw new Error(payload?.message || "처리 상태 변경에 실패했습니다.");
      }

      const nextRow: KavenixDomainSetupAssistanceRow = {
        ...selectedRow,
        adminNote: adminNote.trim() || null,
        chargedAt: payload?.request?.chargedAt ?? selectedRow.chargedAt,
        completedAt: status === "completed" ? new Date().toISOString() : selectedRow.completedAt,
        credentialsAvailable:
          status === "completed" || status === "cancelled"
            ? false
            : selectedRow.credentialsAvailable,
        paymentErrorMessage:
          payload?.request?.paymentErrorMessage ?? selectedRow.paymentErrorMessage,
        paymentStatus: payload?.request?.paymentStatus ?? selectedRow.paymentStatus,
        startedAt:
          status === "in_progress"
            ? selectedRow.startedAt ?? new Date().toISOString()
            : selectedRow.startedAt,
        status,
      };
      setRows((current) => current.map((row) => (row.id === nextRow.id ? nextRow : row)));
      setSelectedRow(nextRow);
      if (status === "completed" || status === "cancelled") {
        setCredentials(null);
      }
      setMessage(
        `${
          status === "completed"
            ? selectedRow.feeAmount === 0
              ? "연결 완료와 프로모션 사용 처리를 완료했습니다."
              : "연결 완료와 설정비 결제를 처리했습니다."
            : "처리 상태를 변경했습니다."
        } ${
          payload?.notificationSent === false
            ? "신청자 알림 메일 발송에는 실패했습니다."
            : "신청자 알림 메일을 발송했습니다."
        }`,
      );
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "처리 상태 변경에 실패했습니다.");
    } finally {
      setSavingStatus(false);
    }
  };

  const copyText = async (value: string) => {
    await navigator.clipboard.writeText(value);
    setMessage("클립보드에 복사했습니다.");
  };

  return (
    <>
      <div className="overflow-x-auto">
        <table className="w-full min-w-[1120px] border-collapse text-left">
          <thead>
            <tr className="border-b border-[#edf1f6] text-[12px] font-semibold text-[#7a8ba8]">
              <th className="px-3 py-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="px-3 py-3">결제</th>
              <th className="px-3 py-3">접수 시각</th>
              <th className="px-3 py-3 text-right sm:pr-4 lg:pr-8">관리</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr>
                <td colSpan={9} className="px-4 py-14 text-center text-[13px] text-[#7b8ca8]">
                  설정 대행 신청이 없습니다.
                </td>
              </tr>
            ) : null}
            {rows.map((row) => (
              <tr key={row.id} className="border-b border-[#edf1f6] text-[13px] text-[#30425f] last:border-b-0 hover:bg-[#fafcff]">
                <td className="px-3 py-3 sm:pl-4 lg:pl-8">
                  <span className={`inline-flex h-7 items-center rounded-full px-2.5 text-[12px] font-semibold ${statusClassName(row.status)}`}>
                    {statusLabel(row.status)}
                  </span>
                </td>
                <td className="px-3 py-3 font-semibold text-[#16233c]">{row.domain}</td>
                <td className="px-3 py-3">{row.requesterEmail}</td>
                <td className="px-3 py-3">{row.notificationEmail ?? "-"}</td>
                <td className="px-3 py-3">{row.provider}</td>
                <td className="px-3 py-3">
                  <p className="font-semibold">{formatAssistanceFee(row.feeAmount)}</p>
                  {row.promotionCode ? <p className="mt-1 text-[11px] font-semibold text-[#2f6df6]">{row.promotionCode}</p> : null}
                </td>
                <td className={`px-3 py-3 font-semibold ${paymentStatusClassName(row.paymentStatus)}`}>
                  {paymentStatusLabel(row.paymentStatus)}
                </td>
                <td className="px-3 py-3 text-[#70819d]">{formatDate(row.requestedAt)}</td>
                <td className="px-3 py-3 text-right sm:pr-4 lg:pr-8">
                  <button type="button" onClick={() => openRequest(row)} className="h-8 cursor-pointer rounded-[8px] px-2.5 text-[12px] font-semibold text-[#2f6df6] hover:bg-[#edf4ff]">
                    상세보기
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {selectedRow ? (
        <div className="fixed inset-0 z-[10030] flex items-end justify-center bg-[#111827]/32 p-0 backdrop-blur-[2px] sm:items-center sm:p-5" role="presentation" onMouseDown={(event) => {
          if (event.currentTarget === event.target) {
            setSelectedRow(null);
          }
        }}>
          <div role="dialog" aria-modal="true" aria-labelledby="domain-assistance-admin-title" className="max-h-[90dvh] w-full overflow-y-auto rounded-t-[22px] bg-white shadow-[0_30px_80px_rgba(18,32,65,0.24)] sm:max-w-[680px] sm:rounded-[22px]">
            <div className="flex items-start justify-between gap-4 border-b border-[#edf1f6] px-5 py-5 sm:px-6">
              <div>
                <p className="text-[12px] font-semibold text-[#2f6df6]">설정 대행 #{selectedRow.id}</p>
                <h2 id="domain-assistance-admin-title" className="mt-1 text-[20px] font-semibold tracking-[-0.04em] text-[#16233c]">{selectedRow.domain}</h2>
                <p className="mt-1 text-[13px] text-[#70819d]">{selectedRow.requesterEmail} · {selectedRow.provider}</p>
                <p className="mt-1 text-[12px] text-[#526784]">완료 알림 {selectedRow.notificationEmail ?? "-"}</p>
              </div>
              <button type="button" aria-label="설정 대행 상세 닫기" onClick={() => setSelectedRow(null)} className="inline-flex h-9 w-9 cursor-pointer items-center justify-center rounded-full text-[22px] text-[#8190a8] hover:bg-[#f3f6fb] hover:text-[#2f6df6]">×</button>
            </div>
            <div className="space-y-5 px-5 py-5 sm:px-6">
              <div className="grid gap-3 sm:grid-cols-4">
                <div><p className="text-[12px] text-[#7c879b]">상태</p><p className="mt-1 font-semibold text-[#263957]">{statusLabel(selectedRow.status)}</p></div>
                <div><p className="text-[12px] text-[#7c879b]">설정비</p><p className="mt-1 font-semibold text-[#263957]">{formatAssistanceFee(selectedRow.feeAmount)}</p>{selectedRow.promotionCode ? <p className="mt-1 text-[11px] font-semibold text-[#2f6df6]">{selectedRow.promotionCode} · {getDomainSetupAssistanceNetAmount(selectedRow.discountAmount).toLocaleString("ko-KR")}원 할인</p> : null}</div>
                <div><p className="text-[12px] text-[#7c879b]">접수</p><p className="mt-1 font-semibold text-[#263957]">{formatDate(selectedRow.requestedAt)}</p></div>
                <div><p className="text-[12px] text-[#7c879b]">결제</p><p className={`mt-1 font-semibold ${paymentStatusClassName(selectedRow.paymentStatus)}`}>{paymentStatusLabel(selectedRow.paymentStatus)}</p></div>
              </div>
              {selectedRow.paymentErrorMessage ? (
                <p className="text-[12px] leading-5 text-[#d64a5f]">최근 결제 실패: {selectedRow.paymentErrorMessage}</p>
              ) : null}

              <div className="border-y border-[#edf1f6] py-4">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <p className="text-[13px] font-semibold text-[#263957]">도메인 관리 계정</p>
                    <p className="mt-1 text-[12px] text-[#70819d]">업무에 필요한 순간에만 열람하세요.</p>
                  </div>
                  <button type="button" disabled={!selectedRow.credentialsAvailable || loadingCredentials} onClick={() => void loadCredentials()} aria-expanded={credentials !== null} className="h-9 cursor-pointer rounded-[9px] border border-[#cddcff] bg-[#f6f9ff] px-3 text-[12px] font-semibold text-[#2f6df6] disabled:cursor-not-allowed disabled:border-[#e1e6ef] disabled:bg-[#f7f8fa] disabled:text-[#9aa7ba]">
                    {loadingCredentials
                      ? "불러오는 중..."
                      : !selectedRow.credentialsAvailable
                        ? "계정정보 폐기됨"
                        : credentials
                          ? "계정정보 숨기기"
                          : "계정정보 보기"}
                  </button>
                </div>
                {credentials ? (
                  <div ref={credentialsPanelRef} className="mt-4 overflow-hidden rounded-[12px] border border-[#cddcff] bg-[#f7faff]">
                    <div className="border-b border-[#dce7fb] px-3.5 py-2.5">
                      <p className="text-[12px] font-semibold text-[#2f6df6]">제출된 도메인 관리 계정</p>
                      <p className="mt-0.5 text-[11px] leading-4 text-[#70819d]">처리에 필요한 경우에만 사용하고 외부에 공유하지 마세요.</p>
                    </div>
                    <div className="divide-y divide-[#dce7fb] px-3.5">
                      <div className="flex items-center gap-3 py-3"><span className="w-16 shrink-0 text-[12px] text-[#7c879b]">아이디</span><code className="min-w-0 flex-1 break-all text-[13px] text-[#263957]">{credentials.accountIdentifier}</code><button type="button" onClick={() => void copyText(credentials.accountIdentifier)} className="shrink-0 text-[12px] font-semibold text-[#2f6df6]">복사</button></div>
                      <div className="flex items-center gap-3 py-3"><span className="w-16 shrink-0 text-[12px] text-[#7c879b]">비밀번호</span><code className="min-w-0 flex-1 break-all text-[13px] text-[#263957]">{credentials.accountPassword}</code><button type="button" onClick={() => void copyText(credentials.accountPassword)} className="shrink-0 text-[12px] font-semibold text-[#2f6df6]">복사</button></div>
                    </div>
                  </div>
                ) : null}
              </div>

              <div>
                <p className="text-[13px] font-semibold text-[#263957]">신청자 메모</p>
                <p className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#667792]">{selectedRow.requesterNote || "전달된 메모가 없습니다."}</p>
              </div>
              <label className="block">
                <span className="mb-2 block text-[13px] font-semibold text-[#263957]">관리자 처리 메모</span>
                <textarea ref={adminNoteRef} value={adminNote} onChange={(event) => setAdminNote(event.target.value)} className="min-h-[90px] w-full resize-y rounded-[10px] border border-[#dbe5f7] px-3 py-2.5 text-[13px] leading-6 text-[#263957] outline-none focus:border-[#bcd1ff]" placeholder="신청자에게 전달할 처리 내용이나 취소 사유를 입력하세요." />
              </label>
              {message ? <p className="text-[12px] font-semibold text-[#526784]">{message}</p> : null}
            </div>
            <div className="flex flex-wrap justify-end gap-2 border-t border-[#edf1f6] px-5 py-4 sm:px-6">
              <button type="button" disabled={savingStatus || selectedRow.status === "completed" || selectedRow.status === "cancelled"} onClick={() => void updateStatus("cancelled")} className="h-9 cursor-pointer rounded-[9px] px-3 text-[12px] font-semibold text-[#d64a5f] hover:bg-[#fff1f3] disabled:cursor-not-allowed disabled:opacity-50">신청 취소</button>
              <button type="button" disabled={savingStatus || selectedRow.status !== "pending"} onClick={() => void updateStatus("in_progress")} className="om-btn-secondary h-9 cursor-pointer rounded-[9px] px-3 text-[12px] shadow-none disabled:cursor-not-allowed disabled:opacity-50">처리 시작</button>
              <button type="button" disabled={savingStatus || selectedRow.status === "completed" || selectedRow.status === "cancelled"} onClick={() => void updateStatus("completed")} className="om-btn-primary h-9 cursor-pointer rounded-[9px] px-3 text-[12px] shadow-none disabled:cursor-not-allowed disabled:opacity-50">{savingStatus ? "완료 처리 중..." : selectedRow.feeAmount === 0 ? "연결 완료 처리" : `연결 완료 및 ${formatAssistanceFee(selectedRow.feeAmount)} 결제`}</button>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
