import { Button } from '@/components/ui/button';
import { useTranslation } from '@/hooks/use-translation';
import axios, { AxiosError } from 'axios';
import { UserPlus, X } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import type { OwnerOption } from '../types';
import { OwnerFormFields, type OwnerFormShape } from './OwnerFormFields';

const EMPTY_OWNER: OwnerFormShape = {
    name: '',
    last_name: '',
    civilite: '',
    cin: '',
    pay_origine: '',
    email: '',
    phone: '',
    prefix_phone: '',
    password: '',
    photo_cin_recto: null,
    photo_cin_verso: null,
};

/**
 * Full "Créer un propriétaire" form rendered INLINE in the wizard when the
 * operator picks that mode in OwnerModeSelector (previously a nested Radix
 * dialog). Inline avoids the whole nested-modal focus/z-index fight and keeps
 * the wizard in one visual flow.
 *
 * Two constraints follow from living inside the AddFolderDialog's <form>:
 *  - No <form> element here (nested forms are invalid HTML and the inner one is
 *    silently dropped). Submission is driven by an explicit type="button" click.
 *  - Enter is intercepted so it creates the propriétaire instead of bubbling up
 *    and making the wizard jump to step 2.
 *
 * Creates a standalone User with role 'proprietaire' via axios (not Inertia
 * useForm) so the new record's id comes back as JSON without a page reload.
 */
export const InlineCreateOwnerPanel = ({
    onCreated,
    onCancel,
    phonesPrefix,
    initialEmail,
}: {
    onCreated: (owner: OwnerOption) => void;
    onCancel: () => void;
    phonesPrefix: string[];
    initialEmail?: string;
}) => {
    const { t } = useTranslation();
    const [data, setData] = useState<OwnerFormShape>({ ...EMPTY_OWNER, email: initialEmail ?? '' });
    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 submit = async () => {
        if (processing) return;
        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'));
            setData({ ...EMPTY_OWNER });
            onCreated(owner);
        } 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);
        }
    };

    // Enter inside any field of this panel means "create the propriétaire",
    // never "go to step 2". Textareas keep their newline behaviour.
    const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
        if (e.key !== 'Enter') return;
        const target = e.target as HTMLElement;
        if (target.tagName === 'TEXTAREA') return;
        e.preventDefault();
        e.stopPropagation();
        void submit();
    };

    return (
        <div className="bg-muted/30 rounded-lg border p-4" onKeyDown={handleKeyDown}>
            <div className="flex items-start justify-between gap-2">
                <div>
                    <h4 className="text-secondary flex items-center gap-2 text-sm font-semibold">
                        <UserPlus className="h-4 w-4" />
                        {t('crm', 'create_owner')}
                    </h4>
                    <p className="text-muted-foreground mt-1 text-xs">{t('crm', 'standalone_owner_description')}</p>
                </div>
                <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={onCancel}
                    disabled={processing}
                    aria-label={t('crm', 'inline_create_owner_cancel')}
                    title={t('crm', 'inline_create_owner_cancel')}
                >
                    <X className="h-4 w-4" />
                </Button>
            </div>

            {/* nativeRequired={false}: the browser must not run HTML validation on
                these fields when the operator clicks "Suivant" on the wizard —
                the server owns validation here and reports it as 422 + toast. */}
            <OwnerFormFields
                data={data}
                setData={updateField}
                errors={errors}
                phonesPrefix={phonesPrefix}
                requireCinFiles={false}
                nativeRequired={false}
            />

            <div className="mt-4 flex items-center gap-2">
                <Button type="button" variant="outline" onClick={onCancel} disabled={processing}>
                    {t('crm', 'inline_create_owner_cancel')}
                </Button>
                <Button type="button" className="bg-secondary flex-1" onClick={() => void submit()} disabled={processing}>
                    {processing ? t('crm', 'processing') : t('crm', 'create_owner_submit')}
                </Button>
            </div>
        </div>
    );
};
