"use client";

import { useState, useEffect } from "react";
import {
  Shield,
  FileText,
  MapPin,
  AlertTriangle,
  Activity,
  Users,
  Globe,
  XCircle,
} from "lucide-react";
import AuditLogViewer from "./AuditLogViewer";
import LoginActivityTable from "./LoginActivityTable";
import SuspiciousActivityCard from "./SuspiciousActivityCard";

interface SecurityStats {
  totalLogins24h: number;
  failedLogins24h: number;
  uniqueUsers24h: number;
  uniqueCountries24h: number;
  suspiciousActivities: SuspiciousActivity[];
}

interface SuspiciousActivity {
  type:
    | "multiple_failures"
    | "new_location"
    | "unusual_time"
    | "rapid_attempts";
  userId: string;
  userEmail: string;
  userName: string | null;
  details: string;
  count: number;
  lastOccurrence: string;
}

type TabType = "audit" | "logins" | "alerts";

export default function SecurityDashboard() {
  const [activeTab, setActiveTab] = useState<TabType>("audit");
  const [stats, setStats] = useState<SecurityStats | null>(null);
  const [loadingStats, setLoadingStats] = useState(true);

  useEffect(() => {
    fetchStats();
  }, []);

  const fetchStats = async () => {
    try {
      const response = await fetch("/api/staff/dashboard/security/stats");
      if (response.ok) {
        const data = await response.json();
        setStats(data);
      }
    } catch (error) {
      console.error("Failed to fetch security stats:", error);
    } finally {
      setLoadingStats(false);
    }
  };

  const tabs = [
    { id: "audit" as TabType, name: "Audit Logs", icon: FileText },
    { id: "logins" as TabType, name: "Login Activity", icon: MapPin },
    { id: "alerts" as TabType, name: "Security Alerts", icon: AlertTriangle },
  ];

  return (
    <div className="space-y-6">
      {/* Stats Overview */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          icon={Activity}
          label="Total Logins (24h)"
          value={loadingStats ? "-" : stats?.totalLogins24h.toString() || "0"}
          color="blue"
        />
        <StatCard
          icon={XCircle}
          label="Failed Logins (24h)"
          value={loadingStats ? "-" : stats?.failedLogins24h.toString() || "0"}
          color="red"
          highlight={stats && stats.failedLogins24h > 10}
        />
        <StatCard
          icon={Users}
          label="Active Users (24h)"
          value={loadingStats ? "-" : stats?.uniqueUsers24h.toString() || "0"}
          color="green"
        />
        <StatCard
          icon={Globe}
          label="Countries (24h)"
          value={
            loadingStats ? "-" : stats?.uniqueCountries24h.toString() || "0"
          }
          color="purple"
        />
      </div>

      {/* Suspicious Activity Alerts */}
      {stats && stats.suspiciousActivities.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4">
          <div className="flex items-center gap-2 mb-3">
            <AlertTriangle className="w-5 h-5 text-red-600" />
            <h3 className="font-semibold text-red-800">
              Suspicious Activity Detected
            </h3>
            <span className="ml-auto bg-red-600 text-white text-xs font-bold px-2 py-0.5 rounded-full">
              {stats.suspiciousActivities.length}
            </span>
          </div>
          <div className="space-y-2">
            {stats.suspiciousActivities.slice(0, 3).map((activity, index) => (
              <SuspiciousActivityCard key={index} activity={activity} />
            ))}
            {stats.suspiciousActivities.length > 3 && (
              <button
                onClick={() => setActiveTab("alerts")}
                className="text-sm text-red-700 hover:text-red-800 font-medium"
              >
                View all {stats.suspiciousActivities.length} alerts...
              </button>
            )}
          </div>
        </div>
      )}

      {/* Tabs */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <div className="border-b border-gray-200">
          <nav className="flex -mb-px">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex items-center gap-2 px-6 py-4 text-sm font-medium border-b-2 transition-colors ${
                    isActive
                      ? "border-brand-green text-brand-green"
                      : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {tab.name}
                  {tab.id === "alerts" &&
                    stats &&
                    stats.suspiciousActivities.length > 0 && (
                      <span className="ml-1 bg-red-100 text-red-600 text-xs font-bold px-1.5 py-0.5 rounded-full">
                        {stats.suspiciousActivities.length}
                      </span>
                    )}
                </button>
              );
            })}
          </nav>
        </div>

        <div className="p-6">
          {activeTab === "audit" && <AuditLogViewer />}
          {activeTab === "logins" && <LoginActivityTable />}
          {activeTab === "alerts" && (
            <AlertsPanel activities={stats?.suspiciousActivities || []} />
          )}
        </div>
      </div>
    </div>
  );
}

function StatCard({
  icon: Icon,
  label,
  value,
  color,
  highlight,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
  color: "blue" | "red" | "green" | "purple";
  highlight?: boolean;
}) {
  const colors = {
    blue: "bg-blue-50 text-blue-600 border-blue-100",
    red: "bg-red-50 text-red-600 border-red-100",
    green: "bg-green-50 text-green-600 border-green-100",
    purple: "bg-purple-50 text-purple-600 border-purple-100",
  };

  return (
    <div
      className={`bg-white rounded-xl border p-4 ${
        highlight ? "border-red-300 ring-2 ring-red-100" : "border-gray-200"
      }`}
    >
      <div className="flex items-center gap-3">
        <div className={`p-2.5 rounded-lg ${colors[color]}`}>
          <Icon className="w-5 h-5" />
        </div>
        <div>
          <p className="text-2xl font-bold text-brand-ink">{value}</p>
          <p className="text-xs text-gray-500">{label}</p>
        </div>
      </div>
    </div>
  );
}

function AlertsPanel({ activities }: { activities: SuspiciousActivity[] }) {
  if (activities.length === 0) {
    return (
      <div className="text-center py-12">
        <Shield className="w-12 h-12 text-green-500 mx-auto mb-4" />
        <h3 className="text-lg font-semibold text-brand-ink mb-2">All Clear</h3>
        <p className="text-gray-500">
          No suspicious activity detected in the last 24 hours.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-semibold text-brand-ink">Security Alerts</h3>
        <span className="text-sm text-gray-500">
          {activities.length} active alerts
        </span>
      </div>
      {activities.map((activity, index) => (
        <SuspiciousActivityCard key={index} activity={activity} expanded />
      ))}
    </div>
  );
}
