import ButtonJbs from '@/components/jbs/button';
import InputJbs from '@/components/jbs/input';
import SelectJbs from '@/components/jbs/select';
import { CurrencyRupee } from '@mui/icons-material';
import { Box, FormControl, Grid, InputAdornment, MenuItem, Select } from '@mui/material';
import { useEffect, useState } from 'react';

const unitTypes = ['RFT', 'SQFT', 'PCS', 'KG'];
const dimensionUnits = ['in', 'ft', 'cm', 'mm', 'm'];

function convertToFeet(value, unit) {
    switch (unit) {
        case 'in':
            return value / 12;
        case 'cm':
            return value / 30.48;
        case 'mm':
            return value / 304.8;
        case 'm':
            return value * 3.281;
        default:
            return value;
    }
}

function calculateQuantity(unitType, length, width, height, qty) {
    switch (unitType) {
        case 'RFT':
            return length * qty;
        case 'SQFT':
            return length * width * qty;
        case 'PCS':
            return qty;
        case 'KG':
            return qty;
        default:
            return qty;
    }
}

function isDimensionUsed(unitType, dim) {
    const map = {
        RFT: ['length'],
        SQFT: ['length', 'width'],
    };
    return map[unitType]?.includes(dim);
}

export default function AddItemForm({ item, onlyDisplay, onItemAdd, onItemDelete, ...props }) {
    const [form, setForm] = useState({
        item_name: '',
        description: '',
        unit_type: 'SQFT',
        length_value: '',
        length_unit: 'ft',
        width_value: '',
        width_unit: 'ft',
        height_value: '',
        height_unit: 'ft',
        quantity: 1,
        unit_price: 0,
        total: 0,
    });

    const [errors, setErrors] = useState({});
    const [calculated, setCalculated] = useState({
        calculated_qty: 0,
        total_price: 0,
        final_amount: 0,
    });

    const [canEdit, setCanEdit] = useState(true);

    const handleChange = (field) => (e) => {
        setForm({ ...form, [field]: e.target.value });
        if (errors[field]) setErrors({ ...errors, [field]: '' });
    };

    const validateForm = () => {
        let newErrors = {};

        if (!form.item_name.trim()) newErrors.item_name = 'Item name is required';
        if (!form.unit_type) newErrors.unit_type = 'Unit type is required';

        if (isDimensionUsed(form.unit_type, 'length') && !form.length_value) {
            newErrors.length_value = 'Length is required';
        }
        if (isDimensionUsed(form.unit_type, 'width') && !form.width_value) {
            newErrors.width_value = 'Width is required';
        }

        if (!form.quantity || parseFloat(form.quantity) <= 0) {
            newErrors.quantity = 'Quantity must be greater than 0';
        }
        if (form.unit_price === '' || parseFloat(form.unit_price) < 0) {
            newErrors.unit_price = 'Unit price must be 0 or more';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleAddItem = () => {
        if (validateForm()) {
            const updatedForm = {
                ...form,
                total: calculated.final_amount,
            };
            onItemAdd(updatedForm);
        }
    };

    useEffect(() => {
        const length = convertToFeet(parseFloat(form.length_value || 0), form.length_unit);
        const width = convertToFeet(parseFloat(form.width_value || 0), form.width_unit);
        const height = convertToFeet(parseFloat(form.height_value || 0), form.height_unit);
        const qty = parseFloat(form.quantity || 1);
        const unit_price = parseFloat(form.unit_price || 0);

        const calculated_qty = calculateQuantity(form.unit_type, length, width, height, qty);
        const total_price = calculated_qty * unit_price;

        setCalculated({
            calculated_qty,
            total_price,
            final_amount: total_price,
        });
    }, [form]);

    useEffect(() => {
        if (item) {
            setForm(item);
            setCanEdit(false);
        }
    }, [item]);

    const shouldShow = (dim) => isDimensionUsed(form.unit_type, dim);

    return (
        <Box p={2} style={{ borderRadius: '10px 10px 10px 10px', borderRight: '4px solid red',borderLeft: '4px solid red' }}>
            <Grid container spacing={2}>
                <Grid size={{ xs: 12, sm: 12, md: 12, xl: 11 }}>
                    <Grid container spacing={2} style={{ marginBottom: '20px' }}>
                        <Grid size={{ xs: 12, sm: 12, md: 4, xl: 4 }}>
                            <InputJbs
                                disabled={!canEdit}
                                size="small"
                                fullWidth
                                label="Item Name"
                                value={form.item_name}
                                onChange={handleChange('item_name')}
                                error={!!errors.item_name}
                                helperText={errors.item_name}
                            />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 12, md: 2, xl: 2 }}>
                            <FormControl fullWidth>
                                <SelectJbs
                                    disabled={!canEdit}
                                    size="small"
                                    options={unitTypes.map((unit) => ({ value: unit, label: unit }))}
                                    label="Unit"
                                    clearable
                                    value={form.unit_type}
                                    onChange={handleChange('unit_type')}
                                    error={!!errors.unit_type}
                                    helperText={errors.unit_type}
                                />
                            </FormControl>
                        </Grid>
                        {'length width height'.split(' ').map((dim) => (
                            <Grid key={dim} size={{ xs: 12, sm: 12, md: 2, xl: 2 }}>
                                <InputJbs
                                    size="small"
                                    fullWidth
                                    label={dim.charAt(0).toUpperCase() + dim.slice(1)}
                                    value={form[`${dim}_value`]}
                                    onChange={handleChange(`${dim}_value`)}
                                    disabled={!shouldShow(dim) || !canEdit}
                                    error={!!errors[`${dim}_value`]}
                                    helperText={errors[`${dim}_value`]}
                                    InputProps={{
                                        endAdornment: (
                                            <FormControl variant="standard" sx={{ minWidth: 60 }}>
                                                <Select
                                                    value={form[`${dim}_unit`]}
                                                    onChange={handleChange(`${dim}_unit`)}
                                                    disabled={!shouldShow(dim) || !canEdit}
                                                >
                                                    {dimensionUnits.map((u) => (
                                                        <MenuItem key={u} value={u}>
                                                            {u}
                                                        </MenuItem>
                                                    ))}
                                                </Select>
                                            </FormControl>
                                        ),
                                    }}
                                />
                            </Grid>
                        ))}
                    </Grid>
                    <Grid container spacing={2}>
                        <Grid size={{ xs: 12, sm: 12, md: 4, xl: 4 }}>
                            <InputJbs
                                disabled={!canEdit}
                                multiline
                                rows={3}
                                size="small"
                                fullWidth
                                label="Description"
                                value={form.description}
                                onChange={handleChange('description')}
                            />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 12, md: 2, xl: 2 }}>
                            <InputJbs
                                disabled={!canEdit}
                                size="small"
                                fullWidth
                                label="Quantity"
                                value={form.quantity}
                                onChange={handleChange('quantity')}
                                error={!!errors.quantity}
                                helperText={errors.quantity}
                            />
                        </Grid>
                        <Grid size={{ xs: 12, sm: 12, md: 2, xl: 2 }}>
                            <InputJbs
                                disabled={!canEdit}
                                size="small"
                                fullWidth
                                label="Unit Price"
                                value={form.unit_price}
                                onChange={handleChange('unit_price')}
                                error={!!errors.unit_price}
                                helperText={errors.unit_price}
                                InputProps={{
                                    startAdornment: (
                                        <InputAdornment position="start">
                                            <CurrencyRupee fontSize="small" />
                                        </InputAdornment>
                                    ),
                                }}
                            />
                        </Grid>
                    </Grid>
                </Grid>
                <Grid size={{ xs: 12, sm: 12, md: 12, xl: 1 }}>₹{calculated.final_amount.toFixed(2)}</Grid>
            </Grid>
            <Grid container spacing={2} class="mt-2">
                {canEdit ? (
                    <>
                        <ButtonJbs size="small" variant="outlined" onClick={handleAddItem}>
                            {form.id ? 'Update' : 'Save'}
                        </ButtonJbs>
                    </>
                ) : (
                    <>
                        <ButtonJbs size="small" variant="outlined" onClick={() => setCanEdit(true)}>
                            Edit
                        </ButtonJbs>
                        <ButtonJbs color="error" size="small" variant="outlined" onClick={() => onItemDelete(form.id)} style={{ marginLeft: '10px' }}>
                            Delete
                        </ButtonJbs>
                    </>
                )}
            </Grid>
        </Box>
    );
}
