'use client';
import Form from '@/components/form/Form';
import FormField from '@/components/form/FormField';
import { Button } from '@/components/ui/button';
import { PhoneInputField as PhoneField } from '@/components/ui/phone-input';
import { zodResolver } from '@hookform/resolvers/zod';
import { Plus } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { route } from 'ziggy-js';
import { z } from 'zod';

const PhoneInputField = ({ serverError }: { serverError?: string }) => {
    const { watch, setValue } = useFormContext();
    const phoneValue = watch('phone');

    const handlePhoneChange = (value: string | undefined) => {
        setValue('phone', value || '', {
            shouldDirty: true,
            shouldTouch: true,
            shouldValidate: false,
        });
    };

    const handleBlur = () => {
        setValue('phone', phoneValue || '', { shouldValidate: true });
    };

    return (
        <PhoneField
            label="Phone Number"
            value={phoneValue || ''}
            onChange={handlePhoneChange}
            onBlur={handleBlur}
            defaultCountry="US"
            placeholder="Enter phone number"
            errorMessage={serverError}
            international
            countryCallingCodeEditable={false}
        />
    );
};

// Login checkbox component that uses form context
const LoginCheckboxField = () => {
    const { watch, setValue } = useFormContext();
    const isLoginEnabled = watch('is_login');

    return (
        <div className="space-y-4">
            <label className="flex items-center space-x-2">
                <input
                    type="checkbox"
                    className="h-4 w-4 rounded border-gray-300"
                    checked={isLoginEnabled || false}
                    onChange={(e) => {
                        setValue('is_login', e.target.checked, { shouldValidate: false });
                        // Clear password if disabling login
                        if (!e.target.checked) {
                            setValue('password', '', { shouldValidate: false });
                        }
                    }}
                />
                <span className="text-sm text-gray-700">Allow login access</span>
            </label>

            {isLoginEnabled && <FormField name="password" label="Password" type="password" placeholder="Enter password for login access" required />}
        </div>
    );
};

export type UserFormValues = z.infer<typeof UserFormSchema>;

export type NormalizedUserPayload = {
    name: string;
    email: string;
    phone: string;
};

interface UserFormProps {
    mode: 'add' | 'edit';
    initialUser?: any;
    onSubmitUser: (payload: NormalizedUserPayload) => void;
    onCancel?: () => void;
    className?: string;
    title?: string;
    appName?: string;
    serverErrors?: Record<string, string>;
    customerTypeSetting?: 'company' | 'individual' | 'both';
}

const UserFormSchema = z.object({
    name: z.string().min(3, 'Name must be at least 3 characters'),
    email: z.string().email('Please enter a valid email').min(1, 'Email is required'),
    phone: z.string().optional().or(z.literal('')),
    country_code: z.string().optional().or(z.literal('')),
    is_login: z.boolean().optional(),
    password: z.string().optional().or(z.literal('')),
    app_name: z.string().min(1, 'App name is required'),
    source: z.string().min(1, 'Source is required'),
    assigned_to: z
        .array(z.union([z.number(), z.string()]))
        .optional()
        .default([]),
    contact_owner: z.union([z.number(), z.string()]).optional().nullable(),
    category: z.number().default(1),
    status: z.number().default(1),
});

export default function UserForm({
    mode,
    initialUser,
    onSubmitUser,
    onCancel,
    className,
    title,
    appName = 'main',
    serverErrors = {},
    customerTypeSetting = 'both',
}: UserFormProps) {
    console.log('🚀 ~ UserForm ~ initialUser:', initialUser);
    const [users, setUsers] = useState<Array<{ label: string; value: number }>>([]);

    // Fetch users for assignment dropdowns
    useEffect(() => {
        const fetchUsers = async () => {
            try {
                const response = await fetch(route('users.api'));

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();
                console.log('🚀 ~ fetchUsers ~ result:', result);

                if (result.success) {
                    console.log('🚀 ~ Setting users data:', result.data);
                    setUsers(result.data);
                } else {
                    console.error('Failed to fetch users:', result.message);
                }
            } catch (error) {
                console.error('Failed to fetch users:', error);
            }
        };
        fetchUsers();
    }, []);

    const defaultValues = useMemo(() => {
        // Debug: Log the initial user data to see the structure
        console.log('🚀 ~ UserForm ~ initialUser:', initialUser);
        console.log('🚀 ~ UserForm ~ initialUser?.assigned_users:', initialUser?.assigned_users);
        console.log('🚀 ~ UserForm ~ initialUser?.manager:', initialUser?.manager);

        // Handle both possible data structures: assigned_users (from API) or assigned_to (legacy)
        const assignedData = initialUser?.assigned_users || initialUser?.assigned_to || [];
        const assignedUserIds = Array.isArray(assignedData) ? assignedData.map((user: any) => String(user.id)) : [];

        // Handle both possible data structures: manager (from API) or owner (legacy)
        const ownerData = initialUser?.manager || initialUser?.owner;
        const contactOwnerId = ownerData?.id ? String(ownerData.id) : null;

        return {
            name: initialUser?.name || '',
            email: initialUser?.email || '',
            phone: initialUser?.phone || '',
            country_code: initialUser?.country_code || '',
            is_login: initialUser?.is_login || mode === 'add' || false,
            password: mode === 'add' ? 'password' : '',
            app_name: appName || 'main',
            source: initialUser?.source || 'lead',
            assigned_to: assignedUserIds,
            contact_owner: contactOwnerId,
            category: initialUser?.category ?? 1,
            status: initialUser?.status ?? 1, // Use ?? to allow 0 (inactive) status
        };
    }, [initialUser, appName, customerTypeSetting, mode, title]);

    const resolver = zodResolver(UserFormSchema);

    const handleSubmit = async (values: UserFormValues) => {
        const payload: any = {
            name: values.name,
            email: values.email || '',
            phone: values.phone || '',
            is_login: values.is_login || false,
            password: values.password || '',
            app_name: values.app_name || appName || 'main',
            source: values.source || 'lead',
            // Keep as strings to match Edit page behavior - backend handles conversion
            assigned_to: Array.isArray(values.assigned_to) ? values.assigned_to.map((id) => String(id)) : [],
            contact_owner: values.contact_owner ? String(values.contact_owner) : null,
            category: values.category ?? 1,
            status: values.status ?? 1, // Use ?? to allow 0 (inactive) status
        };
        // console.log('🚀 ~ handleSubmit ~ payload:', payload);

        onSubmitUser(payload);
    };

    console.log('🚀 ~ UserForm ~ Final defaultValues:', defaultValues);
    console.log('🚀 ~ UserForm ~ Users options:', users);

    return (
        <div className={['space-y-6 p-2', className].filter(Boolean).join(' ')}>
            <Form submitHandler={handleSubmit} defaultValues={defaultValues} formClassNames="space-y-6" resolver={resolver}>
                <div>
                    <FormField name="name" label="Name" type="text" placeholder="e.g. John Smith" required />
                    {serverErrors.name && <p className="mt-1 text-sm text-red-500">{serverErrors.name}</p>}
                </div>

                <div>
                    <FormField name="email" label="Primary Email" type="email" placeholder="e.g. john@example.com" required />
                    {serverErrors.email && <p className="mt-1 text-sm text-red-500">{serverErrors.email}</p>}
                </div>

                <PhoneInputField serverError={serverErrors.phone} />

                <div className="grid grid-cols-2 gap-2">
                    <FormField
                        name="status"
                        label="Status"
                        type="select"
                        options={[
                            { label: 'Active', value: 1 },
                            { label: 'Inactive', value: 0 },
                            { label: 'Freezed', value: 16 },
                        ]}
                        className="h-10"
                    />
                </div>

                <LoginCheckboxField />
                {/* <div>
                    <FormField name="password" label="Password" type="password" placeholder="Enter password for login access" required />
                    {serverErrors.password && <p className="mt-1 text-sm text-red-500">{serverErrors.password}</p>}
                </div> */}

                <div className="flex justify-end gap-3">
                    {onCancel && (
                        <Button variant="outline" type="button" onClick={onCancel}>
                            Cancel
                        </Button>
                    )}
                    <Button className="hover:bg-success-800 bg-success text-white" type="submit">
                        <Plus className="h-4 w-4" />
                        {mode === 'add' ? `Add ${title}` : `Edit ${title}`}
                    </Button>
                </div>
            </Form>
        </div>
    );
}
