import React from 'react';
import AdminLayout from '../../../Layouts/AdminLayout';
import { Head, useForm, Link, router } from '@inertiajs/react';
import { Autocomplete, Box, Button, Grid, TextField, MenuItem, Typography, Dialog, DialogTitle, DialogContent, DialogActions, IconButton } from '@mui/material';
import { Save, ArrowBack, Add } from '@mui/icons-material';
import FormLayout from '../../../Components/FormLayout';

import route from '../../../utils/route';
export default function ClientForm({ client, countries, countryCurrencies, walletCurrencies }) {
    const isEdit = !!client;
    const [countryMapOpen, setCountryMapOpen] = React.useState(false);
    const { data, setData, post, put, processing, errors } = useForm({
        client_name: client?.client_name || '',
        website_address: client?.website_address || '',
        email_address: client?.email_address || '',
        country: client?.country || '',
        contact_person: client?.contact_person || '',
        contact_number: client?.contact_number || '',
        password: '',
        country_currency: client?.country_currency || '',
        wallet_currency_id: client?.wallet_currency_id || '',
        status: client?.status || 'active',
    });

    const countryMapForm = useForm({
        country_name: '',
        country_code: '',
        currency_code: '',
    });

    const selectedCountry = React.useMemo(
        () => (countries || []).find((country) => country.country_name === data.country) || null,
        [countries, data.country]
    );

    const selectedWalletCurrency = React.useMemo(
        () => (walletCurrencies || []).find((currency) => String(currency.id) === String(data.wallet_currency_id)) || null,
        [walletCurrencies, data.wallet_currency_id]
    );

    const selectedCountryCurrency = React.useMemo(
        () => (countryCurrencies || []).find((currency) => currency.currency_code === data.country_currency) || null,
        [countryCurrencies, data.country_currency]
    );

    const hasCountryCurrencyMapping = Boolean(
        selectedCountry?.currency_code &&
        (countryCurrencies || []).some((currency) => currency.currency_code === selectedCountry.currency_code)
    );

    const mappedCountryCurrency = React.useMemo(
        () => hasCountryCurrencyMapping
            ? (countryCurrencies || []).find((currency) => currency.currency_code === selectedCountry?.currency_code) || null
            : null,
        [hasCountryCurrencyMapping, countryCurrencies, selectedCountry]
    );

    React.useEffect(() => {
        if (!mappedCountryCurrency) {
            return;
        }

        if (data.country_currency !== mappedCountryCurrency.currency_code) {
            setData('country_currency', mappedCountryCurrency.currency_code);
        }
    }, [mappedCountryCurrency, data.country_currency, setData]);

    const handleCountryChange = (_, selected) => {
        const countryName = selected?.country_name || '';
        setData('country', countryName);

        if (!selected?.currency_code) {
            return;
        }

        const mappedCountryCurrency = (countryCurrencies || []).find(
            (currency) => currency.currency_code === selected.currency_code
        );

        if (!mappedCountryCurrency) {
            return;
        }

        setData('country_currency', mappedCountryCurrency.currency_code);

        const mappedWalletCurrency = (walletCurrencies || []).find(
            (currency) => currency.currency_code === selected.currency_code
        );

        if (mappedWalletCurrency) {
            setData('wallet_currency_id', mappedWalletCurrency.id);
        }
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        isEdit ? put(route('admin.clients.update', client.id)) : post(route('admin.clients.store'));
    };

    const handleCountryMapSubmit = (e) => {
        e.preventDefault();

        countryMapForm
            .transform((formData) => ({
                ...formData,
                country_code: (formData.country_code || '').toUpperCase(),
                currency_code: (formData.currency_code || '').toUpperCase(),
            }))
            .post(route('admin.countries.map.store'), {
                preserveScroll: true,
                preserveState: true,
                errorBag: 'countryMap',
                onSuccess: () => {
                    setCountryMapOpen(false);
                    countryMapForm.reset();
                    countryMapForm.clearErrors();
                    router.reload({ only: ['countries'] });
                },
            });
    };

    const tips = [
        { label: 'Client Name', text: 'Company or organization name of the client.' },
        { label: 'Email & Password', text: 'Used by the client to log in to their portal.' },
        { label: 'Country', text: 'Select from countries mapped to active currencies.' },
        { label: 'Add/Map Country', text: 'Use Add/Map Country when a required country is not available.' },
        { label: 'Country Currency', text: 'Selected from the currencies table.' },
        { label: 'Wallet Currency', text: 'Selected only from currencies that are defined in active subscriptions.' },
    ];

    return (
        <AdminLayout title={isEdit ? 'Edit Client' : 'Add Client'}>
            <Head title={isEdit ? 'Edit Client' : 'Add Client'} />
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
                <Button component={Link} href={route('admin.clients.index')} startIcon={<ArrowBack />} variant="outlined" size="small">Back</Button>
                <Typography variant="h5">{isEdit ? 'Edit Client' : 'Add Client'}</Typography>
            </Box>
            <FormLayout tips={tips}>
                <form onSubmit={handleSubmit}>
                    <Grid container spacing={3}>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth label="Client Name" value={data.client_name} onChange={(e) => setData('client_name', e.target.value)} error={!!errors.client_name} helperText={errors.client_name} />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth label="Website Address" value={data.website_address} onChange={(e) => setData('website_address', e.target.value)} error={!!errors.website_address} helperText={errors.website_address} />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth label="Email Address" type="email" value={data.email_address} onChange={(e) => setData('email_address', e.target.value)} error={!!errors.email_address} helperText={errors.email_address} />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                <Autocomplete
                                    sx={{ flex: 1 }}
                                    options={countries || []}
                                    value={selectedCountry}
                                    onChange={handleCountryChange}
                                    getOptionLabel={(option) => option.country_name}
                                    isOptionEqualToValue={(option, value) => option.country_code === value.country_code}
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            fullWidth
                                            label="Country"
                                            error={!!errors.country}
                                            helperText={errors.country}
                                        />
                                    )}
                                />
                                <IconButton
                                    size="small"
                                    title="Add/Map Country"
                                    onClick={() => setCountryMapOpen(true)}
                                    sx={{
                                        mt: errors.country ? -2.75 : 0,
                                        color: 'success.main',
                                        border: '1px solid',
                                        borderColor: 'divider',
                                        borderRadius: 1,
                                    }}
                                >
                                    <Add fontSize="small" />
                                </IconButton>
                            </Box>
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth label="Contact Person" value={data.contact_person} onChange={(e) => setData('contact_person', e.target.value)} error={!!errors.contact_person} helperText={errors.contact_person} />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth label="Contact Number" value={data.contact_number} onChange={(e) => setData('contact_number', e.target.value)} error={!!errors.contact_number} helperText={errors.contact_number} />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth label={isEdit ? 'New Password (leave blank to keep)' : 'Password'} type="password" value={data.password} onChange={(e) => setData('password', e.target.value)} error={!!errors.password} helperText={errors.password} required={!isEdit} />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <Autocomplete
                                options={countryCurrencies || []}
                                value={selectedCountryCurrency}
                                onChange={(_, newValue) => setData('country_currency', newValue?.currency_code || '')}
                                disabled={!!mappedCountryCurrency}
                                getOptionLabel={(option) => `${option.currency_name} (${option.currency_code})`}
                                isOptionEqualToValue={(option, value) => option.id === value.id}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        fullWidth
                                        label="Country Currency"
                                        error={!!errors.country_currency}
                                        helperText={errors.country_currency || (mappedCountryCurrency ? `Auto-mapped from country: ${mappedCountryCurrency.currency_code}` : '')}
                                    />
                                )}
                            />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <Autocomplete
                                options={walletCurrencies || []}
                                value={selectedWalletCurrency}
                                onChange={(_, newValue) => setData('wallet_currency_id', newValue?.id || '')}
                                getOptionLabel={(option) => `${option.currency_name} (${option.currency_code})`}
                                isOptionEqualToValue={(option, value) => option.id === value.id}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        fullWidth
                                        label="Wallet Currency"
                                        error={!!errors.wallet_currency_id}
                                        helperText={errors.wallet_currency_id}
                                    />
                                )}
                            />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 6 }}>
                            <TextField fullWidth select label="Status" value={data.status} onChange={(e) => setData('status', e.target.value)}>
                                <MenuItem value="active">Active</MenuItem>
                                <MenuItem value="inactive">Inactive</MenuItem>
                            </TextField>
                        </Grid>
                        <Grid size={12}>
                            <Button type="submit" variant="contained" startIcon={<Save />} disabled={processing} size="large">
                                {isEdit ? 'Update' : 'Create'} Client
                            </Button>
                        </Grid>
                    </Grid>
                </form>
            </FormLayout>

            <Dialog open={countryMapOpen} onClose={() => { setCountryMapOpen(false); countryMapForm.clearErrors(); }} fullWidth maxWidth="sm">
                <form onSubmit={handleCountryMapSubmit}>
                    <DialogTitle>Add/Map Country</DialogTitle>
                    <DialogContent sx={{ pt: 1 }}>
                        <Grid container spacing={2} sx={{ mt: 0.5 }}>
                            <Grid size={{ xs: 12, sm: 6 }}>
                                <TextField
                                    fullWidth
                                    label="Country Name"
                                    value={countryMapForm.data.country_name}
                                    onChange={(e) => countryMapForm.setData('country_name', e.target.value)}
                                    error={!!countryMapForm.errors.country_name}
                                    helperText={countryMapForm.errors.country_name}
                                />
                            </Grid>
                            <Grid size={{ xs: 12, sm: 6 }}>
                                <TextField
                                    fullWidth
                                    label="Country Code (ISO 2)"
                                    value={countryMapForm.data.country_code}
                                    onChange={(e) => countryMapForm.setData('country_code', e.target.value)}
                                    error={!!countryMapForm.errors.country_code}
                                    helperText={countryMapForm.errors.country_code}
                                    inputProps={{ maxLength: 2 }}
                                />
                            </Grid>
                            <Grid size={12}>
                                <Autocomplete
                                    options={countryCurrencies || []}
                                    value={(countryCurrencies || []).find((currency) => currency.currency_code === countryMapForm.data.currency_code) || null}
                                    onChange={(_, newValue) => countryMapForm.setData('currency_code', newValue?.currency_code || '')}
                                    getOptionLabel={(option) => `${option.currency_name} (${option.currency_code})`}
                                    isOptionEqualToValue={(option, value) => option.id === value.id}
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            fullWidth
                                            label="Currency"
                                            error={!!countryMapForm.errors.currency_code}
                                            helperText={countryMapForm.errors.currency_code}
                                        />
                                    )}
                                />
                            </Grid>
                        </Grid>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => { setCountryMapOpen(false); countryMapForm.clearErrors(); }}>Cancel</Button>
                        <Button type="submit" variant="contained" disabled={countryMapForm.processing}>Save Mapping</Button>
                    </DialogActions>
                </form>
            </Dialog>
        </AdminLayout>
    );
}
