"use client";

import { useEffect, useState } from "react";

type Platform = "android" | "windows-store" | "windows-exe";
type ManagedPlatform = Exclude<Platform, "windows-exe">;
type Policy = {
  platform: Platform;
  latestVersion: string;
  latestBuild: number;
  minimumVersion: string;
  minimumBuild: number;
  updateMode: "recommended" | "required";
  releaseNotes: string;
  updatedAt: string | null;
};
type Data = {
  policies: Policy[];
  legacyNativeAuthEnabled: boolean;
  legacyMailboxCount: number;
};

const labels: Record<ManagedPlatform, string> = {
  android: "Android · Google Play",
  "windows-store": "Windows · Microsoft Store",
};

const fieldClass = "h-10 w-full rounded-[10px] border border-[#dbe5f7] bg-white px-3 text-[13px] text-[#1a2943] outline-none focus:border-[#8bb1ff]";
const isManagedPolicy = (policy: Policy): policy is Policy & { platform: ManagedPlatform } => policy.platform !== "windows-exe";

export function KavenixAppVersionDashboard() {
  const [data, setData] = useState<Data | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    fetch("/api/kavenix/app-version-policy", { cache: "no-store" })
      .then(async (response) => {
        if (!response.ok) throw new Error("버전 정책을 불러오지 못했습니다.");
        return response.json() as Promise<Data>;
      })
      .then((result) => { if (active) setData(result); })
      .catch((error) => { if (active) setNotice(error instanceof Error ? error.message : "조회에 실패했습니다."); });
    return () => { active = false; };
  }, []);

  const updatePolicy = (platform: Platform, change: Partial<Policy>) => {
    setData((current) => current ? {
      ...current,
      policies: current.policies.map((policy) => policy.platform === platform ? { ...policy, ...change } : policy),
    } : current);
  };

  const savePolicy = async (policy: Policy & { platform: ManagedPlatform }) => {
    if (busy) return;
    setBusy(policy.platform);
    setNotice(null);
    try {
      const response = await fetch("/api/kavenix/app-version-policy", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(policy),
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.message || "저장하지 못했습니다.");
      updatePolicy(policy.platform, result.policy);
      setNotice(`${labels[policy.platform]} 버전 정책을 저장했습니다.`);
    } catch (error) {
      setNotice(error instanceof Error ? error.message : "저장하지 못했습니다.");
    } finally {
      setBusy(null);
    }
  };

  const toggleLegacy = async () => {
    if (!data || busy) return;
    const nextEnabled = !data.legacyNativeAuthEnabled && data.legacyMailboxCount === 0;
    if (data.legacyNativeAuthEnabled && !window.confirm(
      "구버전 앱의 로그인을 차단하고 현재 호환 중인 메일함 자격을 폐기합니다. Android와 Windows 새 버전이 실제 설치 가능한지 확인하셨나요?",
    )) return;
    setBusy("legacy");
    setNotice(null);
    try {
      const response = await fetch("/api/kavenix/app-version-policy", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "legacy-native-auth", enabled: nextEnabled }),
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.message || "설정을 변경하지 못했습니다.");
      setData((current) => current ? {
        ...current,
        legacyNativeAuthEnabled: result.legacyNativeAuthEnabled,
        legacyMailboxCount: result.remaining,
      } : current);
      setNotice(result.remaining > 0 && !nextEnabled
        ? `${result.remaining}개 메일함의 구버전 자격 폐기가 남았습니다. 다시 눌러 재시도해주세요.`
        : nextEnabled ? "구버전 앱 로그인을 허용했습니다." : "구버전 앱 로그인과 직접 IMAP 자격을 차단했습니다.");
    } catch (error) {
      setNotice(error instanceof Error ? error.message : "설정을 변경하지 못했습니다.");
    } finally {
      setBusy(null);
    }
  };

  if (!data) return <div className="px-4 py-8 text-[13px] text-[#70819d] sm:px-6 lg:px-8">{notice ?? "버전 정책을 불러오는 중입니다."}</div>;

  return (
    <div className="space-y-5 px-3 py-5 sm:px-4 lg:px-8">
      <div className="rounded-[14px] border border-[#dbe5f7] bg-[#f8faff] p-4 text-[13px] leading-6 text-[#4f6384]">
        최신 버전은 실제 스토어 심사 완료·배포 후 입력하세요. 권장은 이전 버전에 안내만 표시하고, 강제는 최신 버전 미만 로그인을 막습니다. 최소 지원 버전 미만은 방식과 무관하게 차단됩니다.
      </div>
      {notice && <p role="status" className="rounded-[10px] bg-[#edf4ff] px-4 py-3 text-[13px] text-[#2456ae]">{notice}</p>}
      <div className="grid gap-4 xl:grid-cols-2">
        {data.policies.filter(isManagedPolicy).map((policy) => (
          <section key={policy.platform} className="min-w-0 rounded-[16px] border border-[#e1e8f3] bg-white p-4 sm:p-5">
            <h2 className="text-[15px] font-semibold text-[#16233c]">{labels[policy.platform]}</h2>
            <div className="mt-5 grid grid-cols-[minmax(0,1fr)_90px] gap-3">
              <label className="min-w-0 text-[12px] font-semibold text-[#526684]">최신 버전
                <input className={`${fieldClass} mt-1`} value={policy.latestVersion} onChange={(event) => updatePolicy(policy.platform, { latestVersion: event.target.value })} placeholder="1.0.37" />
              </label>
              <label className="min-w-0 text-[12px] font-semibold text-[#526684]">빌드
                <input className={`${fieldClass} mt-1`} type="number" min="0" value={policy.latestBuild} onChange={(event) => updatePolicy(policy.platform, { latestBuild: Number(event.target.value) })} />
              </label>
              <label className="min-w-0 text-[12px] font-semibold text-[#526684]">최소 지원 버전
                <input className={`${fieldClass} mt-1`} value={policy.minimumVersion} onChange={(event) => updatePolicy(policy.platform, { minimumVersion: event.target.value })} placeholder="1.0.36" />
              </label>
              <label className="min-w-0 text-[12px] font-semibold text-[#526684]">빌드
                <input className={`${fieldClass} mt-1`} type="number" min="0" value={policy.minimumBuild} onChange={(event) => updatePolicy(policy.platform, { minimumBuild: Number(event.target.value) })} />
              </label>
            </div>
            <label className="mt-4 block text-[12px] font-semibold text-[#526684]">업데이트 방식
              <select className={`${fieldClass} mt-1`} value={policy.updateMode} onChange={(event) => updatePolicy(policy.platform, { updateMode: event.target.value as Policy["updateMode"] })}>
                <option value="recommended">권장 업데이트</option>
                <option value="required">강제 업데이트</option>
              </select>
            </label>
            <label className="mt-4 block text-[12px] font-semibold text-[#526684]">업데이트 안내
              <textarea className="mt-1 min-h-20 w-full resize-y rounded-[10px] border border-[#dbe5f7] bg-white px-3 py-2 text-[13px] font-normal text-[#1a2943] outline-none focus:border-[#8bb1ff]" maxLength={1000} value={policy.releaseNotes} onChange={(event) => updatePolicy(policy.platform, { releaseNotes: event.target.value })} />
            </label>
            <button type="button" disabled={Boolean(busy)} onClick={() => void savePolicy(policy)} className="mt-4 h-10 w-full cursor-pointer rounded-[10px] bg-[#2f6df6] px-4 text-[13px] font-semibold text-white disabled:cursor-not-allowed disabled:opacity-50">{busy === policy.platform ? "저장 중..." : "버전 정책 저장"}</button>
          </section>
        ))}
      </div>
      <section className="rounded-[16px] border border-[#f0d7a9] bg-[#fffaf0] p-4 sm:p-5">
        <h2 className="text-[15px] font-semibold text-[#754b17]">구버전 앱 호환</h2>
        <p className="mt-2 text-[13px] leading-6 text-[#805e30]">현재 구버전 앱 로그인이 {data.legacyNativeAuthEnabled ? "허용" : "차단"}되어 있으며, 직접 IMAP 자격이 남은 활성 메일함은 {data.legacyMailboxCount}개입니다. 새 Android·Windows 버전 설치가 가능해진 뒤 차단하세요. 차단 시 기존 앱은 업데이트 안내와 함께 로그인할 수 없고 직접 IMAP 자격도 폐기됩니다.</p>
        <button type="button" disabled={Boolean(busy)} onClick={() => void toggleLegacy()} className="mt-4 h-10 cursor-pointer rounded-[10px] border border-[#d9bd85] bg-white px-4 text-[13px] font-semibold text-[#754b17] disabled:cursor-not-allowed disabled:opacity-50">
          {data.legacyNativeAuthEnabled ? "구버전 앱 로그인 차단" : data.legacyMailboxCount > 0 ? "남은 직접 자격 폐기 재시도" : "구버전 앱 로그인 다시 허용"}
        </button>
      </section>
    </div>
  );
}
