import React, { useMemo, useState } from 'react';
import {
  Avatar,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme
} from '@mui/material';
import { MdOutlineAdminPanelSettings, MdEdit, MdDeleteOutline, MdAdd } from 'react-icons/md';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import Loader from 'components/Loader';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import PageHeader from 'components/nearle_components/PageHeader';
import StatCard from 'components/nearle_components/StatCard';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';
import { getAppUsers, createAppUser, updateAppUser, deleteAppUser } from 'pages/api/doormileApi';
import { enqueueSnackbar } from 'notistack';

// ============================================================================
// GET /admin/users confirmed live: { id, email, first_name, phone, role,
// status } — role is a free-text string ("admin", "rep" both observed
// live; the auth doc's "1 admin, 3 manager, 4 executive" describes the JWT
// roleid encoding for login, not this list's field). No `name`/`roleid` at
// all. POST/PUT body shape for create/edit is still unconfirmed (write
// endpoints, not exercised live this pass) — kept as first_name/phone/role
// to match the GET shape.
// ============================================================================

const DT = {
  radiusCard: 14,
  radiusField: 10,
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  borderHover: '#cbd5e1',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};
const a = (c, suffix) => `${c}${suffix}`;
const soft = (c) => a(c, '18');
const ring = (c) => a(c, '26');
const BRAND = '#C01227';
const ROLES = ['admin', 'manager', 'executive', 'rep'];
const roleLabel = (role) => (role ? role.charAt(0).toUpperCase() + role.slice(1) : '—');

const emptyForm = { id: null, first_name: '', email: '', phone: '', password: '', role: 'admin', status: 'Active' };

const AppUsers = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const queryClient = useQueryClient();
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState(emptyForm);

  const { data: users = [], isLoading } = useQuery({ queryKey: ['admin-app-users'], queryFn: getAppUsers });

  const rows = useMemo(() => {
    if (!debouncedSearch) return users;
    const q = debouncedSearch.toLowerCase().trim();
    return users.filter((row) => [row.first_name, row.email, row.phone].filter(Boolean).some((f) => String(f).toLowerCase().includes(q)));
  }, [users, debouncedSearch]);

  const stats = useMemo(() => {
    const total = users.length;
    const admins = users.filter((u) => String(u.role).toLowerCase() === 'admin').length;
    return { total, admins };
  }, [users]);

  const opentoast = (message, variant = 'error') =>
    enqueueSnackbar(message, { variant, anchorOrigin: { vertical: 'top', horizontal: 'right' }, autoHideDuration: 2000 });

  const saveMutation = useMutation({
    mutationFn: (payload) => (payload.id ? updateAppUser(payload.id, payload.data) : createAppUser(payload.data)),
    onSuccess: (res) => {
      if (res.success) {
        opentoast(form.id ? 'User updated' : 'User created', 'success');
        queryClient.invalidateQueries({ queryKey: ['admin-app-users'] });
        setDialogOpen(false);
      } else {
        opentoast(res.message || 'Failed to save user');
      }
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to save user')
  });

  const deleteMutation = useMutation({
    mutationFn: (id) => deleteAppUser(id),
    onSuccess: (res) => {
      if (res.success) {
        opentoast('User deleted', 'success');
        queryClient.invalidateQueries({ queryKey: ['admin-app-users'] });
      } else {
        opentoast(res.message || 'Failed to delete user');
      }
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to delete user')
  });

  const openCreate = () => {
    setForm(emptyForm);
    setDialogOpen(true);
  };

  const openEdit = (row) => {
    setForm({
      id: row.id,
      first_name: row.first_name || '',
      email: row.email || '',
      phone: row.phone || '',
      password: '',
      role: row.role || 'admin',
      status: row.status || 'Active'
    });
    setDialogOpen(true);
  };

  const handleDelete = (row) => {
    if (window.confirm(`Delete staff user "${row.first_name}"?`)) deleteMutation.mutate(row.id);
  };

  const handleSave = () => {
    if (!form.first_name || !form.email || (!form.id && !form.password)) {
      opentoast('Fill Name, Email' + (!form.id ? ' and Password' : ''));
      return;
    }
    const { id, ...data } = form;
    if (id && !data.password) delete data.password;
    saveMutation.mutate({ id, data });
  };

  return (
    <>
      {(isLoading || saveMutation.isPending || deleteMutation.isPending) && <Loader />}

      <PageHeader
        title="App Users"
        subtitle="Live · Staff Logins"
        live
        action={
          <Button variant="contained" startIcon={<MdAdd size={16} />} onClick={openCreate} sx={{ bgcolor: BRAND, whiteSpace: 'nowrap' }}>
            New User
          </Button>
        }
      />

      <Grid container spacing={{ xs: 2, md: 2.5 }} sx={{ mb: { xs: 1.5, md: 2 } }}>
        <Grid item xs={6}>
          <StatCard title="Total Staff" value={stats.total} icon={<MdOutlineAdminPanelSettings size={20} />} color={BRAND} />
        </Grid>
        <Grid item xs={6}>
          <StatCard title="Admins" value={stats.admins} icon={<MdOutlineAdminPanelSettings size={20} />} color="#6366f1" />
        </Grid>
      </Grid>

      <Paper
        elevation={0}
        sx={{ mt: { xs: 1.5, md: 2 }, p: { xs: 1, md: 1.5 }, borderTopLeftRadius: DT.radiusCard / 8, borderTopRightRadius: DT.radiusCard / 8, border: '1px solid', borderColor: DT.borderSubtle, borderBottom: 0, background: '#fff' }}
      >
        <Stack direction={{ xs: 'column', sm: 'row' }} alignItems={{ xs: 'stretch', sm: 'center' }} justifyContent="space-between" spacing={1.25}>
          <Typography variant="body2" sx={{ color: DT.textPrimary, fontWeight: 700 }}>
            {users.length} total · {rows.length} shown
          </Typography>
          <Box sx={{ width: { xs: '100%', sm: 280 } }}>
            <DebounceSearchBar
              value={searchword}
              onChange={setSearchword}
              onDebouncedChange={setDebouncedSearch}
              placeholder="Search staff (ctrl+k)"
              sx={{
                m: 0,
                width: '100%',
                borderRadius: DT.radiusField + 'px',
                bgcolor: DT.surface,
                '& fieldset': { borderColor: DT.borderSubtle, borderWidth: 1 },
                '&:hover fieldset': { borderColor: DT.borderHover },
                '&.Mui-focused fieldset': { borderColor: BRAND, borderWidth: 1.5 },
                '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring(BRAND)}` }
              }}
            />
          </Box>
        </Stack>
      </Paper>

      <Paper elevation={0} sx={{ borderBottomLeftRadius: DT.radiusCard / 8, borderBottomRightRadius: DT.radiusCard / 8, border: '1px solid', borderColor: DT.borderSubtle, overflow: 'hidden', background: '#fff' }}>
        <TableContainer sx={{ maxHeight: { xs: 'calc(100vh - 260px)', md: 'calc(100vh - 190px)' } }}>
          <Table stickyHeader sx={{ minWidth: isMobile ? 820 : 880 }}>
            <TableHead>
              <TableRow sx={{ '& th': { backgroundColor: DT.surfaceAlt, color: DT.textSecondary, fontSize: 11, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', whiteSpace: 'nowrap', borderBottom: `1px solid ${DT.borderSubtle}` } }}>
                <TableCell>#</TableCell>
                <TableCell>Name</TableCell>
                <TableCell>Email</TableCell>
                <TableCell>Phone</TableCell>
                <TableCell>Role</TableCell>
                <TableCell>Status</TableCell>
                <TableCell align="right">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading && <OrdersTableSkeleton col={4} />}
              {rows.length === 0 && !isLoading ? (
                <TableRow>
                  <TableCell colSpan={7} sx={{ py: 6 }}>
                    <Stack alignItems="center" spacing={1.5}>
                      <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                        <MdOutlineAdminPanelSettings size={28} />
                      </Avatar>
                      <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                        No staff users to show
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                rows.map((row, index) => (
                  <TableRow key={row.id || index} sx={{ '& td': { borderBottom: `1px solid ${DT.divider}` }, '&:hover': { backgroundColor: DT.surfaceAlt } }}>
                    <TableCell>{index + 1}</TableCell>
                    <TableCell>
                      <Typography variant="body2" sx={{ fontWeight: 700 }}>
                        {row.first_name}
                      </Typography>
                    </TableCell>
                    <TableCell>{row.email}</TableCell>
                    <TableCell>{row.phone || '—'}</TableCell>
                    <TableCell>{roleLabel(row.role)}</TableCell>
                    <TableCell>{row.status || '—'}</TableCell>
                    <TableCell align="right">
                      <Stack direction="row" spacing={0.5} justifyContent="flex-end">
                        <Tooltip title="Edit user">
                          <IconButton size="small" onClick={() => openEdit(row)} sx={{ color: BRAND }}>
                            <MdEdit size={16} />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Delete user">
                          <IconButton size="small" onClick={() => handleDelete(row)} sx={{ color: '#ef4444' }}>
                            <MdDeleteOutline size={16} />
                          </IconButton>
                        </Tooltip>
                      </Stack>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ fontWeight: 700 }}>{form.id ? 'Edit User' : 'New Staff User'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 0.5 }}>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>Name</InputLabel>
                <TextField value={form.first_name} onChange={(e) => setForm((f) => ({ ...f, first_name: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>Email</InputLabel>
                <TextField type="email" value={form.email} onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>Phone</InputLabel>
                <TextField value={form.phone} onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>{form.id ? 'New Password (leave blank to keep unchanged)' : 'Password'}</InputLabel>
                <TextField type="password" value={form.password} onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Role</InputLabel>
                <Select fullWidth value={form.role} onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}>
                  {ROLES.map((r) => (
                    <MenuItem key={r} value={r}>
                      {roleLabel(r)}
                    </MenuItem>
                  ))}
                </Select>
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Status</InputLabel>
                <Select fullWidth value={form.status} onChange={(e) => setForm((f) => ({ ...f, status: e.target.value }))}>
                  <MenuItem value="Active">Active</MenuItem>
                  <MenuItem value="Inactive">Inactive</MenuItem>
                </Select>
              </Stack>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={() => setDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleSave} sx={{ bgcolor: BRAND }}>
            {form.id ? 'Save Changes' : 'Create'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default AppUsers;
