'use client';

import React, { useState } from 'react';
import { TextField, Button, Grid, Typography, Box, Card, CardMedia, CardActions, IconButton } from '@mui/material';
import { styled } from '@mui/material/styles';
import { toBase64 } from '@/helpers/toBase64';
import axios from 'axios';
import toast from 'react-hot-toast';
import PhotoCamera from '@mui/icons-material/PhotoCamera';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import { BASE_URI, BASE_URL } from '@/helpers/constants';
import myAxios from '@/helpers/myAxios';
import { useMyNavigation } from '@/hooks/useMyNavigation';

interface UserFormProps {
    apiUrl: string;
}

const Input = styled('input')({
    display: 'none',
});

const UserForm = () => {
    const { push } = useMyNavigation();
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [passportSeries, setPassportSeries] = useState('');
    const [pinfl, setPinfl] = useState('');
    const [passportFront, setPassportFront] = useState<File | null>(null);
    const [passportBack, setPassportBack] = useState<File | null>(null);
    const [passportFrontPreview, setPassportFrontPreview] = useState<string | null>(null);
    const [passportBackPreview, setPassportBackPreview] = useState<string | null>(null);
    const [errors, setErrors] = useState<Record<string, string>>({});

    const validateForm = () => {
        const newErrors: Record<string, string> = {};
        if (!firstName) newErrors.firstName = 'Ism majburiy!';
        if (!lastName) newErrors.lastName = 'Familiya majburiy!';
        if (!passportSeries) newErrors.passportSeries = 'Passport seriya raqami majburiy!';
        if (!pinfl) newErrors.pinfl = 'PINFL (JSHSHR) majburiy!';
        if (!passportFront) newErrors.passportFront = 'Passport oldi rasmi majburiy!';
        if (!passportBack) newErrors.passportBack = 'Passport orqa rasmi majburiy!';
        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handlePassportFrontChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0] || null;
        if (file) {
            setPassportFront(file);
            const reader = new FileReader();
            reader.onloadend = () => {
                setPassportFrontPreview(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    const handlePassportBackChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0] || null;
        if (file) {
            setPassportBack(file);
            const reader = new FileReader();
            reader.onloadend = () => {
                setPassportBackPreview(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    const clearPassportFront = () => {
        setPassportFront(null);
        setPassportFrontPreview(null);
    };

    const clearPassportBack = () => {
        setPassportBack(null);
        setPassportBackPreview(null);
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!validateForm()) return;

        try {
            const frontBase64 = passportFront ? await toBase64(passportFront) : '';
            const backBase64 = passportBack ? await toBase64(passportBack) : '';

            const payload = {
                fullName: firstName + ' ' + lastName,
                passportSeries,
                passportPin: pinfl,
                passportFrontImage: frontBase64,
                passportBackImage: backBase64,
            };

            const token = localStorage.getItem('token');
            const response = await axios.post(`${BASE_URI}/me/passports`, payload, {
                headers: {
                    Authorization: `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
            });
            toast.success("Ma'lumotlar muvaffaqiyatli yuborildi!");
            push('/profile/user-data');
        } catch (error) {
            console.error('API xatosi:', error);
            toast.error("Ma'lumotlar yuborishda xatolik yuz berdi!");
        }
    };

    return (
        <Box sx={{ width: '100%', padding: '20px' }}>
            <Typography variant='h5' align='center' gutterBottom>
                {"Foydalanuvchi ma'lumotlari"}
            </Typography>
            <form onSubmit={handleSubmit}>
                <Grid container spacing={2}>
                    <Grid item xs={12} sm={6}>
                        <TextField
                            label='Ism'
                            variant='outlined'
                            fullWidth
                            value={firstName}
                            onChange={e => setFirstName(e.target.value)}
                            required
                            error={!!errors.firstName}
                            helperText={errors.firstName}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                        <TextField
                            label='Familiya'
                            variant='outlined'
                            fullWidth
                            value={lastName}
                            onChange={e => setLastName(e.target.value)}
                            required
                            error={!!errors.lastName}
                            helperText={errors.lastName}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                        <TextField
                            label='Passport seriya raqami'
                            variant='outlined'
                            fullWidth
                            value={passportSeries}
                            onChange={e => setPassportSeries(e.target.value)}
                            required
                            error={!!errors.passportSeries}
                            helperText={errors.passportSeries}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                        <TextField
                            label='PINFL (JSHSHR)'
                            variant='outlined'
                            fullWidth
                            value={pinfl}
                            onChange={e => setPinfl(e.target.value)}
                            required
                            error={!!errors.pinfl}
                            helperText={errors.pinfl}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                        <Card>
                            <label htmlFor='passport-front-upload'>
                                <Input accept='image/*' id='passport-front-upload' type='file' onChange={handlePassportFrontChange} />
                                {passportFrontPreview ? (
                                    <CardMedia component='img' height='140' image={passportFrontPreview} alt='Passport front' />
                                ) : (
                                    <Button variant='outlined' component='span' fullWidth startIcon={<PhotoCamera />}>
                                        Passport oldi rasmi
                                    </Button>
                                )}
                            </label>
                            {passportFrontPreview && (
                                <CardActions>
                                    <IconButton onClick={clearPassportFront} aria-label='delete'>
                                        <DeleteIcon />
                                    </IconButton>
                                    <label htmlFor='passport-front-upload'>
                                        <IconButton component='span' aria-label='edit'>
                                            <EditIcon />
                                        </IconButton>
                                    </label>
                                </CardActions>
                            )}
                        </Card>
                        {errors.passportFront && (
                            <Typography variant='caption' color='error'>
                                {errors.passportFront}
                            </Typography>
                        )}
                    </Grid>
                    <Grid item xs={12} sm={6}>
                        <Card>
                            <label htmlFor='passport-back-upload'>
                                <Input accept='image/*' id='passport-back-upload' type='file' onChange={handlePassportBackChange} />
                                {passportBackPreview ? (
                                    <CardMedia component='img' height='140' image={passportBackPreview} alt='Passport back' />
                                ) : (
                                    <Button variant='outlined' component='span' fullWidth startIcon={<PhotoCamera />}>
                                        Passport orqa rasmi
                                    </Button>
                                )}
                            </label>
                            {passportBackPreview && (
                                <CardActions>
                                    <IconButton onClick={clearPassportBack} aria-label='delete'>
                                        <DeleteIcon />
                                    </IconButton>
                                    <label htmlFor='passport-back-upload'>
                                        <IconButton component='span' aria-label='edit'>
                                            <EditIcon />
                                        </IconButton>
                                    </label>
                                </CardActions>
                            )}
                        </Card>
                        {errors.passportBack && (
                            <Typography variant='caption' color='error'>
                                {errors.passportBack}
                            </Typography>
                        )}
                    </Grid>
                    <Grid item xs={12}>
                        <Button type='submit' variant='contained' color='primary' fullWidth>
                            Yuborish
                        </Button>
                    </Grid>
                </Grid>
            </form>
        </Box>
    );
};

export default UserForm;
