import { DeleteIcon, EditIcon } from '@bigcommerce/big-design-icons';
import { Box, Button, Form, FormGroup, Modal, MultiSelect, Panel, Select, Table } from '@bigcommerce/big-design';
import { type FormEvent, useEffect, useState } from 'react';
import { useAssemblies, useHoseParts } from '../../../lib/hooks';

const Index = () => {
    const [isOpen, setIsOpen] = useState(false);
    const [isEditOpen, setIsEditOpen] = useState(false);
    const [editingAssemblyId, setEditingAssemblyId] = useState<string | number | null>(null);

    const [standard, setStandard] = useState('');
    const [gas, setGas] = useState('');
    const [hoseType, setHoseType] = useState<string[]>([]);
    const [swivel, setSwivel] = useState<string[]>([]);
    const [inlet, setInlet] = useState<string[]>([]);
    const [outlet, setOutlet] = useState<string[]>([]);
    const [length, setLength] = useState<string[]>([]);

    const [assemblies, setAssemblies] = useState<any[]>([]);
    const { assemblyList } = useAssemblies();

    useEffect(() => {
        if (assemblyList) setAssemblies(assemblyList);
    }, [assemblyList]);

    const resetAssemblyForm = () => {
        setStandard('');
        setGas('');
        setHoseType([]);
        setSwivel([]);
        setInlet([]);
        setOutlet([]);
        setLength([]);
    };

    const handleAddAssemblyOpen = () => {
        resetAssemblyForm();
        setIsOpen(true);
    };
  
    const handleGasChange = (val: string) => setGas(val);
    const handleStandardChange = (val: string) => setStandard(val);
    const handleHoseTypeChange = (val: string[]) => setHoseType(val);
    const handleSwivelChange = (val: string[]) => setSwivel(val);
    const handleInletChange = (val: string[]) => setInlet(val);
    const handleOutletChange = (val: string[]) => setOutlet(val);
    const handleLengthChange = (val: string[]) => setLength(val);

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();
        try {
            const data = {
                standard,
                gas,
                hoseType,
                swivel,
                inlet,
                outlet,
                length,
                "action" : "create"
            };
            await fetch('/api/hose/assembly', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            }).then((response) => {
                response.json().then((data) => {
                    setAssemblies(data.assemblies);
                    setIsOpen(false);
                });
            });
        } catch (error) {
            console.error('Error submitting form:', error);
        }
    };

    const handleEditSubmit = async (e: FormEvent) => {
        e.preventDefault();
        try {
            if (!editingAssemblyId) return;

            const data = {
                id: editingAssemblyId,
                hoseType,
                swivel,
                inlet,
                outlet,
                length,
                action: 'update',
            };

            await fetch('/api/hose/assembly', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            }).then((response) => {
                response.json().then((data) => {
                    setAssemblies(data.assemblies);
                    setIsEditOpen(false);
                    setEditingAssemblyId(null);
                });
            });
        } catch (error) {
            console.error('Error submitting edit form:', error);
        }
    };

    const handleAssemblyDelete = async (id: string| number) => {
        try {
            const deleteData = {
                id: id,
                action: "delete"
            }

            await fetch(`/api/hose/assembly`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(deleteData),
            }).then((response) => {
                response.json().then((data) => {
                    setAssemblies(data.assemblies);
                }); 
            });
        } catch (error) {
            console.error('Error deleting item:', error);
        }
    };

    const handleAssemblyEdit = async (id: string | number) => {
        try {
            const details = await fetch('/api/hose/assembly', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ action: 'details', id }),
            }).then((response) => response.json());

            if (!details) return;

            setEditingAssemblyId(id);
            setStandard(details.standard ?? '');
            setGas(details.gas ?? '');
            setHoseType(details.hoseTypeIds ?? []);
            setSwivel(details.swivelIds ?? []);
            setInlet(details.inletIds ?? []);
            setOutlet(details.outletIds ?? []);
            setLength(details.lengthIds ?? []);

            setIsEditOpen(true);
        } catch (error) {
            console.error('Error loading assembly details:', error);
        }
    };

    const { parts } = useHoseParts();

    const getOptionDisplay = (partId: string, optionId: any) => {
        const opt = parts
            .find(({ id }) => id === partId)
            ?.items
            ?.find(({ id }: any) => String(id) === String(optionId));

        if (!opt) return String(optionId ?? '');

        const label = String((opt as any).label ?? '').trim();
        const code = String((opt as any).code ?? '').trim();

        if (label && code) return `${label} (${code})`;
        return label || code || String(optionId ?? '');
    };
        
    return (
        <Panel
            action={{
                variant: 'secondary',
                text: 'Add Assembly',
                onClick: () => {
                    handleAddAssemblyOpen();
                },
            }}
            description="This is the panel's optional description."
            header="Hose Assembly"
        >
            <Box marginTop="large">
                <Box style={{ overflowX: 'auto', WebkitOverflowScrolling: 'touch' }}>
                    <Table
                        columns={[
                            { header: 'Gas', hash: 'gas_id', render: ({ gas_id }) => getOptionDisplay('hose_gas', gas_id) },
                            { header: 'Standard', hash: 'standard_id', render: ({ standard_id }) => getOptionDisplay('hose_standard', standard_id) },
                            { header: 'Action', hash: 'action', render: ({ id }) => (
                                <>
                                    <Button 
                                        variant="subtle" 
                                        iconOnly={<DeleteIcon />}
                                        aria-label="Delete option value"
                                        onClick={() => handleAssemblyDelete(id)}
                                    />
                                    <Button 
                                        variant="subtle" 
                                        iconOnly={<EditIcon />}
                                        aria-label="Edit option value"
                                        onClick={() => handleAssemblyEdit(id)}
                                    />
                                </>
                            )}
                        ]}
                        items={assemblies}
                        stickyHeader
                    />
                </Box>
            </Box>
            <Modal
                actions={[
                {
                    text: 'Cancel',
                    variant: 'subtle',
                    onClick: () => setIsOpen(false),
                },
                { text: 'Add', onClick: () =>
                    (document.getElementById("add-assembly-form") as HTMLFormElement)?.requestSubmit()
                },
                ]}
                closeOnClickOutside={false}
                closeOnEscKey={true}
                header="Gas Assembly"
                isOpen={isOpen}
                onClose={() => setIsOpen(false)}
            >
                <Form fullWidth={true} onSubmit={handleSubmit} id="add-assembly-form">
                    <FormGroup>
                        <Select
                            action={{
                                actionType: 'destructive' as const,
                                content: `Reset Standard`,
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Standard"
                            maxHeight={100}
                            onOptionChange={handleStandardChange}
                            options={parts.find(({ id }) => id === 'hose_standard')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Select Standard"
                            placement="bottom-start"
                            required
                            value={standard}
                        />
                    </FormGroup>
                    <FormGroup>
                        <Select
                            action={{
                                actionType: 'destructive' as const,
                                content: `Reset Gas`,
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Gas"
                            maxHeight={100}
                            onOptionChange={handleGasChange}
                            options={parts.find(({ id }) => id === 'hose_gas')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`
                            })) ?? []}
                            placeholder="Select Gas"
                            placement="bottom-start"
                            required
                            value={gas}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            key={`edit-hoseType-${String(editingAssemblyId ?? '')}`}
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Hose Type',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Hose Type"
                            maxHeight={100}
                            onOptionsChange={handleHoseTypeChange}
                            options={parts.find(({ id }) => id === 'hose_type')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Hose Type"
                            placement="bottom-start"
                            required
                            value={hoseType}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            key={`edit-swivel-${String(editingAssemblyId ?? '')}`}
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Swivel',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Swivel"
                            maxHeight={100}
                            onOptionsChange={handleSwivelChange}
                            options={parts.find(({ id }) => id === 'hose_swivel')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Swivel"
                            placement="bottom-start"
                            required
                            value={swivel}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            key={`edit-inlet-${String(editingAssemblyId ?? '')}`}
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Inlet',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Inlet"
                            maxHeight={100}
                            onOptionsChange={handleInletChange}
                            options={parts.find(({ id }) => id === 'hose_inlet')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Inlet"
                            placement="bottom-start"
                            required
                            value={inlet}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            key={`edit-outlet-${String(editingAssemblyId ?? '')}`}
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Outlet',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Outlet"
                            maxHeight={100}
                            onOptionsChange={handleOutletChange}
                            options={parts.find(({ id }) => id === 'hose_outlet')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Outlet"
                            placement="bottom-start"
                            required
                            value={outlet}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            key={`edit-length-${String(editingAssemblyId ?? '')}`}
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Length',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Length"
                            maxHeight={100}
                            onOptionsChange={handleLengthChange}
                            options={parts.find(({ id }) => id === 'hose_length')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Length"
                            placement="bottom-start"
                            required
                            value={length}
                        />
                    </FormGroup>
                </Form>
            </Modal>
            <Modal
                actions={[
                {
                    text: 'Cancel',
                    variant: 'subtle',
                    onClick: () => {
                        setIsEditOpen(false);
                        setEditingAssemblyId(null);
                    },
                },
                { text: 'Save', onClick: () =>
                    (document.getElementById("edit-assembly-form") as HTMLFormElement)?.requestSubmit()
                },
                ]}
                closeOnClickOutside={false}
                closeOnEscKey={true}
                header="Edit Gas Assembly"
                isOpen={isEditOpen}
                onClose={() => {
                    setIsEditOpen(false);
                    setEditingAssemblyId(null);
                }}
            >
                <Form fullWidth={true} onSubmit={handleEditSubmit} id="edit-assembly-form">
                    <FormGroup>
                        <Select
                            action={{
                                actionType: 'destructive' as const,
                                content: `Reset Standard`,
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            disabled={true}
                            filterable={true}
                            label="Standard"
                            maxHeight={100}
                            onOptionChange={handleStandardChange}
                            options={parts.find(({ id }) => id === 'hose_standard')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Select Standard"
                            placement="bottom-start"
                            required
                            value={standard}
                        />
                    </FormGroup>
                    <FormGroup>
                        <Select
                            action={{
                                actionType: 'destructive' as const,
                                content: `Reset Gas`,
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            disabled={true}
                            filterable={true}
                            label="Gas"
                            maxHeight={100}
                            onOptionChange={handleGasChange}
                            options={parts.find(({ id }) => id === 'hose_gas')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`
                            })) ?? []}
                            placeholder="Select Gas"
                            placement="bottom-start"
                            required
                            value={gas}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Hose Type',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Hose Type"
                            maxHeight={100}
                            onOptionsChange={handleHoseTypeChange}
                            options={parts.find(({ id }) => id === 'hose_type')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Hose Type"
                            placement="bottom-start"
                            required
                            value={hoseType}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Swivel',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Swivel"
                            maxHeight={100}
                            onOptionsChange={handleSwivelChange}
                            options={parts.find(({ id }) => id === 'hose_swivel')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Swivel"
                            placement="bottom-start"
                            required
                            value={swivel}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Inlet',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Inlet"
                            maxHeight={100}
                            onOptionsChange={handleInletChange}
                            options={parts.find(({ id }) => id === 'hose_inlet')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Inlet"
                            placement="bottom-start"
                            required
                            value={inlet}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Outlet',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Outlet"
                            maxHeight={100}
                            onOptionsChange={handleOutletChange}
                            options={parts.find(({ id }) => id === 'hose_outlet')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Outlet"
                            placement="bottom-start"
                            required
                            value={outlet}
                        />
                    </FormGroup>
                    <FormGroup>
                        <MultiSelect
                            action={{
                                actionType: 'destructive' as const,
                                content: 'Remove Length',
                                icon: <DeleteIcon />,
                                onActionClick: () => null,
                            }}
                            filterable={true}
                            label="Length"
                            maxHeight={100}
                            onOptionsChange={handleLengthChange}
                            options={parts.find(({ id }) => id === 'hose_length')?.items?.map(({ id, label, code }) => ({
                                value: String(id),
                                content: `${label} (${code})`,
                            })) ?? []}
                            placeholder="Choose Length"
                            placement="bottom-start"
                            required
                            value={length}
                        />
                    </FormGroup>
                </Form>
            </Modal>
        </Panel>
    );
};

export default Index;
