"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { getAuditLogs, AuditLog } from "@/lib/api";
import { TwoFactorSetup } from "./TwoFactorSetup";
import { SSOConfig } from "./SSOConfig";
import { DLPPolicies } from "./DLPPolicies";
import { InformationBarriers } from "./InformationBarriers";
import {
  Shield, KeyRound, Lock, FileText, ShieldBan, ShieldAlert, ScrollText,
  ArrowLeft, RefreshCw, LogOut, Settings,
} from "lucide-react";

type SecurityTab = "2fa" | "sso" | "dlp" | "barriers" | "audit";

const TABS: { key: SecurityTab; label: string; icon: typeof Shield }[] = [
  { key: "2fa", label: "Two-Factor Auth", icon: KeyRound },
  { key: "sso", label: "SSO / SAML", icon: Lock },
  { key: "dlp", label: "DLP Policies", icon: ShieldAlert },
  { key: "barriers", label: "Information Barriers", icon: ShieldBan },
  { key: "audit", label: "Audit Logs", icon: ScrollText },
];

export function SecurityCenter() {
  const { isAuthenticated, loading: authLoading, logout } = useAuth();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<SecurityTab>("2fa");
  const [auditLogs, setAuditLogs] = useState<AuditLog[]>([]);
  const [loadingLogs, setLoadingLogs] = useState(false);

  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.replace("/login");
    }
  }, [authLoading, isAuthenticated, router]);

  useEffect(() => {
    if (activeTab === "audit") {
      setLoadingLogs(true);
      getAuditLogs()
        .then((logs) => setAuditLogs(Array.isArray(logs) ? logs : []))
        .catch((err) => console.error("Failed to load audit logs:", err))
        .finally(() => setLoadingLogs(false));
    }
  }, [activeTab]);

  if (authLoading) {
    return (
      <div className="flex h-screen items-center justify-center bg-slack-darkpurple">
        <div className="text-white text-lg animate-pulse">Loading Security Center...</div>
      </div>
    );
  }

  return (
    <div className="flex h-screen bg-white">
      {/* Far left: workspace sidebar */}
      <div className="w-[60px] bg-slack-purple flex flex-col items-center py-4 gap-3">
        <div className="w-10 h-10 rounded-md bg-white text-slack-purple flex items-center justify-center font-bold text-lg">
          CA
        </div>
        <button
          onClick={() => router.push("/chat")}
          className="w-10 h-10 rounded-md hover:bg-slack-lightpurple flex items-center justify-center text-white"
          title="Back to chat"
        >
          <ArrowLeft size={20} />
        </button>
        <button
          onClick={() => router.push("/settings")}
          className="w-10 h-10 rounded-md hover:bg-slack-lightpurple flex items-center justify-center text-white"
          title="Settings"
        >
          <Settings size={20} />
        </button>
        <button
          onClick={logout}
          className="mt-auto w-10 h-10 rounded-md hover:bg-slack-lightpurple flex items-center justify-center text-white"
          title="Sign out"
        >
          <LogOut size={20} />
        </button>
      </div>

      {/* Main content */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Header */}
        <div className="px-6 py-3 border-b border-gray-200">
          <div className="flex items-center gap-2 mb-3">
            <Shield size={22} className="text-slack-purple" />
            <h1 className="text-lg font-bold text-gray-800">Security Center</h1>
            <span className="text-sm text-gray-400">Workspace security & compliance</span>
          </div>

          {/* Tabs */}
          <div className="flex gap-1 flex-wrap">
            {TABS.map((tab) => {
              const Icon = tab.icon;
              const isActive = activeTab === tab.key;
              return (
                <button
                  key={tab.key}
                  onClick={() => setActiveTab(tab.key)}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
                    isActive
                      ? "bg-slack-purple text-white"
                      : "text-gray-600 hover:bg-gray-100"
                  }`}
                >
                  <Icon size={14} />
                  <span>{tab.label}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 max-w-3xl">
          {activeTab === "2fa" && <TwoFactorSetup />}
          {activeTab === "sso" && <SSOConfig />}
          {activeTab === "dlp" && <DLPPolicies />}
          {activeTab === "barriers" && <InformationBarriers />}
          {activeTab === "audit" && (
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <FileText size={20} className="text-slack-purple" />
                <h3 className="text-sm font-semibold text-gray-800">Security Audit Logs</h3>
              </div>
              {loadingLogs ? (
                <div className="flex items-center justify-center py-8 text-gray-400">
                  <RefreshCw size={20} className="animate-pulse" />
                </div>
              ) : auditLogs.length === 0 ? (
                <p className="text-sm text-gray-400 py-8 text-center">No audit logs found.</p>
              ) : (
                <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
                  <div className="divide-y divide-gray-100">
                    {auditLogs.map((log) => (
                      <div key={log.id} className="p-3 flex items-start gap-3 hover:bg-gray-50">
                        <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center flex-shrink-0">
                          <Shield size={14} className="text-gray-400" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-gray-800">
                            {log.action.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())}
                          </p>
                          <p className="text-xs text-gray-400">
                            By {log.actor?.name || log.actor?.email || "Unknown"} &middot;{" "}
                            {new Date(log.created_at).toLocaleString()}
                          </p>
                          {log.details && (
                            <p className="text-xs text-gray-500 mt-1">{log.details}</p>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default SecurityCenter;