import { useState, useMemo, useEffect } from 'react';
import {
  Card, Stack, Button, TextField, InputAdornment, Box, Tabs, Tab, Chip, Link,
  Table, TableBody, TableCell, TableContainer, TableHead, TableRow, IconButton,
  TablePagination, Typography, CircularProgress, Alert, Tooltip, Divider, useMediaQuery,
  Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import RefreshIcon from '@mui/icons-material/Refresh';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import MailOutlineIcon from '@mui/icons-material/MailOutline';
import PhoneOutlinedIcon from '@mui/icons-material/PhoneOutlined';
import GroupsOutlinedIcon from '@mui/icons-material/GroupsOutlined';
import AdminPanelSettingsOutlinedIcon from '@mui/icons-material/AdminPanelSettingsOutlined';
import BadgeOutlinedIcon from '@mui/icons-material/BadgeOutlined';
import SupportAgentOutlinedIcon from '@mui/icons-material/SupportAgentOutlined';
import ManageAccountsOutlinedIcon from '@mui/icons-material/ManageAccountsOutlined';
import PersonOutlineOutlinedIcon from '@mui/icons-material/PersonOutlineOutlined';

import PageHeader from '@/components/PageHeader';
import StatusChip from '@/components/StatusChip';
import EmptyState from '@/components/EmptyState';
import UserAvatar from '@/components/UserAvatar';
import TabLabelCount from '@/components/TabLabelCount';
import { fetchUsers, deleteUser } from '@/utils/apiClient';
import { toUser } from '@/utils/mappers';
import { titleCase } from '@/utils/format';
import UserFormDialog from './UserFormDialog';

// Per-role accent colour + icon, used for the avatar badge and role chip.
const ROLE_META = {
  admin: { color: 'primary', icon: AdminPanelSettingsOutlinedIcon },
  manager: { color: 'success', icon: ManageAccountsOutlinedIcon },
  rep: { color: 'info', icon: BadgeOutlinedIcon },
  support: { color: 'warning', icon: SupportAgentOutlinedIcon }
};
const roleMeta = (role) => ROLE_META[String(role || '').toLowerCase()] || { color: 'secondary', icon: PersonOutlineOutlinedIcon };

// Avatar with a small role-coloured badge in the corner.
function UserIdentity({ name, email, role }) {
  const { color, icon: RoleIcon } = roleMeta(role);
  const handle = email ? email.split('@')[0] : '';
  return (
    <Stack direction="row" spacing={1.5} alignItems="center">
      <Box sx={{ position: 'relative', display: 'inline-flex' }}>
        <UserAvatar name={name} size={40} sx={{ border: '2px solid', borderColor: `${color}.lighter` }} />
        <Box
          sx={{
            position: 'absolute', right: -3, bottom: -3, width: 18, height: 18, borderRadius: '50%',
            bgcolor: `${color}.main`, color: '#fff', display: 'inline-flex', alignItems: 'center',
            justifyContent: 'center', border: '2px solid #fff'
          }}
        >
          <RoleIcon sx={{ fontSize: 11 }} />
        </Box>
      </Box>
      <Box sx={{ minWidth: 0 }}>
        <Typography variant="body2" sx={{ fontWeight: 600, color: 'grey.800', lineHeight: 1.25 }}>{name}</Typography>
        {handle && <Typography variant="caption" color="text.secondary">@{handle}</Typography>}
      </Box>
    </Stack>
  );
}

function RoleCell({ role }) {
  const { color, icon: RoleIcon } = roleMeta(role);
  return (
    <Chip
      size="small"
      icon={<RoleIcon sx={{ fontSize: 15, ml: 0.5 }} />}
      label={titleCase(role)}
      sx={{
        fontWeight: 600,
        bgcolor: `${color === 'secondary' ? 'grey.100' : `${color}.lighter`}`,
        color: `${color === 'secondary' ? 'grey.700' : `${color}.dark`}`,
        '& .MuiChip-icon': { color: 'inherit' }
      }}
    />
  );
}

// Mobile presentation of a user row — a self-contained card instead of a wide table row.
function UserCard({ row, index, onEdit, onDelete }) {
  return (
    <Box sx={{ p: 1.75, borderRadius: 3, border: 1, borderColor: 'divider', bgcolor: 'background.paper' }}>
      <Stack direction="row" spacing={1.25} alignItems="flex-start">
        <Box sx={{ flexGrow: 1, minWidth: 0 }}>
          <UserIdentity name={row.name} email={row.email} role={row.role} />
        </Box>
        <RoleCell role={row.role} />
      </Stack>

      <Stack spacing={1} sx={{ mt: 1.75 }}>
        <Stack direction="row" spacing={1} alignItems="center" sx={{ minWidth: 0 }}>
          <MailOutlineIcon sx={{ fontSize: 16, color: 'grey.400', flexShrink: 0 }} />
          {row.email ? (
            <Link href={`mailto:${row.email}`} underline="hover" color="text.primary" noWrap sx={{ fontSize: '0.8125rem' }}>
              {row.email}
            </Link>
          ) : <Typography variant="body2" color="text.disabled">No email</Typography>}
        </Stack>
        <Stack direction="row" spacing={1} alignItems="center">
          <PhoneOutlinedIcon sx={{ fontSize: 16, color: 'grey.400', flexShrink: 0 }} />
          {row.phone ? (
            <Link href={`tel:${row.phone}`} underline="hover" color="text.primary" sx={{ fontSize: '0.8125rem' }}>
              {row.phone}
            </Link>
          ) : <Typography variant="body2" color="text.disabled">No phone</Typography>}
        </Stack>
      </Stack>

      <Divider sx={{ my: 1.5 }} />
      <Stack direction="row" spacing={1} justifyContent="space-between" alignItems="center">
        <Typography variant="caption" color="text.secondary">#{index}</Typography>
        <Stack direction="row" spacing={1}>
          <Button size="small" variant="outlined" startIcon={<EditOutlinedIcon fontSize="small" />} onClick={() => onEdit(row)}>Edit</Button>
          <Button size="small" variant="outlined" color="error" startIcon={<DeleteOutlineIcon fontSize="small" />} onClick={() => onDelete(row)}>Delete</Button>
        </Stack>
      </Stack>
    </Box>
  );
}

export default function TeamUsers() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const [tab, setTab] = useState(0);
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [rpp, setRpp] = useState(10);

  const [dialog, setDialog] = useState({ open: false, mode: 'add', initial: null });
  const [toDelete, setToDelete] = useState(null);
  const [deleting, setDeleting] = useState(false);

  const load = () => {
    setLoading(true);
    setError(null);
    fetchUsers()
      .then((points) => setUsers(points.map(toUser)))
      .catch((e) => setError(e.message || 'Failed to load team users'))
      .finally(() => setLoading(false));
  };

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

  const tabs = useMemo(() => {
    const seen = [];
    users.forEach((u) => { if (!seen.includes(u.role)) seen.push(u.role); });
    return [{ key: 'all', label: 'All' }, ...seen.map((r) => ({ key: r, label: titleCase(r) }))];
  }, [users]);

  const tabKey = tabs[Math.min(tab, tabs.length - 1)]?.key || 'all';

  const counts = useMemo(() => {
    const c = { all: users.length };
    users.forEach((u) => { c[u.role] = (c[u.role] || 0) + 1; });
    return c;
  }, [users]);

  const filtered = useMemo(
    () =>
      users.filter((u) => {
        const matchTab = tabKey === 'all' || u.role === tabKey;
        const matchSearch =
          !search || [u.name, u.email, u.phone, u.role].join(' ').toLowerCase().includes(search.toLowerCase());
        return matchTab && matchSearch;
      }),
    [users, tabKey, search]
  );

  const paged = filtered.slice(page * rpp, page * rpp + rpp);

  const handleSaved = () => { setDialog({ open: false, mode: 'add', initial: null }); load(); };

  const confirmDelete = async () => {
    setDeleting(true);
    try {
      await deleteUser(toDelete.id);
      setToDelete(null);
      load();
    } catch (e) {
      setError(e.message || 'Failed to delete user');
    } finally {
      setDeleting(false);
    }
  };

  return (
    <>
      <PageHeader
        title="App Users"
        breadcrumbs={[{ label: 'App Users' }]}
        action={
          <Stack direction="row" spacing={1.5} sx={{ width: { xs: '100%', sm: 'auto' } }}>
            <Button variant="outlined" startIcon={<RefreshIcon />} onClick={load} disabled={loading} sx={{ flex: { xs: 1, sm: 'none' } }}>Refresh</Button>
            <Button variant="contained" startIcon={<AddIcon />} onClick={() => setDialog({ open: true, mode: 'add', initial: null })} sx={{ flex: { xs: 1, sm: 'none' } }}>Add User</Button>
          </Stack>
        }
      />

      <Card sx={{ overflow: 'hidden' }}>
        <Box
          sx={{
            px: { xs: 1.75, sm: 2.5 }, py: 2, borderBottom: 1, borderColor: 'divider',
            display: 'flex', alignItems: 'center', gap: 1.5,
            background: (theme) => `linear-gradient(90deg, ${theme.palette.primary.lighter}66 0%, ${theme.palette.background.paper} 70%)`
          }}
        >
          <Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: 'primary.lighter', color: 'primary.main', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <GroupsOutlinedIcon fontSize="small" />
          </Box>
          <Box>
            <Typography variant="subtitle1" sx={{ fontWeight: 700, color: 'grey.800', lineHeight: 1.2 }}>App Users Directory</Typography>
            <Typography variant="caption" color="text.secondary">Manage console members, roles and access</Typography>
          </Box>
        </Box>

        <Stack direction={{ xs: 'column', md: 'row' }} spacing={1.5} sx={{ p: { xs: 1.5, sm: 2 } }} alignItems={{ md: 'center' }}>
          <TextField
            size="small" placeholder="Search by name, email, phone…" value={search} onChange={(e) => { setSearch(e.target.value); setPage(0); }}
            sx={{ width: { xs: '100%', md: 300 } }}
            InputProps={{ startAdornment: <InputAdornment position="start"><SearchIcon fontSize="small" /></InputAdornment> }}
          />
          <Box sx={{ flexGrow: 1 }} />
          {!loading && (
            <Stack direction="row" spacing={1} alignItems="center">
              <Typography variant="body2" color="text.secondary">
                {filtered.length} {filtered.length === 1 ? 'user' : 'users'}
              </Typography>
              <Chip size="small" label="live · PostgreSQL" sx={{ height: 22, fontSize: '0.7rem', bgcolor: 'success.lighter', color: 'success.dark', fontWeight: 600 }} />
            </Stack>
          )}
        </Stack>

        <Box sx={{ px: 2, borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={Math.min(tab, tabs.length - 1)} onChange={(_, v) => { setTab(v); setPage(0); }} variant="scrollable" scrollButtons="auto">
            {tabs.map((t, i) => (
              <Tab key={t.key} label={<TabLabelCount label={t.label} count={counts[t.key] || 0} active={tab === i} />} />
            ))}
          </Tabs>
        </Box>

        {error && <Alert severity="error" sx={{ m: 2 }} action={<Button color="inherit" size="small" onClick={load}>Retry</Button>}>{error}</Alert>}

        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}><CircularProgress /></Box>
        ) : paged.length === 0 ? (
          <EmptyState title="No team users found" caption="Try a different role or search term, or add a user." />
        ) : isMobile ? (
          <Stack spacing={1.25} sx={{ p: { xs: 1.5, sm: 2 } }}>
            {paged.map((row, i) => (
              <UserCard
                key={row.id}
                row={row}
                index={page * rpp + i + 1}
                onEdit={(r) => setDialog({ open: true, mode: 'edit', initial: r })}
                onDelete={(r) => setToDelete(r)}
              />
            ))}
          </Stack>
        ) : (
          <TableContainer>
            <Table sx={{ minWidth: 800 }}>
              <TableHead>
                <TableRow sx={{ '& th': { bgcolor: 'grey.50', fontWeight: 700, color: 'grey.700', textTransform: 'uppercase', fontSize: '0.72rem', letterSpacing: 0.4 } }}>
                  <TableCell sx={{ width: 64 }}>S.No</TableCell>
                  <TableCell>User</TableCell>
                  <TableCell>Email</TableCell>
                  <TableCell>Phone</TableCell>
                  <TableCell>Role</TableCell>
                  <TableCell align="right">Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {paged.map((row, i) => (
                  <TableRow key={row.id} hover>
                    <TableCell><Typography variant="body2" color="text.secondary">{page * rpp + i + 1}</Typography></TableCell>
                    <TableCell><UserIdentity name={row.name} email={row.email} role={row.role} /></TableCell>
                    <TableCell>
                      {row.email ? (
                        <Link href={`mailto:${row.email}`} underline="hover" color="text.primary" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.75, fontSize: '0.8125rem' }}>
                          <MailOutlineIcon sx={{ fontSize: 15, color: 'grey.400' }} />{row.email}
                        </Link>
                      ) : <Typography variant="body2" color="text.disabled">—</Typography>}
                    </TableCell>
                    <TableCell>
                      {row.phone ? (
                        <Link href={`tel:${row.phone}`} underline="hover" color="text.primary" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.75, fontSize: '0.8125rem' }}>
                          <PhoneOutlinedIcon sx={{ fontSize: 15, color: 'grey.400' }} />{row.phone}
                        </Link>
                      ) : <Typography variant="body2" color="text.disabled">—</Typography>}
                    </TableCell>
                    <TableCell><RoleCell role={row.role} /></TableCell>
                    <TableCell align="right">
                      <Tooltip title="Edit"><IconButton size="small" onClick={() => setDialog({ open: true, mode: 'edit', initial: row })}><EditOutlinedIcon fontSize="small" /></IconButton></Tooltip>
                      <Tooltip title="Delete"><IconButton size="small" color="error" onClick={() => setToDelete(row)}><DeleteOutlineIcon fontSize="small" /></IconButton></Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        )}
        <TablePagination
          component="div" count={filtered.length} page={page} onPageChange={(_, p) => setPage(p)}
          rowsPerPage={rpp} onRowsPerPageChange={(e) => { setRpp(+e.target.value); setPage(0); }} rowsPerPageOptions={[5, 10, 25]}
        />
      </Card>

      <UserFormDialog
        open={dialog.open}
        mode={dialog.mode}
        initial={dialog.initial}
        onClose={() => setDialog({ open: false, mode: 'add', initial: null })}
        onSaved={handleSaved}
      />

      <Dialog open={!!toDelete} onClose={deleting ? undefined : () => setToDelete(null)}>
        <DialogTitle>Delete user?</DialogTitle>
        <DialogContent>
          <DialogContentText>
            This will permanently remove <strong>{toDelete?.name}</strong> from the PostgreSQL database. This cannot be undone.
          </DialogContentText>
        </DialogContent>
        <DialogActions sx={{ px: 3, py: 2 }}>
          <Button onClick={() => setToDelete(null)} disabled={deleting}>Cancel</Button>
          <Button color="error" variant="contained" onClick={confirmDelete} disabled={deleting} startIcon={deleting ? <CircularProgress size={16} color="inherit" /> : null}>Delete</Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
