"use client";

import React, { useState } from "react";
import useSWR from "swr";
import axios from "@/lib/axios";
import PageBreadcrumb from "@/components/common/PageBreadCrumb";
import { useTranslations } from "next-intl";
import ComponentCard from "@/components/common/ComponentCard";
import CertificateTable from "@/components/certificates/CertificateTable";
import { PlusIcon } from "@/icons";
import { useAuth } from "@/hooks/useAuth";
import { useToast } from "@/context/ToastContext";
import Button from "@/components/ui/button/Button";
import ConfirmationModal from "@/components/common/ConfirmationModal";
import CreateCertificateModal from "@/components/certificates/CreateCertificateModal";
import PageLoader from "@/components/ui/PageLoader";

const fetcher = (url: string) => axios.get(url).then((res) => res.data);

export default function CertificatesClient() {
  const { user } = useAuth();
  const t = useTranslations("Certificates");
  const { addToast } = useToast();
  const { data, error, mutate, isLoading } = useSWR("/api/certificates", fetcher);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isSettingUp, setIsSettingUp] = useState(false);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [confirmDeleteUuid, setConfirmDeleteUuid] = useState<string | null>(null);

  const isAdmin = user?.role === "admin" || user?.role === "owner";

  const handleDelete = async (uuid: string) => {
    setIsDeleting(true);
    try {
      await axios.delete(`/api/certificates/${uuid}`);
      mutate();
      addToast(t("toast_deleted"), "success");
      setConfirmDeleteUuid(null);
    } catch (err: any) {
      console.error(err);
      addToast(err.response?.data?.message || t("toast_delete_failed"), "error");
    } finally {
      setIsDeleting(false);
    }
  };

  const handleSetupCa = async () => {
    setIsSettingUp(true);
    try {
      await axios.post("/api/ca/setup");
      mutate();
      addToast(t("toast_ca_setup_success"), "success");
    } catch (err: any) {
      console.error(err);
      addToast(err.response?.data?.message || t("toast_ca_setup_failed"), "error");
    } finally {
      setIsSettingUp(false);
    }
  };

  if (error) return <div className="p-10 text-center text-error-500">{t("load_failed")}</div>;

  const certificates = data?.data?.data || [];
  const caStatus = data?.ca_status;
  const caReady = caStatus?.is_ready;
  
  // Defaults for the modal
  const createDefaults = {
    organizationName: "TrustLab CA",
    localityName: "Jakarta",
    stateOrProvinceName: "DKI Jakarta",
    countryName: "ID"
  };

  return (
    <div>
      <PageBreadcrumb pageTitle={t("page_title")} />
      
      <div className="space-y-6">
        {!caReady && !isLoading && (
          <div className="p-4 bg-yellow-50 border-l-4 border-yellow-400 dark:bg-yellow-900/20 dark:border-yellow-600 rounded-md flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div className="flex flex-col">
              <span className="text-sm font-bold text-yellow-800 dark:text-yellow-200">
                {t("ca_not_setup_title")}
              </span>
              <span className="text-xs text-yellow-700 dark:text-yellow-300">
                {t("ca_missing_msg", { missing: caStatus?.missing?.join(", ").replace(/_/g, " ") })}
              </span>
              {!isAdmin && (
                <span className="mt-1 text-xs font-medium text-yellow-800 dark:text-yellow-200">
                  {t("contact_admin_msg")}
                </span>
              )}
            </div>
            {isAdmin && (
              <Button 
                onClick={handleSetupCa}
                size="sm"
                className="bg-yellow-600 hover:bg-yellow-700 text-white border-none h-auto whitespace-nowrap w-full sm:w-auto"
                loading={isSettingUp}
              >
                {t("btn_setup_ca")}
              </Button>
            )}
          </div>
        )}

        <ComponentCard 
          title={t("management_title")} 
          desc={t("management_desc")}
          headerAction={
            <button
              onClick={() => setIsCreateModalOpen(true)}
              disabled={!caReady}
              className={`flex items-center justify-center gap-2 px-4 py-2 text-sm font-medium text-white transition rounded-lg bg-brand-500 hover:bg-brand-600 ${!caReady ? "opacity-50 cursor-not-allowed" : ""}`}
            >
              <PlusIcon className="w-4 h-4" />
              {t("btn_generate_new")}
            </button>
          }
        >
          <CertificateTable 
            certificates={certificates} 
            onDelete={setConfirmDeleteUuid} 
          />
          
          {(isLoading || isDeleting) && (
            <div className="absolute inset-0 bg-white/50 dark:bg-gray-900/50 flex items-center justify-center z-10 backdrop-blur-sm rounded-2xl">
               <PageLoader text={t("processing")} className="h-full" />
            </div>
          )}
        </ComponentCard>
      </div>

      <CreateCertificateModal
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSuccess={() => mutate()}
        defaults={createDefaults}
      />

      <ConfirmationModal
        isOpen={confirmDeleteUuid !== null}
        onClose={() => setConfirmDeleteUuid(null)}
        onConfirm={() => confirmDeleteUuid && handleDelete(confirmDeleteUuid)}
        title={t("delete_title")}
        message={t("delete_msg")}
        isLoading={isDeleting}
        confirmLabel={t("delete_confirm")}
        requiredInput="DELETE"
      />
    </div>
  );
}
