import Form from '@/components/form/Form';
import FormField from '@/components/form/FormField';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { type User } from '@/types';
import { yupResolver } from '@hookform/resolvers/yup';
import { router, usePage } from '@inertiajs/react';
import { Edit3, Loader2, Lock, UserPlus } from 'lucide-react';
import { useEffect, useState } from 'react';
import { SubmitHandler } from 'react-hook-form';
import { toast } from 'sonner';
import * as yup from 'yup';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '../ui/accordion';
import { log } from 'console';

interface Role {
    id: number;
    name: string;
}

interface UserModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    user?: User | null;
    roles: Role[];
    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(),
    };

    // Only require passwords for new users or when changing password during edit
    if (!isEditing) {
        return yup.object({
            ...baseSchema,
            password: yup.string().required('Password is required').min(8, 'Password must be at least 8 characters'),
            password_confirmation: yup
                .string()
                .required('Password confirmation is required')
                .oneOf([yup.ref('password')], 'Passwords must match'),
        });
    }

    // For editing, passwords are optional but must match if provided
    return yup
        .object({
            ...baseSchema,
            password: yup.string().optional(),
            password_confirmation: yup.string().optional(),
        })
        .test('passwords-match', 'Passwords must match', function (values) {
            const { password, password_confirmation } = values;

            // If password is provided, confirmation must also be provided and match
            if (password && password.length > 0) {
                if (!password_confirmation) {
                    return this.createError({
                        path: 'password_confirmation',
                        message: 'Password confirmation is required when password is provided',
                    });
                }
                if (password !== password_confirmation) {
                    return this.createError({
                        path: 'password_confirmation',
                        message: 'Passwords must match',
                    });
                }
                if (password.length < 8) {
                    return this.createError({
                        path: 'password',
                        message: 'Password must be at least 8 characters',
                    });
                }
            }

            return true;
        });
};

export function UserModal({ open, onOpenChange, user, roles, onSuccess }: UserModalProps) {

    const isAdmin = user?.is_admin;

    const [isSubmitting, setIsSubmitting] = useState(false);
    const isEditing = Boolean(user);
    const hasRoles = Boolean(roles && roles.length > 0);
    // Access Inertia page props to pull backend validation errors (422)
    const page = usePage<any>();

    const current_user_role = page.props.auth.user.current_role_name;


    // Transform roles into options format
    const roleOptions =
        roles?.map((role) => ({
            value: role.id.toString(),
            label: role.name,
        })) || [];

    // Get user's current role IDs for editing (multiselect)
    const getUserRoleIds = () => {
        if (!user?.role || !roles || roles.length === 0) return [];

        // Handle both string and array cases for user.role
        const userRoles = Array.isArray(user.role) ? user.role : [user.role];

        return userRoles
            ?.map((roleName: string) => {
                const roleObj = roles?.find((r) => r.name.toLowerCase() === roleName.toLowerCase());
                return roleObj ? roleObj.id.toString() : null;
            })
            .filter(Boolean) as string[];
    };

    // Helper function to split name into first and last name
    const getFirstName = () => {
        if (user?.first_name) return user.first_name;
        if (user?.name) {
            const nameParts = user.name.split(' ');
            return nameParts[0] || '';
        }
        return '';
    };

    const getLastName = () => {
        if (user?.last_name) return user.last_name;
        if (user?.name) {
            const nameParts = user.name.split(' ');
            return nameParts.slice(1).join(' ') || '';
        }
        return '';
    };

    const defaultValues = {
        first_name: getFirstName(),
        last_name: getLastName(),
        uid: user?.uid || '',
        email: user?.email || '',
        phone: user?.phone || '',
        address: user?.address || '',
        password: '',
        password_confirmation: '',
        roles: isEditing ? getUserRoleIds() : [],
    };

    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}`;
        }

        if (isEditing && !submitData.password) {
            delete submitData.password;
            delete submitData.password_confirmation;
        }

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

        try {
            const url = isEditing ? route('users.update', user!.id) : route('users.store');
            router.post(url, submitData, {
                onSuccess: () => {
                    toast.success(isEditing ? 'User updated successfully!' : 'User 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 User' : 'Add New User';
    const modalDescription = isEditing ? 'Update user account details and permissions' : "Create new user here. Click save when you're done.";
    const submitButtonText = isEditing ? 'Update User' : 'Create User';
    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, hasRoles))}
                        defaultValues={defaultValues}
                        key={user?.id || 'create'} // Force re-render when user changes
                        externalErrors={(page.props as any)?.errors}
                    >
                        {/* Personal 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>
                        {/* User 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
                                disabled={isEditing && current_user_role !== 'admin'}
                            />


                            {!isAdmin && (
                                <div className="space-y-1">
                                    <FormField
                                        type="multiselect"
                                        name="roles"
                                        label="Role"
                                        placeholder="Select roles (optional)"
                                        options={roleOptions || []}
                                        required={false}
                                    />
                                </div>
                            )}

                        </div>
                        {/* Contact and Role */}
                        <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="text" name="address" label="Address" placeholder="Address" />
                        </div>
                        {/* Password Section */}
                        {isEditing ? (
                            /* Password change accordion for editing */
                            <Accordion type="single" collapsible className="mb-5">
                                <AccordionItem value="password" className="rounded-lg border px-4">
                                    <AccordionTrigger className="hover:no-underline">
                                        <div className="flex items-center gap-2">
                                            <Lock className="h-4 w-4" />
                                            <span>Change Password</span>
                                        </div>
                                    </AccordionTrigger>
                                    <AccordionContent className="pt-4">
                                        <div className="grid gap-4 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2">
                                            <FormField
                                                type="password"
                                                name="password"
                                                label="New Password"
                                                placeholder="Enter new password"
                                                description="Leave empty to keep current password"
                                                required={false}
                                            />
                                            <FormField
                                                type="password"
                                                name="password_confirmation"
                                                label="Confirm New Password"
                                                placeholder="Confirm new password"
                                                required={false}
                                            />
                                        </div>
                                    </AccordionContent>
                                </AccordionItem>
                            </Accordion>
                        ) : (
                            /* Required password fields for creating */
                            <div className="mb-5 grid gap-4 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2">
                                <FormField
                                    type="password"
                                    name="password"
                                    label="Password"
                                    placeholder="Enter password"
                                    required
                                // description="Minimum 8 characters"
                                />
                                <FormField
                                    type="password"
                                    name="password_confirmation"
                                    label="Confirm Password"
                                    placeholder="Confirm password"
                                    required
                                />
                            </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>
    );
}
