import React, { useState, useEffect } from 'react';
import { Search, ChevronDown, ChevronUp, Check, Save, Loader2, AlertCircle, Users, Server, Shield } from 'lucide-react';
import { Badge } from './ui/badge';
import { Card } from './ui/card';
import { cn } from '../lib/utils';

const apiHeaders = () => ({
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${localStorage.getItem('auth_token') ?? ''}`,
});

interface UserInfo {
  id: string;
  username: string;
  email: string;
  role: string;
}

interface ServerInfo {
  id: string;
  name: string;
}

interface Permission {
  id: string;
  userId: string;
  serverId: string;
}

export const RightsManagement: React.FC = () => {
  const [users, setUsers] = useState<UserInfo[]>([]);
  const [servers, setServers] = useState<ServerInfo[]>([]);
  const [userPermissions, setUserPermissions] = useState<Record<string, Permission[]>>({});
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [tab, setTab] = useState<'users' | 'roles'>('users');

  const fetchData = async () => {
    try {
      const [usersRes, serversRes, permsRes] = await Promise.all([
        fetch('/api/users/search?q=', { headers: apiHeaders() }),
        fetch('/api/servers', { headers: apiHeaders() }),
        fetch('/api/permissions', { headers: apiHeaders() }),
      ]);

      const usersData = await usersRes.json();
      const serversData = await serversRes.json();
      const permsData = await permsRes.json();

      setUsers(usersData.users ?? []);
      setServers(serversData.servers ?? []);

      // Group permissions by userId
      const grouped: Record<string, Permission[]> = {};
      (permsData.permissions ?? []).forEach((p: Permission) => {
        if (!grouped[p.userId]) grouped[p.userId] = [];
        grouped[p.userId].push(p);
      });
      setUserPermissions(grouped);
    } catch (err) {
      console.error('Failed to fetch rights data', err);
    } finally {
      setLoading(false);
    }
  };

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

  const togglePermission = async (userId: string, serverId: string) => {
    const existing = userPermissions[userId]?.find(p => p.serverId === serverId);
    try {
      if (existing) {
        await fetch(`/api/permissions?id=${existing.id}`, {
          method: 'DELETE',
          headers: apiHeaders(),
        });
        setUserPermissions(prev => ({
          ...prev,
          [userId]: prev[userId].filter(p => p.id !== existing.id),
        }));
      } else {
        const res = await fetch('/api/permissions', {
          method: 'POST',
          headers: apiHeaders(),
          body: JSON.stringify({ userId, serverId }),
        });
        const newPerm = await res.json();
        setUserPermissions(prev => ({
          ...prev,
          [userId]: [...(prev[userId] || []), newPerm],
        }));
      }
    } catch (err) {
      console.error('Failed to toggle permission', err);
    }
  };

  const filteredUsers = users.filter(u =>
    u.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
    u.email.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-black tracking-tight text-foreground">Permissions</h2>
          <p className="text-sm text-muted-foreground mt-1">Choose which users have access to which servers.</p>
        </div>
      </div>

      <Card className="border-border/50 bg-card/40 backdrop-blur-xl p-1 relative overflow-hidden">
        <div className="flex p-1 gap-1">
          <button
            onClick={() => setTab('users')}
            className={cn(
              "flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all",
              tab === 'users'
                ? "bg-primary text-primary-foreground shadow-lg shadow-primary/20"
                : "text-muted-foreground hover:bg-muted hover:text-foreground"
            )}
          >
            <Users className="w-4 h-4" />
            Users
          </button>
          <button
            onClick={() => setTab('roles')}
            className={cn(
              "flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all",
              tab === 'roles'
                ? "bg-primary text-primary-foreground shadow-lg shadow-primary/20"
                : "text-muted-foreground hover:bg-muted hover:text-foreground"
            )}
          >
            <Shield className="w-4 h-4" />
            Roles
          </button>
        </div>
      </Card>

      {tab === 'users' && (
        <div className="space-y-6">
          <div className="relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
            <input
              type="text"
              placeholder="Search by username or email..."
              className="w-full pl-12 pr-4 py-4 bg-card/40 border border-border/50 rounded-2xl text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all"
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
            />
          </div>

          {loading ? (
             <div className="flex flex-col items-center justify-center py-20 gap-4">
                <Loader2 className="w-10 h-10 animate-spin text-primary opacity-20" />
                <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/40">Loading users...</span>
             </div>
          ) : (
            <div className="grid grid-cols-1 gap-4">
              {filteredUsers.map(user => (
                <Card key={user.id} className="border-border/50 bg-card/40 backdrop-blur-sm group hover:border-primary/30 transition-all">
                  <div className="p-6">
                    <div className="flex items-center justify-between mb-6">
                      <div className="flex items-center gap-4">
                        <div className="w-12 h-12 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary font-black text-xl">
                          {user.username.slice(0, 1).toUpperCase()}
                        </div>
                        <div>
                          <h4 className="font-black text-lg text-foreground tracking-tight">{user.username}</h4>
                          <p className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">{user.email || 'No email'}</p>
                        </div>
                      </div>
                      <Badge className="bg-primary/10 text-primary border-primary/20 text-[10px] font-black uppercase tracking-widest">
                        {user.role}
                      </Badge>
                    </div>

                    <div className="space-y-4">
                      <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-muted-foreground/60 border-b border-border/10 pb-2">
                        <Server className="w-3.5 h-3.5" />
                        Server Access
                      </div>
                      
                      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
                        {servers.map(server => {
                          const hasAccess = userPermissions[user.id]?.some(p => p.serverId === server.id);
                          return (
                            <button
                              key={server.id}
                              onClick={() => togglePermission(user.id, server.id)}
                              className={cn(
                                "flex items-center justify-between px-4 py-2.5 rounded-xl border transition-all text-xs font-bold",
                                hasAccess
                                  ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-500"
                                  : "bg-muted/30 border-border/50 text-muted-foreground/40 hover:border-border"
                              )}
                            >
                              <span className="truncate mr-2">{server.name}</span>
                              {hasAccess && <Check className="w-3.5 h-3.5 flex-shrink-0" />}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </div>
      )}

      {tab === 'roles' && (
        <Card className="border-dashed border-2 py-32 bg-muted/5">
           <div className="flex flex-col items-center justify-center text-center space-y-4 opacity-40">
              <Shield className="w-16 h-16 text-muted-foreground" />
              <div className="space-y-1">
                <h3 className="text-xl font-black tracking-tighter">Role Management</h3>
                <p className="text-sm text-muted-foreground max-w-xs mx-auto">
                  Role management is only available to owners.
                </p>
              </div>
           </div>
        </Card>
      )}
    </div>
  );
};
