"use client";

import { useState } from "react";
import { 
  ShieldCheck, Shield, Users, Activity, 
  Database, HardDriveDownload, History, Server,
  Search, MoreHorizontal, CheckCircle2, AlertTriangle, Key
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Table, TableBody, TableCell, TableHead, 
  TableHeader, TableRow 
} from "@/components/ui/table";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, 
  DropdownMenuSeparator, DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu";

const mockUsers = [
  { id: "USR-001", name: "Super Admin", email: "admin@k-creation.dz", role: "Super Admin", status: "Active", lastLogin: "2 mins ago" },
  { id: "USR-002", name: "Sarah Lamine", email: "s.lamine@k-creation.dz", role: "Sales Manager", status: "Active", lastLogin: "1 hour ago" },
  { id: "USR-003", name: "Ahmed Benali", email: "a.benali@k-creation.dz", role: "Support Tech", status: "Active", lastLogin: "3 hours ago" },
  { id: "USR-004", name: "Karim M.", email: "k.m@k-creation.dz", role: "Warehouse", status: "Suspended", lastLogin: "2 days ago" },
];

const mockLogs = [
  { id: "LOG-991", user: "Super Admin", action: "Exported Database Backup", module: "System", time: "10 mins ago", status: "Success" },
  { id: "LOG-992", user: "Sarah Lamine", action: "Created Quote #QT-2024-084", module: "Sales", time: "1 hour ago", status: "Success" },
  { id: "LOG-993", user: "System", action: "Failed Login Attempt (IP: 41.22.x.x)", module: "Auth", time: "2 hours ago", status: "Failed" },
  { id: "LOG-994", user: "Ahmed Benali", action: "Resolved Ticket #TCK-1045", module: "Support", time: "3 hours ago", status: "Success" },
];

const getRoleBadge = (role: string) => {
  switch (role) {
    case "Super Admin": return <Badge className="bg-brand-red/20 text-brand-red border-brand-red/30"><Shield className="w-3 h-3 mr-1"/> Super Admin</Badge>;
    case "Sales Manager": return <Badge className="bg-blue-500/20 text-blue-400 border-blue-500/30">Sales</Badge>;
    case "Support Tech": return <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30">Support</Badge>;
    default: return <Badge className="bg-gray-500/20 text-gray-400 border-gray-500/30">{role}</Badge>;
  }
};

export default function SuperAdminDashboard() {
  const [activeTab, setActiveTab] = useState("users");
  const [searchQuery, setSearchQuery] = useState("");

  const filteredUsers = mockUsers.filter(u => 
    u.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    u.email.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-bold text-white tracking-tight flex items-center gap-3">
            <ShieldCheck className="w-8 h-8 text-brand-red" />
            Super Admin Portal
          </h2>
          <p className="text-gray-400 mt-1">Manage users, roles, system backups, and security logs.</p>
        </div>
        <Button className="bg-brand-red hover:bg-brand-red/90 text-white font-semibold">
          <Database className="w-4 h-4 mr-2" /> Backup Database Now
        </Button>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="bg-brand-charcoal border border-white/10 p-1">
          <TabsTrigger value="users" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">User Management</TabsTrigger>
          <TabsTrigger value="roles" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">Roles & Permissions</TabsTrigger>
          <TabsTrigger value="logs" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">Activity Logs</TabsTrigger>
          <TabsTrigger value="system" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">System Monitor</TabsTrigger>
        </TabsList>

        {/* USER MANAGEMENT TAB */}
        <TabsContent value="users" className="mt-6">
          <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm overflow-hidden">
            <div className="p-4 border-b border-white/10 flex items-center justify-between bg-black/20">
              <div className="relative w-full max-w-sm">
                <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-500" />
                <Input 
                  placeholder="Search users by name or email..." 
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9 bg-black/40 border-white/10 focus-visible:ring-brand-red text-white"
                />
              </div>
              <Button variant="outline" className="border-white/10 bg-transparent text-white hover:bg-white/5">
                <Users className="w-4 h-4 mr-2" /> Invite User
              </Button>
            </div>
            
            <div className="overflow-x-auto">
              <Table>
                <TableHeader className="bg-black/40 hover:bg-black/40">
                  <TableRow className="border-white/10 hover:bg-transparent">
                    <TableHead className="text-gray-400 font-semibold">User</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Role</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Last Login</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Status</TableHead>
                    <TableHead className="text-right text-gray-400 font-semibold">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredUsers.map((user) => (
                    <TableRow key={user.id} className="border-white/5 hover:bg-white/5 transition-colors">
                      <TableCell>
                        <div className="font-bold text-white">{user.name}</div>
                        <div className="text-xs text-gray-400 mt-1">{user.email}</div>
                      </TableCell>
                      <TableCell>{getRoleBadge(user.role)}</TableCell>
                      <TableCell className="text-gray-400 text-sm">{user.lastLogin}</TableCell>
                      <TableCell>
                        {user.status === 'Active' ? 
                          <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30">Active</Badge> : 
                          <Badge className="bg-brand-red/20 text-brand-red border-brand-red/30">Suspended</Badge>
                        }
                      </TableCell>
                      <TableCell className="text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0 text-gray-400 hover:text-white hover:bg-white/10">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="bg-brand-charcoal border-white/10 text-white w-48">
                            <DropdownMenuItem className="focus:bg-white/10 cursor-pointer"><Key className="w-4 h-4 mr-2"/> Reset Password</DropdownMenuItem>
                            <DropdownMenuItem className="focus:bg-white/10 cursor-pointer"><Shield className="w-4 h-4 mr-2"/> Change Role</DropdownMenuItem>
                            <DropdownMenuSeparator className="bg-white/10" />
                            {user.status === 'Active' ? (
                              <DropdownMenuItem className="focus:bg-brand-red focus:text-white cursor-pointer text-brand-red">Suspend User</DropdownMenuItem>
                            ) : (
                              <DropdownMenuItem className="focus:bg-emerald-500/20 focus:text-emerald-400 cursor-pointer">Reactivate User</DropdownMenuItem>
                            )}
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>

        {/* ACTIVITY LOGS TAB */}
        <TabsContent value="logs" className="mt-6">
          <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm overflow-hidden">
            <CardHeader className="border-b border-white/10 bg-black/20">
              <CardTitle className="text-white flex items-center gap-2"><History className="w-5 h-5 text-gray-400"/> System Activity Logs</CardTitle>
            </CardHeader>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader className="bg-black/40 hover:bg-black/40">
                  <TableRow className="border-white/10 hover:bg-transparent">
                    <TableHead className="text-gray-400 font-semibold">Time</TableHead>
                    <TableHead className="text-gray-400 font-semibold">User / IP</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Module</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Action</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockLogs.map((log) => (
                    <TableRow key={log.id} className="border-white/5 hover:bg-white/5 transition-colors">
                      <TableCell className="text-gray-400 text-sm whitespace-nowrap">{log.time}</TableCell>
                      <TableCell className="font-medium text-white">{log.user}</TableCell>
                      <TableCell>
                        <Badge variant="outline" className="text-gray-300 border-white/20">{log.module}</Badge>
                      </TableCell>
                      <TableCell className="text-gray-300 text-sm">{log.action}</TableCell>
                      <TableCell>
                        {log.status === 'Success' ? 
                          <span className="flex items-center text-emerald-400 text-sm"><CheckCircle2 className="w-4 h-4 mr-1"/> Success</span> : 
                          <span className="flex items-center text-brand-red text-sm"><AlertTriangle className="w-4 h-4 mr-1"/> Failed</span>
                        }
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>

        {/* SYSTEM MONITOR TAB */}
        <TabsContent value="system" className="mt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-white flex items-center gap-2"><Server className="w-5 h-5 text-blue-400"/> KVM2 Server Status</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex justify-between items-center text-sm border-b border-white/10 pb-2">
                  <span className="text-gray-400">API Connection</span>
                  <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30">Online</Badge>
                </div>
                <div className="flex justify-between items-center text-sm border-b border-white/10 pb-2">
                  <span className="text-gray-400">WebSocket Ping</span>
                  <span className="text-emerald-400 font-mono">24ms</span>
                </div>
                <div className="flex justify-between items-center text-sm border-b border-white/10 pb-2">
                  <span className="text-gray-400">Uptime</span>
                  <span className="text-white">99.98% (45 days)</span>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-white flex items-center gap-2"><Database className="w-5 h-5 text-purple-400"/> Database Health</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex justify-between items-center text-sm border-b border-white/10 pb-2">
                  <span className="text-gray-400">Storage Used</span>
                  <span className="text-white">12.4 GB / 50 GB</span>
                </div>
                <div className="w-full bg-black/50 rounded-full h-2 border border-white/5 mb-4">
                  <div className="bg-purple-500 h-full rounded-full" style={{ width: '25%' }}></div>
                </div>
                <Button className="w-full bg-white/10 hover:bg-white/20 text-white mt-4 border border-white/10">
                  <HardDriveDownload className="w-4 h-4 mr-2" /> Download Full Export (.SQL)
                </Button>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
