import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useTranslation } from '@/hooks/use-translation';
import axios, { AxiosError } from 'axios';
import { useState } from 'react';
import { toast } from 'sonner';
import type { OwnerOption } from '../types';
import { OwnerFormFields, type OwnerFormShape } from './OwnerFormFields';

/**
 * Nested dialog opened from the OwnerCombobox when the operator clicks
 * "+ Ajouter un nouveau propriétaire". Not tied to any folder — creates a
 * standalone User with role 'proprietaire' and hands the new record back to
 * the parent via onCreated so the combobox can auto-select it.
 *
 * Uses axios instead of Inertia useForm so we can get the new user's id
 * back in a JSON response without a full page reload.
 */
export const StandaloneCreateOwnerDialog = ({
    open,
    onOpenChange,
    onCreated,
    phonesPrefix,
    initialEmail,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onCreated: (owner: OwnerOption) => void;
    phonesPrefix: string[];
    initialEmail?: string;
}) => {
    const { t } = useTranslation();
    const [data, setData] = useState<OwnerFormShape>({
        name: '',
        last_name: '',
        civilite: '',
        cin: '',
        pay_origine: '',
        email: initialEmail ?? '',
        phone: '',
        prefix_phone: '',
        password: '',
        photo_cin_recto: null,
        photo_cin_verso: null,
    });
    const [errors, setErrors] = useState<Partial<Record<keyof OwnerFormShape, string>>>({});
    const [processing, setProcessing] = useState(false);

    const updateField = <K extends keyof OwnerFormShape>(key: K, value: OwnerFormShape[K]) => {
        setData((prev) => ({ ...prev, [key]: value }));
        if (errors[key]) {
            setErrors((prev) => {
                const next = { ...prev };
                delete next[key];
                return next;
            });
        }
    };

    const resetForm = () => {
        setData({
            name: '',
            last_name: '',
            civilite: '',
            cin: '',
            pay_origine: '',
            email: '',
            phone: '',
            prefix_phone: '',
            password: '',
            photo_cin_recto: null,
            photo_cin_verso: null,
        });
        setErrors({});
    };

    const submit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setProcessing(true);
        setErrors({});
        try {
            const formData = new FormData();
            formData.append('name', data.name);
            formData.append('last_name', data.last_name);
            formData.append('civilite', data.civilite);
            formData.append('cin', data.cin);
            formData.append('pay_origine', data.pay_origine);
            formData.append('email', data.email);
            formData.append('phone', data.phone);
            formData.append('prefix_phone', data.prefix_phone);
            formData.append('password', data.password);
            if (data.photo_cin_recto) formData.append('photo_cin_recto', data.photo_cin_recto);
            if (data.photo_cin_verso) formData.append('photo_cin_verso', data.photo_cin_verso);

            const response = await axios.post(route('crm.onboarding.owners.quick-store'), formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });

            const owner: OwnerOption = response.data.owner;
            toast.success(t('crm', 'owner_created_success'));
            onCreated(owner);
            resetForm();
            onOpenChange(false);
        } catch (err) {
            const axiosError = err as AxiosError<{ errors?: Record<string, string[]>; message?: string }>;
            if (axiosError.response?.status === 422 && axiosError.response.data.errors) {
                const serverErrors: Partial<Record<keyof OwnerFormShape, string>> = {};
                Object.entries(axiosError.response.data.errors).forEach(([key, messages]) => {
                    serverErrors[key as keyof OwnerFormShape] = messages[0];
                    toast.error(messages[0]);
                });
                setErrors(serverErrors);
            } else {
                toast.error(axiosError.response?.data?.message ?? t('crm', 'owner_create_error'));
            }
        } finally {
            setProcessing(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="z-[60] max-h-[90vh] overflow-y-auto sm:max-w-[520px]">
                <DialogHeader>
                    <DialogTitle>{t('crm', 'create_owner')}</DialogTitle>
                    <DialogDescription>{t('crm', 'standalone_owner_description')}</DialogDescription>
                </DialogHeader>
                <form onSubmit={submit}>
                    <OwnerFormFields
                        data={data}
                        setData={updateField}
                        errors={errors}
                        phonesPrefix={phonesPrefix}
                        requireCinFiles={false}
                    />
                    <Button type="submit" className="bg-secondary mt-4 w-full" disabled={processing}>
                        {processing ? t('crm', 'processing') : t('crm', 'create_owner_submit')}
                    </Button>
                </form>
            </DialogContent>
        </Dialog>
    );
};
