import ButtonJbs from '@/components/jbs/button';
import FormView from '@/components/jbs/form-view';
import InputJbs from '@/components/jbs/input';
import SelectJbs from '@/components/jbs/select';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { Add, Close } from '@mui/icons-material';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import axios from 'axios';
import { FormEventHandler, useEffect, useState } from 'react';
import InputError from '@/components/input-error';


const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Estimates',
        href: '/estimates',
    },
    {
        title: 'Create',
        href: '#',
    },
];
type EstimateForm = {
    customer_id: string;
    interior_designer_id: string;
    address: {
        customer_address_id: string,
        address_line_1: string;
        address_line_2?: string;
        city: string;
        state: string;
        postal_code: string;
        country: string;
    };
};

export default function Create(props) {
    const { data, setData, post, processing, errors, reset } = useForm<Required<EstimateForm>>({
        customer_id: '',
        interior_designer_id: '',
        address: {
            customer_address_id : "",
            address_line_1: "",
            address_line_2: "",
            city: "",
            state: "",
            postal_code: "",
            country: "India",
        },
    });

    const customers = props.customers ?? [];
    const interior_designers = props.interior_designers ?? [];

    const [addressArray, setAddressArray] = useState([]);

    const submit: FormEventHandler = (e)  => {
        e.preventDefault();
        post(route('estimates.store'), {
            onFinish: () => {},
        });
    };

    useEffect(() => {
        if (data.customer_id) {
            setAddressArray([]);
            reset('address');
            axios
                .post(route('customer_addresses.options'), { customer_id: data.customer_id })
                .then((response) => {
                    const { data: respData } = response;
                    if (respData.success) {
                        setAddressArray(respData.data);
                    }
                })
                .catch((error) => {
                    console.error('Failed to fetch addresses', error);
                });
        }
    }, [data.customer_id]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Create Estimate" />
            
            <FormView>
                <FormView.Title>
                    <Typography variant="h6" gutterBottom>
                        Create Estimate
                    </Typography>
                </FormView.Title>
                <FormView.Body>
                    <form onSubmit={submit}>
                        <Grid container spacing={2}>
                            <Grid size={12}>
                                <SelectJbs
                                    options={customers}
                                    label="Customer"
                                    value={data.customer_id}
                                    onChange={(e) => setData('customer_id', e.target.value)}
                                />
                                <InputError message={errors.customer_id} className="mt-2" />
                            </Grid>
                            <Grid size={12}>
                                <SelectJbs
                                    options={interior_designers}
                                    label="Interior Designer"
                                    value={data.interior_designer_id}
                                    onChange={(e) => setData('interior_designer_id', e.target.value)}
                                />
                            </Grid>
                            {data.customer_id != '' && (
                                <Grid size={12}>
                                    <SelectJbs
                                        create="true"
                                        options={addressArray}
                                        label="Address"
                                        value={data.address.customer_address_id}
                                        onChange={(e) => setData('address', {...data.address,customer_address_id : e.target.value})}
                                    />
                                    <InputError message={errors["address.customer_address_id"]} className="mt-2" />
                                </Grid>
                            )}
                            {data.address.customer_address_id == '0' && (
                                <Card variant="outlined" className="w-full">
                                    <CardContent>
                                        <Typography variant="h5" component="div">
                                            Create New Address
                                        </Typography>
                                        <Grid container spacing={2} style={{ marginTop: '20px' }}>
                                            <Grid size={12}>
                                                <InputJbs size="small" label="Address Line 1" onChange={(e) => setData('address', {...data.address,address_line_1 : e.target.value})} />
                                                <InputError message={errors["address.address_line_1"]} className="mt-2" />
                                            </Grid>
                                            <Grid size={12}>
                                                <InputJbs size="small" label="Address Line 2" onChange={(e) => setData('address', {...data.address,address_line_2 : e.target.value})} />
                                                <InputError message={errors["address.address_line_2"]} className="mt-2" />
                                            </Grid>
                                            <Grid size={4}>
                                                <InputJbs size="small" label="City" onChange={(e) => setData('address', {...data.address,city : e.target.value})} />
                                                <InputError message={errors["address.city"]} className="mt-2" />
                                            </Grid>
                                            <Grid size={4}>
                                                <InputJbs size="small" label="State" onChange={(e) => setData('address', {...data.address,state : e.target.value})} />
                                                <InputError message={errors["address.state"]} className="mt-2" />
                                            </Grid>
                                            <Grid size={4}>
                                                <InputJbs size="small" label="Postal code" onChange={(e) => setData('address', {...data.address,postal_code : e.target.value})} />
                                                <InputError message={errors["address.postal_code"]} className="mt-2" />
                                            </Grid>
                                            <Grid size={12}>
                                                <InputJbs size="small" value={data.address.country} disabled  label="Country" />
                                            </Grid>
                                        </Grid>
                                    </CardContent>
                                </Card>
                            )}
                            <Grid size={12}>
                                <ButtonJbs type="submit" startIcon={<Add />}>
                                    Create
                                </ButtonJbs>
                                <ButtonJbs style={{ marginLeft: '10px' }} color="error" href={route('estimates.index')} startIcon={<Close />}>
                                    Cancel
                                </ButtonJbs>
                            </Grid>
                        </Grid>
                    </form>
                </FormView.Body>
            </FormView>
        </AppLayout>
    );
}
