import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { useAdminUser, useCreateAdminUser, useUpdateAdminUser } from '../core/_hooks';
import { AdminUserFormData } from '../core/_models';
import { usePermissions } from '../../permissions/core/_hooks';
import { useRoles } from '../../roles/core/_hooks';
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { MultiSelectAutocomplete, Option } from "@/components/ui/MultiSelectAutocomplete";
import { ArrowRight } from "lucide-react";
import { FormHeader, PageContainer, Label } from '../../../components/ui/Typography';

const adminUserSchema = yup.object({
    first_name: yup.string().required('نام الزامی است').min(2, 'نام باید حداقل 2 کاراکتر باشد'),
    last_name: yup.string().required('نام خانوادگی الزامی است').min(2, 'نام خانوادگی باید حداقل 2 کاراکتر باشد'),
    username: yup.string().required('نام کاربری الزامی است').min(3, 'نام کاربری باید حداقل 3 کاراکتر باشد'),
    password: yup.string().when('isEdit', {
        is: false,
        then: (schema) => schema.required('رمز عبور الزامی است').min(8, 'رمز عبور باید حداقل 8 کاراکتر باشد'),
        otherwise: (schema) => schema.notRequired().test('min-length', 'رمز عبور باید حداقل 8 کاراکتر باشد', function (value) {
            return !value || value.length >= 8;
        })
    }),
    status: yup.string().required('وضعیت الزامی است').oneOf(['active', 'deactive'], 'وضعیت نامعتبر است'),
    permissions: yup.array().of(yup.number()).default([]),
    roles: yup.array().of(yup.number()).default([]),
    isEdit: yup.boolean().default(false)
});

const AdminUserFormPage = () => {
    const navigate = useNavigate();
    const { id } = useParams<{ id: string }>();
    const isEdit = !!id;

    const { data: user, isLoading: isLoadingUser } = useAdminUser(id || '', isEdit);
    const { mutate: createUser, isPending: isCreating } = useCreateAdminUser();
    const { mutate: updateUser, isPending: isUpdating } = useUpdateAdminUser();

    const { data: permissions, isLoading: isLoadingPermissions } = usePermissions();
    const { data: roles, isLoading: isLoadingRoles } = useRoles();

    const isLoading = isCreating || isUpdating;

    const {
        register,
        handleSubmit,
        formState: { errors, isValid, isDirty },
        setValue,
        watch
    } = useForm<AdminUserFormData>({
        resolver: yupResolver(adminUserSchema) as any,
        mode: 'onChange',
        defaultValues: {
            first_name: '',
            last_name: '',
            username: '',
            password: '',
            status: 'active' as 'active' | 'deactive',
            permissions: [],
            roles: [],
            isEdit: isEdit
        }
    });

    // Debug form state
    const formValues = watch();
    console.log('🔍 Current form values:', formValues);
    console.log('🔍 Form isValid:', isValid);
    console.log('🔍 Form isDirty:', isDirty);
    console.log('🔍 Form errors:', errors);

    // Populate form when editing
    useEffect(() => {
        if (isEdit && user) {
            setValue('first_name', user.first_name, { shouldValidate: true });
            setValue('last_name', user.last_name, { shouldValidate: true });
            setValue('username', user.username, { shouldValidate: true });
            setValue('status', user.status, { shouldValidate: true });
            setValue('permissions', user.permissions?.map((p: any) => p.id) || [], { shouldValidate: true });
            setValue('roles', user.roles?.map((r: any) => r.id) || [], { shouldValidate: true });
            setValue('isEdit', true, { shouldValidate: true });
        }
    }, [isEdit, user, setValue]);

    const onSubmit = (data: AdminUserFormData) => {
        if (isEdit && id) {
            updateUser({
                id,
                userData: {
                    id: parseInt(id),
                    first_name: data.first_name,
                    last_name: data.last_name,
                    username: data.username,
                    password: data.password && data.password.trim() ? data.password : undefined,
                    status: data.status,
                    permissions: data.permissions,
                    roles: data.roles
                }
            }, {
                onSuccess: () => {
                    navigate('/admin-users');
                }
            });
        } else {
            console.log('🚀 Creating new admin user...');
            createUser({
                first_name: data.first_name,
                last_name: data.last_name,
                username: data.username,
                password: data.password || '',
                status: data.status,
                permissions: data.permissions,
                roles: data.roles
            }, {
                onSuccess: (result) => {
                    console.log('✅ Admin user created successfully:', result);
                    console.log('🔄 Navigating to admin users list...');
                    navigate('/admin-users');
                },
                onError: (error) => {
                    console.error('❌ Error in component onError:', error);
                }
            });
        }
    };

    const handleBack = () => {
        navigate('/admin-users');
    };

    if (isEdit && isLoadingUser) {
        return (
            <PageContainer>
                <div className="space-y-6 animate-pulse">
                    <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
                    <div className="card p-6 space-y-6">
                        {[...Array(6)].map((_, i) => (
                            <div key={i}>
                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2"></div>
                                <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
                            </div>
                        ))}
                    </div>
                </div>
            </PageContainer>
        );
    }

    const backButton = (
        <Button
            variant="secondary"
            onClick={handleBack}
            className="flex items-center gap-2"
        >
            <ArrowRight className="h-4 w-4" />
            بازگشت
        </Button>
    );

    return (
        <PageContainer className="max-w-2xl mx-auto">
            <FormHeader
                title={isEdit ? 'ویرایش کاربر ادمین' : 'ایجاد کاربر ادمین جدید'}
                subtitle={isEdit ? 'ویرایش اطلاعات کاربر ادمین' : 'اطلاعات کاربر ادمین جدید را وارد کنید'}
                backButton={backButton}
            />

            {/* Form */}
            <div className="card p-4 sm:p-6">
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 sm:space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <Input
                            label="نام"
                            {...register('first_name')}
                            error={errors.first_name?.message}
                            placeholder="نام کاربر"
                        />
                        <Input
                            label="نام خانوادگی"
                            {...register('last_name')}
                            error={errors.last_name?.message}
                            placeholder="نام خانوادگی کاربر"
                        />
                    </div>

                    <Input
                        label="نام کاربری"
                        {...register('username')}
                        error={errors.username?.message}
                        placeholder="نام کاربری"
                    />

                    <Input
                        label={isEdit ? "رمز عبور (اختیاری)" : "رمز عبور"}
                        type="password"
                        {...register('password')}
                        error={errors.password?.message}
                        placeholder={isEdit ? "رمز عبور جدید (در صورت تمایل به تغییر)" : "رمز عبور"}
                    />

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <MultiSelectAutocomplete
                            label="دسترسی‌ها"
                            options={(permissions || []).map((permission): Option => ({
                                id: permission.id,
                                title: permission.title,
                                description: permission.description
                            }))}
                            selectedValues={watch('permissions') || []}
                            onChange={(values) => setValue('permissions', values, { shouldValidate: true })}
                            placeholder="انتخاب دسترسی‌ها..."
                            isLoading={isLoadingPermissions}
                            error={errors.permissions?.message}
                        />

                        <MultiSelectAutocomplete
                            label="نقش‌ها"
                            options={(roles || []).map((role): Option => ({
                                id: role.id,
                                title: role.title,
                                description: role.description
                            }))}
                            selectedValues={watch('roles') || []}
                            onChange={(values) => setValue('roles', values, { shouldValidate: true })}
                            placeholder="انتخاب نقش‌ها..."
                            isLoading={isLoadingRoles}
                            error={errors.roles?.message}
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            وضعیت
                        </label>
                        <select
                            {...register('status')}
                            className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                        >
                            <option value="active">فعال</option>
                            <option value="deactive">غیرفعال</option>
                        </select>
                        {errors.status && (
                            <p className="text-red-500 text-sm mt-1">{errors.status.message}</p>
                        )}
                    </div>

                    <div className="flex justify-end space-x-4 space-x-reverse pt-6 border-t border-gray-200 dark:border-gray-600">
                        <Button
                            type="button"
                            variant="secondary"
                            onClick={handleBack}
                            disabled={isLoading}
                        >
                            انصراف
                        </Button>
                        <Button
                            type="submit"
                            loading={isLoading}
                            disabled={!isValid || isLoading}
                        >
                            {isEdit ? 'به‌روزرسانی' : 'ایجاد'}
                        </Button>
                    </div>
                </form>
            </div>
        </PageContainer>
    );
};

export default AdminUserFormPage; 