import Form from '@admin/components/form/Form';
import FormField from '@admin/components/form/FormField';
import { Button } from '@admin/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@admin/components/ui/dialog';
import { Item } from '@admin/types/item';
import { yupResolver } from '@hookform/resolvers/yup';
import { router } from '@inertiajs/react';
import { Edit3, Loader2, UserPlus } from 'lucide-react';
import { useEffect, useState } from 'react';
import { SubmitHandler } from 'react-hook-form';
import { toast } from 'sonner';
import * as yup from 'yup';


interface ItemModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    item?: Item | null;
    filters?: any[]; // Changed from roles to filters
    onSuccess?: () => void;
}

// Create validation schema that adapts based on edit mode
const createSchema = (isEditing: boolean, hasRoles: boolean = true) => {
    const baseSchema = {
        first_name: yup.string().required('First name is required').min(2, 'First name must be at least 2 characters'),
        last_name: yup.string().required('Last name is required').min(2, 'Last name must be at least 2 characters'),
        uid: yup.string().optional(),
        email: yup.string().email('Invalid email address').required('Email is required'),
        phone: yup.string().optional(),
        address: yup.string().optional(),
        // Roles now optional. If you later want at least one role when any roles exist, restore min(1,...)
        roles: yup.array().of(yup.string()).optional(),
    };

    // For editing, passwords are optional but must match if provided
    return yup.object({
        ...baseSchema,
        password: yup.string().optional(),
        password_confirmation: yup.string().optional(),
    });
};

// Static default item data to show in the form when creating a new item
const staticDefaultItem = {
    first_name: '',
    last_name: '',
    uid: 'ITEM-' + Math.floor(1000 + Math.random() * 9000), // Random ID
    email: '',
    phone: '',
    address: '',
    status: 'active',
    type: 'Type 1',
    roles: [],
};

export function AddEditModal({ open, onOpenChange, item, filters = [], onSuccess }: ItemModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const isEditing = Boolean(item);

    // Transform filters into options format for the select dropdown
    const filterOptions = filters.map((filter) => ({
        value: filter.value,
        label: filter.label,
    }));

    // Helper function to split name into first and last name
    const getFirstName = () => {
        if (item?.first_name) return item.first_name;
        if (item?.name) {
            const nameParts = item.name.split(' ');
            return nameParts[0] || '';
        }
        // Use static default when creating new item
        return staticDefaultItem.first_name;
    };

    const getLastName = () => {
        if (item?.last_name) return item.last_name;
        if (item?.name) {
            const nameParts = item.name.split(' ');
            return nameParts.slice(1).join(' ') || '';
        }
        // Use static default when creating new item
        return staticDefaultItem.last_name;
    };

    // Use the static default data when creating a new item
    const defaultValues = {
        first_name: getFirstName(),
        last_name: getLastName(),
        uid: item?.uid || staticDefaultItem.uid,
        email: item?.email || staticDefaultItem.email,
        phone: item?.phone || staticDefaultItem.phone,
        address: item?.address || staticDefaultItem.address,
        type: item?.type || staticDefaultItem.type,
        status: item?.status || staticDefaultItem.status,
        roles: [],
    };

    const handleSubmit: SubmitHandler<any> = async (data) => {
        setIsSubmitting(true);

        // Remove empty password fields for editing
        const submitData = { ...data };

        // Combine first_name and last_name into name for backend compatibility
        if (submitData.first_name && submitData.last_name) {
            submitData.name = `${submitData.first_name} ${submitData.last_name}`;
        }

        // Add method for editing
        if (isEditing) {
            submitData._method = 'put';
        }

        try {
            // Use the appropriate route based on whether we're editing or creating
            const url = isEditing ? route('items.update', item!.id) : route('items.store');
            router.post(url, submitData, {
                onSuccess: () => {
                    toast.success(isEditing ? 'Item updated successfully!' : 'Item created successfully!');
                    onOpenChange(false);
                    onSuccess?.();
                },
                onError: (errors) => {
                    console.error('Form submission errors:', errors);
                    toast.error('Something went wrong. Please try again.');
                },
                onFinish: () => {
                    setIsSubmitting(false);
                },
            });
        } catch (error) {
            console.error('Submission error:', error);
            toast.error('Something went wrong. Please try again.');
            setIsSubmitting(false);
        }
    };

    const modalTitle = isEditing ? 'Edit Item' : 'Add New Item';
    const modalDescription = isEditing ? 'Update item details' : "Create new item here. Click save when you're done.";
    const submitButtonText = isEditing ? 'Update Item' : 'Create Item';
    const IconComponent = isEditing ? Edit3 : UserPlus;

    // Reset form when modal closes or user changes
    useEffect(() => {
        if (!open) {
            // Reset form state when modal closes
            setIsSubmitting(false);
        }
    }, [open]);

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-h-[95vh] w-[95vw] max-w-4xl overflow-y-auto sm:w-[90vw] md:max-w-3xl">
                <DialogHeader className="gap-0 pb-4">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between">
                        <div className="flex items-center gap-3">
                            <IconComponent className="h-6 w-6" />

                            <div>
                                <DialogTitle className="text-lg sm:text-xl">{modalTitle}</DialogTitle>
                            </div>
                        </div>
                    </div>
                    <DialogDescription className="text-sm text-text-gray sm:text-base">{modalDescription}</DialogDescription>
                </DialogHeader>

                <div className="space-y-6 rounded-lg border px-2 py-4 sm:px-4 md:px-6">
                    <Form
                        submitHandler={handleSubmit}
                        resolver={yupResolver(createSchema(isEditing))}
                        defaultValues={defaultValues}
                        key={item?.id || 'create'} // Force re-render when item changes
                        // externalErrors={(page.props as any)?.errors}
                    >
                        {/* Item Details */}
                        <div className="mb-5 grid gap-4 sm:grid-cols-1 md:grid-cols-2">
                            <FormField type="text" name="first_name" label="First Name" placeholder="John" required />
                            <FormField type="text" name="last_name" label="Last Name" placeholder="Doe" required />
                        </div>
                        {/* Item Information */}
                        <div className="mb-5 grid gap-4 sm:grid-cols-1 md:grid-cols-2">
                            <FormField type="email" name="email" label="Email" placeholder="john.doe@gmail.com" required />

                            <div className="space-y-1">
                                <FormField
                                    type="select"
                                    name="type"
                                    label="Type"
                                    placeholder="Select type"
                                    options={filterOptions || []}
                                    required={false}
                                />
                            </div>
                        </div>
                        {/* Contact and Status */}
                        <div className="mb-5 grid gap-4 sm:grid-cols-1 md:grid-cols-2">
                            <FormField type="text" name="phone" label="Phone Number" placeholder="+123456789" />
                            <FormField
                                type="select"
                                name="status"
                                label="Status"
                                placeholder="Select status"
                                options={[
                                    { value: 'active', label: 'Active' },
                                    { value: 'inactive', label: 'Inactive' },
                                    { value: 'pending', label: 'Pending' },
                                ]}
                            />
                        </div>
                        {/* Additional fields */}
                        <div className="mb-5">
                            <FormField type="text" name="address" label="Address" placeholder="Address" />
                        </div>

                        {/* Actions */}
                        <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                            <Button type="submit" disabled={isSubmitting} className="w-full bg-success hover:bg-brand-800 sm:w-auto">
                                {isSubmitting ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        {isEditing ? 'Updating...' : 'Creating...'}
                                    </>
                                ) : (
                                    <>Save Changes</>
                                )}
                            </Button>
                        </div>
                    </Form>
                </div>
            </DialogContent>
        </Dialog>
    );
}
