import { useState, useEffect } from 'react';
import { getRoles, deleteRole, updateRole } from '../services/roleService';
import type { Role } from '../types/role';
import { Button } from '@/components/ui/button';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { toast } from 'react-hot-toast';
import { Shield, Edit, Trash2, Plus, UserPlus } from 'lucide-react';
import { CreateRoleModal } from '../components/CreateRoleModal';
import { EditRoleModal } from '../components/EditRoleModal';
import { AssignRoleModal } from '../components/AssignRoleModal';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog';

// FE-PAGE-011: Complete Roles page implementation

export function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isAssignModalOpen, setIsAssignModalOpen] = useState(false);
  const [assignUserId, setAssignUserId] = useState<string>('');
  const [assignUserName, setAssignUserName] = useState<string>('');
  const [roleToDelete, setRoleToDelete] = useState<Role | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  const loadRoles = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const loadedRoles = await getRoles();
      setRoles(loadedRoles);
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to load roles';
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleToggleActive = async (role: Role) => {
    try {
      await updateRole(role.id, { is_active: !role.is_active });
      toast.success(
        `Role ${!role.is_active ? 'activated' : 'deactivated'} successfully`,
      );
      loadRoles();
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to update role';
      toast.error(errorMessage);
    }
  };

  const handleDeleteClick = (role: Role) => {
    if (role.is_system) {
      toast.error('Cannot delete system roles');
      return;
    }
    setRoleToDelete(role);
  };

  const handleDeleteConfirm = async () => {
    if (!roleToDelete) return;

    try {
      setIsDeleting(true);
      await deleteRole(roleToDelete.id);
      toast.success('Role deleted successfully');
      loadRoles();
      setRoleToDelete(null);
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to delete role';
      toast.error(errorMessage);
    } finally {
      setIsDeleting(false);
    }
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setIsEditModalOpen(true);
  };

  const handleAssignRole = (userId: string, userName?: string) => {
    setAssignUserId(userId);
    setAssignUserName(userName || '');
    setIsAssignModalOpen(true);
  };

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <LoadingSpinner />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-destructive mb-2">Error</h2>
              <p className="text-muted-foreground">{error}</p>
              <Button onClick={loadRoles} className="mt-4" variant="outline">
                Retry
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold mb-2">Roles Management</h1>
          <p className="text-muted-foreground">
            Manage user roles and permissions
          </p>
        </div>
        <CreateRoleModal onRoleCreated={loadRoles} />
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Roles
          </CardTitle>
        </CardHeader>
        <CardContent>
          {roles.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No roles found</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Display Name</TableHead>
                  <TableHead>Description</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Permissions</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {roles.map((role) => (
                  <TableRow key={role.id}>
                    <TableCell className="font-medium">{role.name}</TableCell>
                    <TableCell>{role.display_name}</TableCell>
                    <TableCell className="max-w-md truncate">
                      {role.description}
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={role.is_active ? 'success' : 'warning'}
                      >
                        {role.is_active ? 'Active' : 'Inactive'}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {role.is_system ? (
                        <Badge variant="primary">System</Badge>
                      ) : (
                        <Badge variant="default">Custom</Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      {role.permissions?.length || 0} permissions
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleToggleActive(role)}
                          disabled={role.is_system}
                        >
                          {role.is_active ? 'Deactivate' : 'Activate'}
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleEdit(role)}
                          disabled={role.is_system}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleDeleteClick(role)}
                                  disabled={role.is_system}
                                >
                                  <Trash2 className="h-4 w-4 text-destructive" />
                                </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* FE-PAGE-011: Assign Role Section */}
      <Card className="mt-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <UserPlus className="h-5 w-5" />
            Assign Role to User
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2">
            <Input
              placeholder="User ID"
              value={assignUserId}
              onChange={(e) => setAssignUserId(e.target.value)}
              className="flex-1"
            />
            <Input
              placeholder="User Name (optional)"
              value={assignUserName}
              onChange={(e) => setAssignUserName(e.target.value)}
              className="flex-1"
            />
            <Button
              onClick={() => handleAssignRole(assignUserId, assignUserName)}
              disabled={!assignUserId}
            >
              <UserPlus className="h-4 w-4 mr-2" />
              Assign Role
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Modals */}
      {editingRole && (
        <EditRoleModal
          role={editingRole}
          open={isEditModalOpen}
          onClose={() => {
            setIsEditModalOpen(false);
            setEditingRole(null);
          }}
          onRoleUpdated={loadRoles}
        />
      )}

      <AssignRoleModal
        userId={assignUserId}
        userName={assignUserName}
        availableRoles={roles.filter((r) => r.is_active)}
        open={isAssignModalOpen}
        onClose={() => {
          setIsAssignModalOpen(false);
          setAssignUserId('');
          setAssignUserName('');
        }}
        onRoleAssigned={() => {
          // Could refresh user roles here if needed
        }}
      />
    </div>
  );
}
