"use client";

import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

import { BottomToast, type BottomToastNotice } from "@/components/bottom-toast";

type SendingServerOption = {
  enabled: boolean;
  host: string;
  isDefault: boolean;
  key: string;
  label: string;
  port: number;
};

type SendingServerResponse = {
  message?: string;
  ok?: boolean;
  result?: {
    sendingServer?: SendingServerOption;
  };
};

type KavenixDomainSendingServerSelectProps = {
  cleanedAt: string | null;
  domain: string;
  domainId: number;
  initialServerKey: string;
  servers: SendingServerOption[];
};

export function KavenixDomainSendingServerSelect({
  cleanedAt,
  domain,
  domainId,
  initialServerKey,
  servers,
}: KavenixDomainSendingServerSelectProps) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);
  const [savedServerKey, setSavedServerKey] = useState(initialServerKey);
  const [selectedServerKey, setSelectedServerKey] = useState(initialServerKey);
  const [toast, setToast] = useState<BottomToastNotice | null>(null);
  const selectedServer = servers.find(
    (server) => server.key === selectedServerKey,
  );
  const configuredInitialServer = servers.some(
    (server) => server.key === initialServerKey,
  );
  const canSubmit =
    !cleanedAt &&
    !busy &&
    Boolean(selectedServer?.enabled) &&
    selectedServerKey !== savedServerKey;

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

    const timeoutId = window.setTimeout(() => setToast(null), 4600);
    return () => window.clearTimeout(timeoutId);
  }, [toast]);

  async function updateSendingServer() {
    if (!canSubmit || !selectedServer) {
      return;
    }

    if (
      !window.confirm(
        `${domain}의 발송 서버를 ${selectedServer.label}(${selectedServer.host}:${selectedServer.port})로 변경할까요?\n\n새로 전송하는 메일부터 적용됩니다. 선택한 서버가 이 도메인의 기존 메일함 인증정보를 받을 수 있도록 먼저 구성되어 있어야 합니다.`,
      )
    ) {
      return;
    }

    setBusy(true);

    try {
      const response = await fetch(
        `/api/kavenix/domains/${domainId}/sending-server`,
        {
          body: JSON.stringify({ serverKey: selectedServerKey }),
          headers: { "Content-Type": "application/json" },
          method: "POST",
        },
      );
      const payload = (await response.json()) as SendingServerResponse;

      if (!response.ok || payload.ok !== true) {
        throw new Error(payload.message || "발송 서버를 변경하지 못했습니다.");
      }

      const updatedServerKey =
        payload.result?.sendingServer?.key ?? selectedServerKey;
      setSavedServerKey(updatedServerKey);
      setSelectedServerKey(updatedServerKey);
      setToast({
        message: payload.message || "발송 서버를 변경했습니다.",
        tone: "success",
      });
      router.refresh();
    } catch (error) {
      setToast({
        message:
          error instanceof Error
            ? error.message
            : "발송 서버를 변경하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setBusy(false);
    }
  }

  return (
    <>
      <div className="min-w-[180px] text-left">
        <div className="flex items-center gap-1.5">
          <select
            aria-label={`${domain} 발송 서버`}
            value={selectedServerKey}
            disabled={Boolean(cleanedAt) || busy}
            onChange={(event) => setSelectedServerKey(event.target.value)}
            className="h-9 min-w-0 flex-1 cursor-pointer rounded-[10px] border border-[#dce5f3] bg-white px-2.5 text-[12px] font-semibold text-[#344761] outline-none transition-colors focus:border-[#8eb2ff] focus:ring-2 focus:ring-[#dce8ff] disabled:cursor-not-allowed disabled:bg-[#f4f6fa] disabled:text-[#9aa8bf]"
          >
            {!configuredInitialServer ? (
              <option value={initialServerKey} disabled>
                구성 누락 ({initialServerKey})
              </option>
            ) : null}
            {servers.map((server) => (
              <option key={server.key} value={server.key} disabled={!server.enabled}>
                {server.label}{server.enabled ? "" : " (중지)"}
              </option>
            ))}
          </select>
          <button
            type="button"
            onClick={updateSendingServer}
            disabled={!canSubmit}
            className="h-9 shrink-0 rounded-[10px] bg-[#2f6df6] px-3 text-[12px] font-semibold text-white transition-colors hover:bg-[#245de3] disabled:cursor-not-allowed disabled:bg-[#b7c6df]"
          >
            {busy ? "변경 중" : "변경"}
          </button>
        </div>
        <p
          className={`mt-1.5 truncate text-[11px] ${
            selectedServer ? "text-[#71819a]" : "font-semibold text-[#c84c58]"
          }`}
          title={
            selectedServer
              ? `${selectedServer.host}:${selectedServer.port}`
              : `발송 서버 관리에 ${initialServerKey} 서버가 없습니다.`
          }
        >
          {selectedServer
            ? `${selectedServer.host}:${selectedServer.port}`
            : "서버 구성 누락"}
        </p>
      </div>

      {toast ? <BottomToast notice={toast} onClose={() => setToast(null)} /> : null}
    </>
  );
}
