/* eslint-disable */

import {
  Box,
  CircularProgress,
  Chip,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
  Tooltip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Fade
} from '@mui/material';

import { CheckCircleOutlined, EnvironmentOutlined, MailOutlined, PhoneOutlined, StopOutlined, UserOutlined } from '@ant-design/icons';

import MainCard from 'components/MainCard';
import { useQuery } from '@tanstack/react-query';

import { Fragment, useState } from 'react';
import TitleCard from 'components/TitleCard';
import CreateUsers from './CreateUsers';
import { getusers } from '../api';

const Users = () => {
  const [createDialogOpen, setCreateDialogOpen] = useState(false);

  const {
    data: usersList = [],
    isLoading: getuserisloading,
    error: getusererror,
    refetch: getUsersRefetch
  } = useQuery({
    queryKey: ['userlist'],
    queryFn: () =>
      getusers({
        roleid: 3,
        tenantid: 1087,
        limit: 20,
        offset: 0
      })
  });

  const renderStatus = (status) => {
    const isActive = status === 'Active';
    return (
      <Chip
        icon={isActive ? <CheckCircleOutlined /> : <StopOutlined />}
        label={status || 'Inactive'}
        color={isActive ? 'success' : 'default'}
        variant="light"
        size="small"
        sx={{ minWidth: 96 }}
      />
    );
  };

  const renderContact = (email, phone) => (
    <Stack spacing={0.5}>
      {email ? (
        <Stack direction="row" alignItems="center" spacing={1} sx={{ color: 'text.secondary' }}>
          <MailOutlined style={{ fontSize: 14 }} />
          <Typography variant="body2" noWrap sx={{ maxWidth: 220 }}>
            {email}
          </Typography>
        </Stack>
      ) : null}
      {phone ? (
        <Stack direction="row" alignItems="center" spacing={1} sx={{ color: 'text.secondary' }}>
          <PhoneOutlined style={{ fontSize: 14 }} />
          <Typography variant="body2" noWrap sx={{ maxWidth: 220 }}>
            {phone}
          </Typography>
        </Stack>
      ) : null}
      {!email && !phone ? (
        <Typography variant="body2" color="text.secondary">
          No contact information.
        </Typography>
      ) : null}
    </Stack>
  );

  const renderAddress = (user) => {
    const address = [user.address, user.city, user.suburb].filter(Boolean).join(', ');

    return (
      <Tooltip title={address || 'No address available'}>
        <Stack direction="row" alignItems="center" spacing={1} sx={{ color: 'text.secondary', cursor: 'pointer' }}>
          <EnvironmentOutlined style={{ fontSize: 16 }} />
          <Typography variant="body2" noWrap sx={{ maxWidth: 220 }}>
            {address || '-'}
          </Typography>
        </Stack>
      </Tooltip>
    );
  };

  return (
    <Fragment>
      <TitleCard
        title="Users"
        secondary={
          <Button variant="contained" onClick={() => setCreateDialogOpen(true)}>
            Create User
          </Button>
        }
      />

      {getuserisloading ? (
        <Stack alignItems="center" justifyContent="center" sx={{ p: 4 }}>
          <CircularProgress />
          <Typography variant="body2" sx={{ mt: 2, color: 'text.secondary' }}>
            Loading users...
          </Typography>
        </Stack>
      ) : getusererror ? (
        <Typography color="error" variant="body2">
          {getusererror.message || 'Error loading users'}
        </Typography>
      ) : (
        <TableContainer
          component={Paper}
          variant="outlined"
          sx={{
            mt: 2,
            overflowX: 'auto',
            maxHeight: 'calc(100vh - 180px)'
          }}
        >
          <Table stickyHeader>
            <TableHead>
              <TableRow>
                <TableCell sx={{ position: 'sticky !important' }}>#</TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Name</TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Contact</TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Address</TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Status</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {usersList.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5}>
                    <Stack sx={{ width: '100%' }} display={'flex'} alignItems={'center'} justifyContent={'center'}>
                      <Empty description={'No Users'} />
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                usersList.map((user, index) => {
                  const fullName = `${user.firstname || ''} ${user.lastname || ''}`.trim() || 'Unknown user';

                  return (
                    <TableRow
                      key={user.userid}
                      sx={{
                        '&:last-child td, &:last-child th': { border: 0 },
                        '&:hover': { bgcolor: 'action.selected' }
                      }}
                    >
                      <TableCell>{index + 1}</TableCell>

                      <TableCell>
                        <Stack direction="row" alignItems="center" spacing={1}>
                          <UserOutlined style={{ fontSize: 18, color: '#9e9e9e' }} />
                          <Box>
                            <Typography variant="subtitle1">{fullName}</Typography>
                            <Typography variant="caption" color="text.secondary">
                              Role ID: {user.roleid || '-'}
                            </Typography>
                          </Box>
                        </Stack>
                      </TableCell>

                      <TableCell>{renderContact(user.email, user.contactno)}</TableCell>
                      <TableCell>{renderAddress(user)}</TableCell>
                      <TableCell>{renderStatus(user.status)}</TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}
      <Dialog open={createDialogOpen} TransitionComponent={Fade} transitionDuration={300} maxWidth="md" fullWidth>
        <DialogContent>
          {/* //Instead of passing setter directly, pass a handler: */}
          <CreateUsers onClose={() => setCreateDialogOpen(false)} getUsersRefetch />
        </DialogContent>
      </Dialog>
    </Fragment>
  );
};
export default Users;
