'use client';

import { useState } from "react";
import { 
  TableRow, 
  TableCell, 
  Chip, 
  Button, 
  CircularProgress, 
  Typography,
  Tooltip
} from "@mui/material";
import { toggleUserRoleAction } from "./actions";
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
import PersonIcon from '@mui/icons-material/Person';
import SecurityIcon from '@mui/icons-material/Security';

interface UserRowProps {
  user: {
    id: string;
    email: string;
    role: string;
    name?: string | null;
  };
  currentUserId: string;
  isBootstrapAdmin: boolean;
}

export default function UserRow({ user, currentUserId, isBootstrapAdmin }: UserRowProps) {
  const [loading, setLoading] = useState(false);

  const handleToggle = async () => {
    const confirmMsg = `Are you sure you want to change ${user.email} to a ${user.role === 'ADMIN' ? 'USER' : 'ADMIN'}?`;
    if (!confirm(confirmMsg)) return;

    setLoading(true);
    try {
      await toggleUserRoleAction(user.id);
    } catch (err: any) {
      alert(err.message || "An error occurred while updating the role.");
    } finally {
      setLoading(false);
    }
  };

  const isSelf = user.id === currentUserId;
  const isAdmin = user.role === "ADMIN";
  
  /**
   * REVISED LOGIC:
   * We only "Lock" the button if:
   * 1. You are the Bootstrap Admin AND
   * 2. You are already an ADMIN in the database.
   * This allows you to promote yourself from USER to ADMIN, but prevents demotion.
   */
  const cannotDemote = isBootstrapAdmin && isSelf && isAdmin;

  return (
    <TableRow hover sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
      <TableCell>
        <Typography variant="body2" fontWeight={isSelf ? 700 : 400}>
          {user.email}
        </Typography>
        {isSelf && (
          <Typography variant="caption" color="primary" sx={{ display: 'block' }}>
            Current Session
          </Typography>
        )}
      </TableCell>

      <TableCell>
        <Chip 
          icon={isAdmin ? <AdminPanelSettingsIcon /> : <PersonIcon />}
          label={isAdmin ? "ADMIN" : "USER"} 
          color={isAdmin ? "primary" : "default"} 
          variant={isAdmin ? "filled" : "outlined"}
          size="small"
          sx={{ fontWeight: 600, px: 1 }}
        />
      </TableCell>

      <TableCell align="right">
        {cannotDemote ? (
          <Tooltip title="The Primary Admin cannot be demoted to ensure system access.">
            <span>
              <Button
                size="small"
                variant="outlined"
                disabled
                startIcon={<SecurityIcon />}
                sx={{ minWidth: 120, textTransform: 'none' }}
              >
                Primary Admin
              </Button>
            </span>
          </Tooltip>
        ) : (
          <Button
            size="small"
            variant="contained"
            color={isAdmin ? "inherit" : "primary"}
            onClick={handleToggle}
            disabled={loading}
            sx={{ minWidth: 120, textTransform: 'none' }}
            startIcon={loading ? <CircularProgress size={16} color="inherit" /> : null}
          >
            {isAdmin ? "Demote to User" : "Promote to Admin"}
          </Button>
        )}
      </TableCell>
    </TableRow>
  );
}