"use client";

import { useState, useCallback } from "react";
import { getCertInfo, type CertInfo } from "@/lib/api";

export function useAdminCert() {
  const [certInfo, setCertInfo] = useState<CertInfo | null>(null);
  const [certLoading, setCertLoading] = useState(false);
  const [certError, setCertError] = useState("");
  const [certSuccess, setCertSuccess] = useState("");
  const [certFile, setCertFile] = useState<File | null>(null);
  const [keyFile, setKeyFile] = useState<File | null>(null);
  const [certUploadLoading, setCertUploadLoading] = useState(false);
  const [selfSignedCN, setSelfSignedCN] = useState("archivmail");
  const [selfSignedDNS, setSelfSignedDNS] = useState("archivmail");
  const [selfSignedIPs, setSelfSignedIPs] = useState("192.168.1.131");
  const [selfSignedYears, setSelfSignedYears] = useState("10");
  const [selfSignedLoading, setSelfSignedLoading] = useState(false);
  const [acmeDomain, setAcmeDomain] = useState("");
  const [acmeEmail, setAcmeEmail] = useState("");
  const [acmeLoading, setAcmeLoading] = useState(false);
  const [acmeOutput, setAcmeOutput] = useState("");

  const loadCert = useCallback(async () => {
    setCertLoading(true);
    setCertError("");
    try {
      const info = await getCertInfo();
      setCertInfo(info);
    } catch (e) {
      setCertError(String(e));
    } finally {
      setCertLoading(false);
    }
  }, []);

  return {
    certInfo,
    setCertInfo,
    certLoading,
    certError,
    setCertError,
    certSuccess,
    setCertSuccess,
    certFile,
    setCertFile,
    keyFile,
    setKeyFile,
    certUploadLoading,
    setCertUploadLoading,
    selfSignedCN,
    setSelfSignedCN,
    selfSignedDNS,
    setSelfSignedDNS,
    selfSignedIPs,
    setSelfSignedIPs,
    selfSignedYears,
    setSelfSignedYears,
    selfSignedLoading,
    setSelfSignedLoading,
    acmeDomain,
    setAcmeDomain,
    acmeEmail,
    setAcmeEmail,
    acmeLoading,
    setAcmeLoading,
    acmeOutput,
    setAcmeOutput,
    loadCert,
  };
}
