"use client";

import React, { useState } from "react";
import useSWR from "swr";
import axios from "@/lib/axios";
import PageBreadcrumb from "@/components/common/PageBreadCrumb";
import ComponentCard from "@/components/common/ComponentCard";
import RootCaTable from "@/components/admin/RootCaTable";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { useToast } from "@/context/ToastContext";
import ConfirmationModal from "@/components/common/ConfirmationModal";
import PageLoader from "@/components/ui/PageLoader";
import { useTranslations } from "next-intl";

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

function SyncButton({ onClick, disabled, isLoading, label, variant = 'blue' }: { onClick: () => void, disabled: boolean, isLoading: boolean, label: string, variant?: 'blue' | 'gray' | 'purple' | 'indigo' }) {
  const variantClasses = {
    blue: 'bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400',
    gray: 'bg-gray-600 hover:bg-gray-700 disabled:bg-gray-400',
    purple: 'bg-purple-600 hover:bg-purple-700 disabled:bg-purple-400',
    indigo: 'bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400',
  };

  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`flex items-center justify-center gap-2 px-3 py-1.5 ${variantClasses[variant]} text-white text-xs font-medium rounded-lg transition-all shadow-sm active:scale-95`}
    >
      {isLoading ? (
        <svg className="animate-spin h-3.5 w-3.5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
      ) : (
        <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
        </svg>
      )}
      {isLoading ? "Syncing..." : label}
    </button>
  );
}

export default function RootCaManagementClient() {
  const t = useTranslations("RootCA");
  const { user } = useAuth();
  const router = useRouter();
  const { addToast } = useToast();
  const { data, error, mutate, isLoading } = useSWR("/api/admin/ca-certificates", fetcher);
  const [isRenewing, setIsRenewing] = useState(false);
  const [isSyncing, setIsSyncing] = useState(false);
  const [confirmRenewUuid, setConfirmRenewUuid] = useState<string | null>(null);

  // Redirect if not admin or owner (double security, backend also checks)
  const { isAdminOrOwner } = useAuth();
  React.useEffect(() => {
    if (user && !isAdminOrOwner) {
      router.push("/dashboard");
    }
  }, [user, isAdminOrOwner, router]);

  const handleRenew = async (uuid: string) => {
    setIsRenewing(true);
    try {
      await axios.post(`/api/admin/ca-certificates/${uuid}/renew`, {
        days: 3650
      });
      mutate();
      addToast(t("toast_renew_success"), "success");
      setConfirmRenewUuid(null);
    } catch (err: any) {
      console.error(err);
      addToast(err.response?.data?.message || t("toast_renew_failed"), "error");
    } finally {
      setIsRenewing(false);
    }
  };

  const handleSyncCdn = async (type: 'all' | 'crt' | 'installers' | 'bundles') => {
    setIsSyncing(true);
    try {
      let endpoint = "/api/admin/ca-certificates/sync-cdn";
      let msg = "Full Sync successful";
      
      if (type === 'crt') {
        endpoint = "/api/admin/ca-certificates/sync-crt";
        msg = "CRT Files Sync successful";
      } else if (type === 'installers') {
        endpoint = "/api/admin/ca-certificates/sync-installers";
        msg = "Individual Installers Sync successful";
      } else if (type === 'bundles') {
        endpoint = "/api/admin/ca-certificates/sync-bundles";
        msg = "Global Bundles Sync successful";
      }

      const response = await axios.post(endpoint);
      addToast(response.data.message || msg, "success");
      mutate();
    } catch (err: any) {
      console.error(err);
      addToast(err.response?.data?.message || "Sync failed", "error");
    } finally {
      setIsSyncing(false);
    }
  };

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

  const certificates = data?.data || [];

  return (
    <div>
      <div className="flex flex-col md:flex-row md:items-center justify-between mb-4 gap-4">
        <PageBreadcrumb pageTitle={t("management_title")} />
        
        <div className="flex flex-wrap items-center gap-2">
          <SyncButton 
            onClick={() => handleSyncCdn('crt')} 
            disabled={isSyncing || isLoading} 
            isLoading={isSyncing}
            label="Sync CRT Only"
            variant="gray"
          />
          <SyncButton 
            onClick={() => handleSyncCdn('installers')} 
            disabled={isSyncing || isLoading} 
            isLoading={isSyncing}
            label="Sync Installers Only"
            variant="blue"
          />
          <SyncButton 
            onClick={() => handleSyncCdn('bundles')} 
            disabled={isSyncing || isLoading} 
            isLoading={isSyncing}
            label="Sync Full Bundles"
            variant="purple"
          />
          <SyncButton 
            onClick={() => handleSyncCdn('all')} 
            disabled={isSyncing || isLoading} 
            isLoading={isSyncing}
            label="Sync All to CDN"
            variant="indigo"
          />
        </div>
      </div>

      <div className="space-y-6">
        <ComponentCard
          title={t("card_title")}
          desc={t("card_desc")}
          className="relative"
        >
          <RootCaTable
            certificates={certificates}
            onRenew={setConfirmRenewUuid}
            isRenewing={isRenewing}
          />

          {(isLoading || isRenewing) && (
            <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 className="p-4 bg-blue-50 border-l-4 border-blue-400 dark:bg-blue-900/20 dark:border-blue-600 rounded-md">
            <h4 className="text-sm font-bold text-blue-800 dark:text-blue-200">{t("info_title")}</h4>
            <ul className="mt-2 text-xs text-blue-700 dark:text-blue-300 list-disc list-inside space-y-1">
                <li>{t("info_point_1")}</li>
                <li>{t("info_point_2")}</li>
                <li>{t("info_point_3")}</li>
                <li>{t("info_point_4")}</li>
            </ul>
        </div>
      </div>

      <ConfirmationModal
        isOpen={confirmRenewUuid !== null}
        onClose={() => setConfirmRenewUuid(null)}
        onConfirm={() => confirmRenewUuid && handleRenew(confirmRenewUuid)}
        title={t("renew_modal_title")}
        message={t("renew_modal_msg")}
        isLoading={isRenewing}
        confirmLabel={t("renew_modal_confirm")}
        variant="warning"
        requiredInput="RENEW"
      />
    </div>
  );
}
