import {
    FormEvent,
    useCallback,
    useEffect,
    useMemo,
    useState,
} from 'react';
import { useLocale } from '../context/LocaleContext';
import api from '../services/api';
import AppCard from '../components/ui/Card';
import AppButton from '../components/ui/Button';
import AppTextField from '../components/ui/TextField';
import PhotoCameraRoundedIcon from '@mui/icons-material/PhotoCameraRounded';
import TypographyAnimated from '@/components/ui/TypographyAnimated';

import {
    Alert,
    Avatar,
    Box,
    Divider,
    Grid,
    IconButton,
    MenuItem,
    Stack,
    Typography,
} from '@mui/material';


const USER_ENDPOINT = import.meta.env.VITE_SETTINGS_USER_ENDPOINT ?? '/api/user';
const ACCOUNT_UPDATE_ENDPOINT = import.meta.env.VITE_ACCOUNT_UPDATE_ENDPOINT ?? '/api/accounts/update';

const STATE_OPTIONS = ['USA', 'Canada', 'Australia'] as const;

export type AccountsUser = {
    id: number;
    name: string;
    email: string;
    rol?: string | null;
    address1?: string | null;
    address2?: string | null;
    city?: string | null;
    state?: string | null;
    zip?: string | null;
    avatar_url?: string | null;
};

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;
}

function profileBadgeSrc(): string {
    const base = import.meta.env.VITE_APP_URL?.replace(/\/$/, '') ?? '';
    const path = '/assets/images/profile-app/01.png';
    return base ? `${base}${path}` : path;
}

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

    const [section, setSection] = useState<'profile' | 'delete'>('profile');
    const [user, setUser] = useState<AccountsUser | null>(null);
    const [loadError, setLoadError] = useState<string | null>(null);

    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [passwordConfirmation, setPasswordConfirmation] = useState('');
    const [rol, setRol] = useState('');
    const [address1, setAddress1] = useState('');
    const [address2, setAddress2] = useState('');
    const [city, setCity] = useState('');
    const [state, setState] = useState('');
    const [zip, setZip] = useState('');
    const [avatarFile, setAvatarFile] = useState<File | null>(null);
    const [previewUrl, setPreviewUrl] = useState<string | null>(null);

    const [saving, setSaving] = useState(false);
    const [deleting, setDeleting] = useState(false);
    const [success, setSuccess] = useState<string | null>(null);
    const [formError, setFormError] = useState<string | null>(null);
    const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>(
        {},
    );

    const fetchUser = useCallback(async () => {
        setLoadError(null);
        try {
            const { data } = await api.get<AccountsUser>(USER_ENDPOINT);
            setUser(data);
            setName(data.name ?? '');
            setEmail(data.email ?? '');
            setRol(data.rol ?? '');
            setAddress1(data.address1 ?? '');
            setAddress2(data.address2 ?? '');
            setCity(data.city ?? '');
            setState(data.state ?? '');
            setZip(data.zip ?? '');
        } catch {
            setUser(null);
            setLoadError(t('accounts', 'profile_load_error'));
        }
    }, [t]);

    useEffect(() => {
        void fetchUser();
    }, [fetchUser]);

    useEffect(() => {
        if (!avatarFile) {
            setPreviewUrl(null);
            return;
        }
        const url = URL.createObjectURL(avatarFile);
        setPreviewUrl(url);
        return () => URL.revokeObjectURL(url);
    }, [avatarFile]);

    const avatarSrc = useMemo(
        () =>
            previewUrl ??
            (user?.avatar_url ? storageUrl(user.avatar_url) : undefined),
        [previewUrl, user?.avatar_url],
    );

    const stateSelectOptions = useMemo(() => {
        const opts = new Set<string>(STATE_OPTIONS);
        if (state && !opts.has(state)) {
            return [state, ...STATE_OPTIONS];
        }
        return [...STATE_OPTIONS];
    }, [state]);

    async function onSubmit(e: FormEvent) {
        e.preventDefault();
        setFormError(null);
        setFieldErrors({});
        setSuccess(null);
        setSaving(true);
        try {
            const fd = new FormData();
            fd.append('name', name);
            fd.append('email', email);
            fd.append('rol', rol);
            fd.append('address1', address1);
            fd.append('address2', address2);
            fd.append('city', city);
            fd.append('state', state);
            fd.append('zip', zip);
            if (password) {
                fd.append('password', password);
                fd.append('password_confirmation', passwordConfirmation);
            }
            if (avatarFile) {
                fd.append('avatar', avatarFile);
            }

            const { data } = await api.post<{
                message?: string;
                user?: AccountsUser;
            }>(ACCOUNT_UPDATE_ENDPOINT, fd);

            if (data.user) {
                setUser(data.user);
            }
            setSuccess(
                data.message ??
                    t('accounts', 'profile_updated_success'),
            );
            setPassword('');
            setPasswordConfirmation('');
            setAvatarFile(null);
            void fetchUser();
        } 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 ?? {});
                setFormError(
                    payload.message ??
                        t('accounts', 'profile_save_error'),
                );
            } else {
                setFormError(t('accounts', 'profile_save_error'));
            }
        } finally {
            setSaving(false);
        }
    }

    if (loadError && !user) {
        return (
            <Box sx={{ py: 4, px: { xs: 2, sm: 3 } }}>
                <Alert severity="error">{loadError}</Alert>
            </Box>
        );
    }

    return (
        <div className="container-fluid">
            <div className=" col-lg-4 col-xxl-4">
                <AppCard>    
                <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"
                            id="Account-form"
                            onSubmit={onSubmit}
                            sx={{ mt: 2 }}
                        >
                            <Stack spacing={3} mt={3}>
                                <Box
                                    sx={{
                                        display: 'flex',
                                        flexDirection: { xs: 'column', lg: 'row' },
                                        gap: 3,
                                        alignItems: { lg: 'flex-start' },
                                    }}
                                >
                                    <Box sx={{ width: { xs: '100%', lg: '20%' } }}>
                                        <Stack
                                            direction="row"
                                            spacing={2}
                                            alignItems="center"
                                        >
                                            <Box sx={{ position: 'relative' }}>
                                                <Avatar
                                                    src={avatarSrc}
                                                    alt=""
                                                    sx={{
                                                        width: 88,
                                                        height: 88,
                                                        border: (theme) =>
                                                            `2px solid ${theme.palette.divider}`,
                                                    }}
                                                />
                                                <IconButton
                                                    component="label"
                                                    size="small"
                                                    color="primary"
                                                    aria-label="Cambiar imagen de perfil"
                                                    sx={{
                                                        position: 'absolute',
                                                        right: -6,
                                                        bottom: -6,
                                                        bgcolor: 'background.paper',
                                                        boxShadow: 2,
                                                        '&:hover': {
                                                            bgcolor:
                                                                'background.paper',
                                                        },
                                                    }}
                                                >
                                                    <input
                                                        type="file"
                                                        name="avatar"
                                                        accept="image/png,image/jpeg,image/jpg"
                                                        hidden
                                                        onChange={(ev) => {
                                                            const f =
                                                                ev.target.files?.[0] ??
                                                                null;
                                                            setAvatarFile(f);
                                                        }}
                                                    />
                                                    <PhotoCameraRoundedIcon fontSize="small" />
                                                </IconButton>
                                            </Box>
                                            <Box>
                                                <Typography
                                                    variant="h6"
                                                    fontWeight={600}
                                                    sx={{
                                                        display: 'flex',
                                                        alignItems: 'center',
                                                        gap: 1,
                                                    }}
                                                >
                                                    {name || user?.name}
                                                    <Box
                                                        component="img"
                                                        src={profileBadgeSrc()}
                                                        alt=""
                                                        sx={{
                                                            width: 20,
                                                            height: 20,
                                                        }}
                                                    />
                                                </Typography>
                                                <Typography
                                                    variant="body2"
                                                    color="text.secondary"
                                                >
                                                    {rol || user?.rol}
                                                </Typography>
                                            </Box>
                                        </Stack>
                                    </Box>

                                    <Box sx={{ width: { xs: '100%', lg: '80%' } }}>
                                        {success ? (
                                            <Alert
                                                severity="success"
                                                onClose={() => setSuccess(null)}
                                                sx={{ mb: 2 }}
                                            >
                                                {success}
                                            </Alert>
                                        ) : null}
                                        {formError ? (
                                            <Alert severity="error" sx={{ mb: 2 }}>
                                                {formError}
                                            </Alert>
                                        ) : null}

                                <Grid container spacing={2} padding={2} mt={3}>
                                    <Grid size={{ xs: 6 }} mb={3}>
                                        <AppTextField
                                            fullWidth
                                            id="name"
                                            name="name"
                                            placeholder={t('accounts', 'usuario')}
                                            label={t(
                                                'accounts',
                                                'nombre_de_usuario',
                                            )}
                                            value={name}
                                            onChange={(e) =>
                                                setName(e.target.value)
                                            }
                                            error={Boolean(fieldErrors.name)}
                                            helperText={
                                                fieldErrors.name?.join(' ')
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 6 }}>
                                        <AppTextField
                                            fullWidth
                                            type="email"
                                            id="email"
                                            name="email"
                                            placeholder={t('accounts', 'email')}
                                            label={t('accounts', 'email')}
                                            value={email}
                                            onChange={(e) =>
                                                setEmail(e.target.value)
                                            }
                                            error={Boolean(fieldErrors.email)}
                                            helperText={
                                                fieldErrors.email?.join(' ')
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12, md: 6 }} mb={3}>
                                        <AppTextField
                                            fullWidth
                                            type="password"
                                            id="password"
                                            name="password"
                                            label={t(
                                                'accounts',
                                                'contrasena',
                                            )}
                                            placeholder="*******"
                                            autoComplete="new-password"
                                            value={password}
                                            onChange={(e) =>
                                                setPassword(e.target.value)
                                            }
                                            error={Boolean(
                                                fieldErrors.password,
                                            )}
                                            helperText={fieldErrors.password?.join(
                                                ' ',
                                            )}
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12, md: 6 }}>
                                        <AppTextField
                                            fullWidth
                                            type="password"
                                            id="password_confirmation"
                                            name="password_confirmation"
                                            label={t(
                                                'accounts',
                                                'confirmar_contrasena',
                                            )}
                                            placeholder="*******"
                                            autoComplete="new-password"
                                            value={passwordConfirmation}
                                            onChange={(e) =>
                                                setPasswordConfirmation(
                                                    e.target.value,
                                                )
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12 }}>
                                        <AppTextField
                                            fullWidth
                                            id="rol"
                                            name="rol"
                                            label={t('accounts', 'rol')}
                                            value={rol}
                                            placeholder={t('accounts', 'rol')}
                                            onChange={(e) =>
                                                setRol(e.target.value)
                                            }
                                        />
                                    </Grid>
                                        </Grid>
                                    </Box>
                                </Box>

                                <Grid container spacing={2} padding={2}>
                                    <Grid size={{ xs: 12 }}>
                                        <Divider />
                                    </Grid>

                                    <Grid size={{ xs: 12 }} mb={3}>
                                        <Typography
                                            variant="subtitle1"
                                            fontWeight={600}
                                            color="text.primary"
                                        >
                                            {t(
                                                'accounts',
                                                'informacion_personal',
                                            )}
                                        </Typography>
                                    </Grid>

                                    <Grid size={{ xs: 12 }} mb={3}>
                                        <AppTextField
                                            fullWidth
                                            multiline
                                            minRows={3}
                                            id="address1"
                                            name="address1"
                                            label={t('accounts', 'direccion')}
                                            value={address1}
                                            placeholder={t('accounts', 'direccion_1')}
                                            onChange={(e) =>
                                                setAddress1(e.target.value)
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12 }} mb={3}>
                                        <AppTextField
                                            fullWidth
                                            multiline
                                            minRows={3}
                                            id="address2"
                                            name="address2"
                                            placeholder={t('accounts', 'direccion_2')}
                                            label={t(
                                                'accounts',
                                                'direccion_2',
                                            )}
                                            value={address2}
                                            onChange={(e) =>
                                                setAddress2(e.target.value)
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12, md: 6 }}>
                                        <AppTextField
                                            fullWidth
                                            id="city"
                                            name="city"
                                            placeholder={t('accounts', 'ciudad')}
                                            label={t('accounts', 'ciudad')}
                                            value={city}
                                            onChange={(e) =>
                                                setCity(e.target.value)
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12, md: 4 }}>
                                        <AppTextField
                                            fullWidth
                                            select
                                            id="state"
                                            name="state"
                                            placeholder={t('accounts', 'estado')}
                                            label={t('accounts', 'estado')}
                                            value={state}
                                            onChange={(e) =>
                                                setState(e.target.value)
                                            }
                                        >
                                            <MenuItem value="">
                                                <em>—</em>
                                            </MenuItem>
                                            {stateSelectOptions.map((opt) => (
                                                <MenuItem
                                                    key={opt}
                                                    value={opt}
                                                >
                                                    {opt}
                                                </MenuItem>
                                            ))}
                                        </AppTextField>
                                    </Grid>
                                    <Grid size={{ xs: 12, md: 2 }}>
                                        <AppTextField
                                            fullWidth
                                            id="zip"
                                            name="zip"
                                            placeholder={t('accounts', 'codigo_postal')}
                                            label={t(
                                                'accounts',
                                                'codigo_postal',
                                            )}
                                            value={zip}
                                            onChange={(e) =>
                                                setZip(e.target.value)
                                            }
                                        />
                                    </Grid>
                                    <Grid size={{ xs: 12 }} mt={3}>
                                        <Stack
                                            direction="row"
                                            justifyContent="flex-end"
                                        >
                                            <AppButton
                                                type="submit"
                                                disabled={saving}
                                            >
                                                {saving
                                                    ? t('accounts', 'saving')
                                                    : t(
                                                            'accounts',
                                                            'submit',
                                                        )}
                                            </AppButton>
                                        </Stack>
                                    </Grid>
                                </Grid>
                            </Stack>
                        </Box>
                </AppCard>
            </div>
              
        </div>
    );
}
