import ComboBoxInput from '@/Components/ComboBoxInput';
import FormInput from '@/Components/FormInput';
import NotificationChannelsSelect from '@/Components/NotificationChannelsSelect';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import {
    Sheet,
    SheetContent,
    SheetDescription,
    SheetHeader,
    SheetTitle,
    SheetTrigger,
} from '@/Components/ui/sheet';
import { t } from '@/lib/utils';
import { User } from '@/types';
import { useForm } from '@inertiajs/react';
import axios from 'axios';
import { Loader2 } from 'lucide-react';
import React, { FormEventHandler, useState } from 'react';

interface ContactCreateFormProps {
    availableNotificationChannels: string[];
}

interface ContactFormData {
    user: User | null;
    label: string;
    email: string;
    phone: string | null;
    notification_channels: string[];
}

export default function ContactCreateForm({
    availableNotificationChannels,
}: ContactCreateFormProps) {
    const [open, setOpen] = React.useState(false);
    const [availableUsers, setAvailableUsers] = useState<User[]>([]);

    const { data, setData, post, processing, errors, reset, transform } =
        useForm<ContactFormData>({
            user: null,
            label: 'Figlio',
            email: '',
            phone: null,
            notification_channels: ['mail'],
        });
    const formErrors = errors as Record<string, string>;

    const submit: FormEventHandler = (e) => {
        e.preventDefault();

        transform(
            (data) =>
                ({
                    ...data,
                    user_id: data.user ? data.user.id : null,
                }) as unknown as ContactFormData,
        );

        post(route('contacts.create'), {
            onSuccess: () => {
                setOpen(false);
                reset();
            },
        });
    };

    const fetchUsers = async (search: string) => {
        try {
            const response = await axios.get(route('search-users'), {
                params: { search },
            });
            setAvailableUsers(response.data);
        } catch (error) {
            console.error('Error fetching items:', error);
        }
    };

    return (
        <Sheet open={open} onOpenChange={setOpen}>
            <SheetTrigger asChild>
                <PrimaryButton>Aggiungi</PrimaryButton>
            </SheetTrigger>
            <SheetContent side="right" className="overflow-auto">
                <SheetHeader>
                    <SheetTitle>Nuovo contatto</SheetTitle>
                    <SheetDescription>
                        <form onSubmit={submit}>
                            <FormInput
                                label="Utente"
                                id="user_id"
                                className="mt-8 block w-full"
                                error={formErrors.user_id}
                            >
                                <ComboBoxInput
                                    value={data.user}
                                    options={availableUsers}
                                    renderOption={(user) =>
                                        `${user.name} ${user.surname}`
                                    }
                                    onChange={(value) => setData('user', value)}
                                    onSearchChange={fetchUsers}
                                />
                            </FormInput>
                            <FormInput
                                label="Etichetta"
                                id="label"
                                className="mt-8 block w-full"
                                error={errors.label}
                            >
                                <TextInput
                                    value={data.label}
                                    onChange={(e) =>
                                        setData('label', e.target.value)
                                    }
                                />
                            </FormInput>
                            <FormInput
                                label="Email"
                                id="email"
                                className="mt-8 block w-full"
                                error={errors.email}
                            >
                                <TextInput
                                    value={data.email}
                                    onChange={(e) =>
                                        setData('email', e.target.value)
                                    }
                                />
                            </FormInput>
                            <FormInput
                                label="Numero di telefono"
                                id="phone"
                                className="my-4 block w-full"
                                error={errors.phone}
                            >
                                <TextInput
                                    value={data.phone}
                                    onChange={(e) =>
                                        setData('phone', e.target.value)
                                    }
                                />
                            </FormInput>
                            <FormInput
                                label="Notifica via"
                                id="notification_channels"
                                className="my-4 block w-full"
                                error={errors.notification_channels}
                            >
                                <NotificationChannelsSelect
                                    onChange={(channels) =>
                                        setData(
                                            'notification_channels',
                                            channels,
                                        )
                                    }
                                    value={data.notification_channels}
                                    availableValues={
                                        availableNotificationChannels
                                    }
                                />
                            </FormInput>

                            <div className="mt-20 flex items-center justify-end">
                                <PrimaryButton
                                    className="ms-4"
                                    disabled={processing}
                                >
                                    {processing ? (
                                        <Loader2 className="animate-spin" />
                                    ) : null}
                                    {t('Save')}
                                </PrimaryButton>
                            </div>
                        </form>
                    </SheetDescription>
                </SheetHeader>
            </SheetContent>
        </Sheet>
    );
}
