import { FormEvent, useCallback, useEffect, useState } from 'react';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import api from '../services/api';
import AppCard from '../components/ui/Card';
import AppButton from '../components/ui/Button';
import AppTextField from '../components/ui/TextField';
import TypographyAnimated from '@/components/ui/TypographyAnimated';
import { useLocale } from '@/context/LocaleContext';
import {
    Alert,
    Avatar,
    Box,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Grid,
    IconButton,
    Pagination,
    Paper,
    Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Tooltip,
    Typography,
} from '@mui/material';

type UserRow = {
    id: number;
    name: string;
    email: string;
    rol?: string | null;
    avatar_url?: string | null;
};

type PaginatorMeta = {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
};

const USERS_LIST_ENDPOINT =
    import.meta.env.VITE_USERS_LIST_ENDPOINT ?? '/api/accounts/users';
const ACCOUNT_REGISTER_ENDPOINT =
    import.meta.env.VITE_ACCOUNT_REGISTER_ENDPOINT ?? '/api/accounts/register';
const ACCOUNT_DELETE_ENDPOINT =
    import.meta.env.VITE_ACCOUNT_DELETE_ENDPOINT ?? '/api/accounts/users';

function storageUrl(path: string): string {
    const base = import.meta.env.VITE_APP_URL?.replace(/\/$/, '') ?? '';
    const p = path.startsWith('/') ? path : `/storage/${path}`;
    return base ? `${base}${p.startsWith('/') ? p : `/${p}`}` : p;
}

export default function Register() {
    const { t } = useLocale();

    const [nameFilter, setNameFilter] = useState('');
    const [emailFilter, setEmailFilter] = useState('');
    const [appliedName, setAppliedName] = useState('');
    const [appliedEmail, setAppliedEmail] = useState('');
    const [rows, setRows] = useState<UserRow[]>([]);
    const [meta, setMeta] = useState<PaginatorMeta | null>(null);
    const [page, setPage] = useState(1);
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [dialogOpen, setDialogOpen] = useState(false);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [rowToDelete, setRowToDelete] = useState<UserRow | null>(null);
    const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>(
        {},
    );

    const [formName, setFormName] = useState('');
    const [formEmail, setFormEmail] = useState('');
    const [formRol, setFormRol] = useState('');
    const [formPassword, setFormPassword] = useState('');
    const [formPasswordConfirmation, setFormPasswordConfirmation] =
        useState('');
    const [deleting, setDeleting] = useState(false);

    const fetchUsers = useCallback(
        async (p: number, name: string, email: string) => {
            setLoading(true);
            setError(null);
            try {
                const { data } = await api.get<{
                    data: UserRow[];
                    current_page: number;
                    last_page: number;
                    per_page: number;
                    total: number;
                }>(USERS_LIST_ENDPOINT, {
                    params: {
                        page: p,
                        name: name || undefined,
                        email: email || undefined,
                    },
                });
                setRows(Array.isArray(data.data) ? data.data : []);
                setMeta({
                    current_page: data.current_page ?? 1,
                    last_page: data.last_page ?? 1,
                    per_page: data.per_page ?? 10,
                    total: data.total ?? 0,
                });
            } catch {
                setRows([]);
                setMeta(null);
                setError('No se pudo cargar la lista de usuarios.');
            } finally {
                setLoading(false);
            }
        },
        [],
    );

    useEffect(() => {
        void fetchUsers(page, appliedName, appliedEmail);
    }, [page, appliedName, appliedEmail, fetchUsers]);

    const hasPages = meta != null && meta.last_page > 1;

    const headerCellSx = {
        fontSize: '0.78rem',
        fontWeight: 700,
        textTransform: 'uppercase' as const,
        letterSpacing: '0.08em',
        color: 'text.secondary',
        py: 1.6,
    };
    const bodyCellSx = {
        fontSize: '0.9rem',
        py: 1.5,
    };

    function resetCreateForm() {
        setFieldErrors({});
        setError(null);
        setFormName('');
        setFormEmail('');
        setFormRol('');
        setFormPassword('');
        setFormPasswordConfirmation('');
    }

    function openCreate() {
        resetCreateForm();
        setDialogOpen(true);
    }

    function closeDialog() {
        if (saving) return;
        setDialogOpen(false);
    }

    function openDeleteDialog(row: UserRow) {
        setRowToDelete(row);
        setDeleteDialogOpen(true);
    }

    function closeDeleteDialog() {
        if (deleting) return;
        setDeleteDialogOpen(false);
        setRowToDelete(null);
    }

    function onSearch(e: FormEvent) {
        e.preventDefault();
        setAppliedName(nameFilter.trim());
        setAppliedEmail(emailFilter.trim());
        setPage(1);
    }

    function onClear() {
        setNameFilter('');
        setEmailFilter('');
        setAppliedName('');
        setAppliedEmail('');
        setPage(1);
        setError(null);
        setSuccess(null);
    }

    async function onSubmitDialog(e: FormEvent) {
        e.preventDefault();
        setSaving(true);
        setFieldErrors({});
        setError(null);

        try {
            const { data } = await api.post<{ message?: string }>(
                ACCOUNT_REGISTER_ENDPOINT,
                {
                    name: formName.trim(),
                    email: formEmail.trim(),
                    rol: formRol.trim(),
                    password: formPassword,
                    password_confirmation: formPasswordConfirmation,
                },
            );

            setSuccess(data.message ?? 'Usuario creado exitosamente.');
            setDialogOpen(false);
            setPage(1);
            void fetchUsers(1, appliedName, appliedEmail);
        } catch (err: unknown) {
            if (
                err &&
                typeof err === 'object' &&
                'response' in err &&
                err.response &&
                typeof err.response === 'object' &&
                'status' in err.response &&
                err.response.status === 422 &&
                'data' in err.response
            ) {
                const payload = err.response.data as {
                    message?: string;
                    errors?: Record<string, string[]>;
                };
                setFieldErrors(payload.errors ?? {});
                setError(
                    payload.message ??
                        'No se pudo crear el usuario. Revisa los datos.',
                );
            } else {
                setError('No se pudo crear el usuario. Intente nuevamente.');
            }
        } finally {
            setSaving(false);
        }
    }

    async function onConfirmDelete() {
        if (!rowToDelete) return;

        setDeleting(true);
        setError(null);

        try {
            const { data } = await api.delete<{ message?: string }>(
                `${ACCOUNT_DELETE_ENDPOINT}/${rowToDelete.id}`,
            );
            setSuccess(data.message ?? 'Usuario eliminado exitosamente.');
            closeDeleteDialog();

            const targetPage =
                rows.length === 1 && page > 1 ? page - 1 : page;
            if (targetPage !== page) {
                setPage(targetPage);
            } else {
                void fetchUsers(page, appliedName, appliedEmail);
            }
        } catch (err: unknown) {
            if (
                err &&
                typeof err === 'object' &&
                'response' in err &&
                err.response &&
                typeof err.response === 'object' &&
                'data' in err.response
            ) {
                const payload = err.response.data as { message?: string };
                setError(
                    payload.message ??
                        'No se pudo eliminar el usuario. Intente nuevamente.',
                );
            } else {
                setError('No se pudo eliminar el usuario. Intente nuevamente.');
            }
        } finally {
            setDeleting(false);
        }
    }

    return (
        <div className="container-fluid">
            <AppCard>
                <Stack spacing={2.5}>
                    <TypographyAnimated
                        variant="subtitle2"
                        prefix={t('accounts', 'top_heading_prefix')}
                        rotatingWords={t('accounts', 'top_heading_rotating')
                            .split('|')
                            .map((s) => s.trim())
                            .filter(Boolean)}
                        sx={{
                            color: 'text.primary',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '0.18em',
                            fontSize: '1.3rem',
                        }}
                    />

                    <Box component="form" onSubmit={onSearch}>
                        <Grid container spacing={2} alignItems="flex-end" mt={1}>
                            <Grid size={{ xs: 12, md: 3 }}>
                                <AppTextField
                                    fullWidth
                                    label={t('accounts', 'nombre_de_usuario')}
                                    name="name"
                                    value={nameFilter}
                                    onChange={(e) => setNameFilter(e.target.value)}
                                    size="small"
                                />
                            </Grid>
                            <Grid size={{ xs: 12, md: 3 }}>
                                <AppTextField
                                    fullWidth
                                    label={t('accounts', 'email')}
                                    name="email"
                                    value={emailFilter}
                                    onChange={(e) => setEmailFilter(e.target.value)}
                                    size="small"
                                />
                            </Grid>
                            <Grid size={{ xs: 12, md: 4 }}>
                                <Stack direction="row" spacing={1.5}>
                                    <AppButton
                                        type="submit"
                                        variant="contained"
                                        disabled={loading}
                                    >
                                        {t('accounts', 'buscar')}
                                    </AppButton>
                                    <AppButton
                                        type="button"
                                        onClick={onClear}
                                        disabled={loading}
                                    >
                                        {t('accounts', 'limpiar')}
                                    </AppButton>
                                    <AppButton
                                        type="button"
                                        variant="contained"
                                        onClick={openCreate}
                                    >
                                        {t('accounts', 'crear')}
                                    </AppButton>
                                </Stack>
                            </Grid>
                        </Grid>
                    </Box>

                    {success ? (
                        <Alert severity="success" onClose={() => setSuccess(null)}>
                            {success}
                        </Alert>
                    ) : null}
                    {error ? (
                        <Alert severity="error" onClose={() => setError(null)}>
                            {error}
                        </Alert>
                    ) : null}

                    <TableContainer component={Paper} elevation={0} variant="outlined">
                        <Table size="medium">
                            <TableHead>
                                <TableRow sx={{ backgroundColor: 'action.hover' }}>
                                    <TableCell sx={headerCellSx}>ID</TableCell>
                                    <TableCell sx={headerCellSx}>Avatar</TableCell>
                                    <TableCell sx={headerCellSx}>
                                        {t('accounts', 'nombre_de_usuario')}
                                    </TableCell>
                                    <TableCell sx={headerCellSx}>
                                        {t('accounts', 'email')}
                                    </TableCell>
                                    <TableCell sx={headerCellSx}>
                                        {t('accounts', 'rol')}
                                    </TableCell>
                                    <TableCell sx={headerCellSx} align="right">
                                        {t('accounts', 'acciones')}
                                    </TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {loading && rows.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                                            {t('accounts', 'cargando')}
                                        </TableCell>
                                    </TableRow>
                                ) : rows.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                                            <Typography color="text.secondary">
                                                {t('accounts', 'no_data_to_show')}
                                            </Typography>
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    rows.map((row) => (
                                        <TableRow key={row.id} hover>
                                            <TableCell sx={bodyCellSx}>{row.id}</TableCell>
                                            <TableCell sx={bodyCellSx}>
                                                <Avatar
                                                    src={
                                                        row.avatar_url
                                                            ? storageUrl(row.avatar_url)
                                                            : undefined
                                                    }
                                                    alt={row.name}
                                                    sx={{ width: 34, height: 34 }}
                                                />
                                            </TableCell>
                                            <TableCell sx={bodyCellSx}>{row.name}</TableCell>
                                            <TableCell sx={bodyCellSx}>{row.email}</TableCell>
                                            <TableCell sx={bodyCellSx}>
                                                {row.rol || '—'}
                                            </TableCell>
                                            <TableCell sx={bodyCellSx} align="right">
                                                <Tooltip
                                                    title={t('accounts', 'eliminar_usuario')}
                                                >
                                                    <IconButton
                                                        size="small"
                                                        color="error"
                                                        onClick={() =>
                                                            openDeleteDialog(
                                                                row,
                                                            )
                                                        }
                                                    >
                                                        <DeleteOutlineIcon fontSize="small" />
                                                    </IconButton>
                                                </Tooltip>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>

                    {hasPages && meta ? (
                        <Box
                            sx={{
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                                gap: 1.5,
                                flexWrap: 'wrap',
                                px: { xs: 0.5, sm: 1 },
                            }}
                        >
                            <Typography variant="body2" color="text.secondary">
                                {t('accounts', 'pagina')} {meta.current_page}{' '}
                                {t('accounts', 'de')} {meta.last_page} ({meta.total}{' '}
                                {t('accounts', 'registros')})
                            </Typography>
                            <Pagination
                                color="primary"
                                shape="rounded"
                                size="small"
                                siblingCount={0}
                                boundaryCount={1}
                                page={meta.current_page}
                                count={meta.last_page}
                                onChange={(_, value) => setPage(value)}
                                disabled={loading}
                            />
                        </Box>
                    ) : null}
                </Stack>
            </AppCard>

            <Dialog open={dialogOpen} onClose={closeDialog} fullWidth maxWidth="sm">
                <Box component="form" onSubmit={onSubmitDialog} autoComplete="off">
                    <DialogTitle>{t('accounts', 'nuevo_usuario')}</DialogTitle>
                    <DialogContent dividers>
                        <Grid container spacing={2} padding={2}>
                            <Grid size={{ xs: 12 }} mb={2}>
                                <AppTextField
                                    required
                                    fullWidth
                                    name="create_name"
                                    label={t('accounts', 'nombre_de_usuario')}
                                    value={formName}
                                    onChange={(e) => setFormName(e.target.value)}
                                    error={Boolean(fieldErrors.name)}
                                    helperText={fieldErrors.name?.join(' ')}
                                    autoComplete="off"
                                    size="small"
                                />
                            </Grid>
                            <Grid size={{ xs: 12 }} mb={2}>
                                <AppTextField
                                    required
                                    fullWidth
                                    type="email"
                                    name="create_email"
                                    label={t('accounts', 'email')}
                                    value={formEmail}
                                    onChange={(e) => setFormEmail(e.target.value)}
                                    error={Boolean(fieldErrors.email)}
                                    helperText={fieldErrors.email?.join(' ')}
                                    autoComplete="off"
                                    size="small"
                                />
                            </Grid>
                            <Grid size={{ xs: 12 }} mb={2}>
                                <AppTextField
                                    fullWidth
                                    name="create_role"
                                    label={t('accounts', 'rol')}
                                    value={formRol}
                                    onChange={(e) => setFormRol(e.target.value)}
                                    error={Boolean(fieldErrors.rol)}
                                    helperText={fieldErrors.rol?.join(' ')}
                                    autoComplete="off"
                                    size="small"
                                />
                            </Grid>
                            <Grid size={{ xs: 12, md: 6 }} mb={2}>
                                <AppTextField
                                    required
                                    fullWidth
                                    type="password"
                                    name="create_password"
                                    label={t('accounts', 'contrasena')}
                                    value={formPassword}
                                    onChange={(e) => setFormPassword(e.target.value)}
                                    error={Boolean(fieldErrors.password)}
                                    helperText={fieldErrors.password?.join(' ')}
                                    autoComplete="new-password"
                                    size="small"
                                />
                            </Grid>
                            <Grid size={{ xs: 12, md: 6 }} mb={2}>
                                <AppTextField
                                    required
                                    fullWidth
                                    type="password"
                                    name="create_password_confirmation"
                                    label={t('accounts', 'confirmar_contrasena')}
                                    value={formPasswordConfirmation}
                                    onChange={(e) =>
                                        setFormPasswordConfirmation(e.target.value)
                                    }
                                    error={Boolean(fieldErrors.password_confirmation)}
                                    helperText={fieldErrors.password_confirmation?.join(' ')}
                                    autoComplete="new-password"
                                    size="small"
                                />
                            </Grid>
                        </Grid>
                    </DialogContent>
                    <DialogActions>
                        <AppButton
                            type="button"
                            variant="outlined"
                            onClick={closeDialog}
                            disabled={saving}
                        >
                            {t('accounts', 'cancelar')}
                        </AppButton>
                        <AppButton type="submit" variant="contained" disabled={saving}>
                            {saving ? t('accounts', 'saving') : t('accounts', 'guardar')}
                        </AppButton>
                    </DialogActions>
                </Box>
            </Dialog>

            <Dialog
                open={deleteDialogOpen}
                onClose={closeDeleteDialog}
                fullWidth
                maxWidth="xs"
            >
                <DialogTitle>{t('accounts', 'eliminar_usuario')}</DialogTitle>
                <DialogContent dividers>
                    <Typography>
                        {t('accounts', 'eliminar_usuario_confirm_titulo')}
                    </Typography>
                    <Typography color="text.secondary" sx={{ mt: 1 }}>
                        {rowToDelete?.name} ({rowToDelete?.email})
                    </Typography>
                    <Typography color="text.secondary" sx={{ mt: 1 }}>
                        {t('accounts', 'eliminar_usuario_confirm_texto')}
                    </Typography>
                </DialogContent>
                <DialogActions>
                    <AppButton
                        type="button"
                        variant="outlined"
                        onClick={closeDeleteDialog}
                        disabled={deleting}
                    >
                        {t('accounts', 'cancelar')}
                    </AppButton>
                    <AppButton
                        type="button"
                        color="error"
                        variant="contained"
                        onClick={onConfirmDelete}
                        disabled={deleting}
                    >
                        {deleting
                            ? t('accounts', 'eliminando_usuario')
                            : t('accounts', 'eliminar')}
                    </AppButton>
                </DialogActions>
            </Dialog>
        </div>
    );
}
