import { Form, FormField } from '@/components/form';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import { router, usePage } from '@inertiajs/react';
import { ArrowLeft, Building2, CreditCard, FileText, Link2, Lock, MapPin, Phone, Plus, Tag, Trash2, User, Users, X } from 'lucide-react';
import React, { ReactNode, useEffect, useState } from 'react';
import { SubmitHandler, useFormContext, useWatch } from 'react-hook-form';
import PhoneInput from 'react-phone-number-input';
import 'react-phone-number-input/style.css';
import { toast } from 'sonner';

declare const route: (...args: any[]) => string;

const CustomPhoneInput = React.forwardRef<HTMLInputElement, any>((props, ref) => (
    <input
        {...props}
        ref={ref}
        className="w-full rounded-md border-0 bg-transparent px-3 py-2 text-sm outline-none placeholder:text-gray-400"
        autoComplete="tel"
    />
));
CustomPhoneInput.displayName = 'CustomPhoneInput';

function PhoneInputField({ name = 'primary_phone', label = 'Phone Number' }: { name?: string; label?: string }) {
    // Hooks
    const { watch, setValue } = useFormContext();

    // Get the phone value directly - it should already be in E164 format
    const phoneValue = watch(name);

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

    return (
        <div className="space-y-1.5">
            <label className="block text-sm font-medium text-gray-700">{label}</label>
            <PhoneInput
                international
                countryCallingCodeEditable={false}
                value={phoneValue || ''}
                onChange={handlePhoneChange}
                defaultCountry="US"
                placeholder="Enter phone number"
                className="flex rounded-lg border border-gray-300 bg-white shadow-sm focus-within:border-blue-500 focus-within:ring-1 focus-within:ring-blue-500"
                inputComponent={CustomPhoneInput}
                style={
                    {
                        '--PhoneInputCountryFlag-height': '1em',
                        '--PhoneInput-color--focus': '#3b82f6',
                    } as React.CSSProperties
                }
            />
        </div>
    );
}

function LoginAccessField() {
    // Hooks
    const { watch, setValue } = useFormContext();

    // State
    const isLoginEnabled = watch('is_login');

    return (
        <div className="space-y-3">
            <label className="flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 transition-colors hover:bg-gray-100">
                <input
                    type="checkbox"
                    className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    checked={isLoginEnabled || false}
                    onChange={(e) => {
                        setValue('is_login', e.target.checked, { shouldValidate: false });
                        if (!e.target.checked) {
                            setValue('password', '', { shouldValidate: false });
                        }
                    }}
                />
                <div className="flex items-center gap-2">
                    <Lock className="h-4 w-4 text-gray-500" />
                    <span className="text-sm font-medium text-gray-700">Allow Login Access</span>
                </div>
            </label>

            {isLoginEnabled && (
                <div className="duration-200 animate-in fade-in slide-in-from-top-2">
                    <FormField name="password" label="Password" type="password" placeholder="Enter password for login access" required />
                </div>
            )}
        </div>
    );
}

function CompanyFields({ currentLogoUrl }: { currentLogoUrl?: string }) {
    // Hooks
    const contactType = useWatch({ name: 'type' });

    if (String(contactType) !== '2') return null;

    return (
        <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
            <FormField type="file" name="logo" label="Company Logo" accept="image/*" currentUrl={currentLogoUrl || undefined} />
            <FormField type="url" name="website" label="Website" placeholder="https://example.com" />
            <FormField type="text" name="industry" label="Industry" placeholder="e.g., Technology, Finance" />
            <FormField type="text" name="company_size" label="Company Size" placeholder="50-100 employees" />
            <FormField type="text" name="yearly_revenue" label="Yearly Revenue" placeholder="$1M - $5M" />
            <FormField type="text" name="vat" label="VAT Number" placeholder="VAT123456" />
            <FormField type="text" name="tax_no" label="Tax Number" placeholder="TAX-123-456" />
            <FormField type="text" name="company_legal_name" label="Company Legal Name" placeholder="Acme Corporation Ltd." />
            <FormField
                type="select"
                name="time_zone"
                label="Time Zone"
                placeholder="Select timezone"
                options={[
                    { label: 'UTC', value: 'UTC' },
                    { label: 'America/New_York (EST)', value: 'America/New_York' },
                    { label: 'America/Los_Angeles (PST)', value: 'America/Los_Angeles' },
                    { label: 'Europe/London (GMT)', value: 'Europe/London' },
                    { label: 'Europe/Paris (CET)', value: 'Europe/Paris' },
                    { label: 'Asia/Tokyo (JST)', value: 'Asia/Tokyo' },
                    { label: 'Asia/Dubai (GST)', value: 'Asia/Dubai' },
                    { label: 'Asia/Dhaka (BST)', value: 'Asia/Dhaka' },
                    { label: 'Australia/Sydney (AEST)', value: 'Australia/Sydney' },
                ]}
            />
            <FormField type="url" name="company_linkedin" label="LinkedIn" placeholder="https://linkedin.com/company/..." />
            <FormField type="textarea" name="description" label="Description" placeholder="Company description..." className="md:col-span-3" />
        </div>
    );
}

function IndividualFields({ currentProfilePhotoUrl }: { currentProfilePhotoUrl?: string }) {
    // Hooks
    const contactType = useWatch({ name: 'type' });

    if (String(contactType) !== '1') return null;

    return (
        <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
            <FormField type="file" name="profile_photo" label="Profile Photo" accept="image/*" currentUrl={currentProfilePhotoUrl || undefined} />
            <FormField type="date" name="dob" label="Date of Birth" />
            <FormField
                type="select"
                name="gender"
                label="Gender"
                options={[
                    { label: 'Male', value: 'Male' },
                    { label: 'Female', value: 'Female' },
                    { label: 'Other', value: 'Other' },
                ]}
            />
            <FormField type="text" name="nid" label="National ID (NID)" placeholder="Enter NID number" />
            <FormField type="text" name="passport" label="Passport Number" placeholder="Enter passport number" />
            <FormField type="text" name="education" label="Education" placeholder="e.g., Bachelor's in Computer Science" />
            <FormField type="text" name="occupation" label="Occupation / Position" placeholder="e.g., Marketing Manager" />
            <FormField type="text" name="company" label="Current Company" placeholder="Company name" />
            <FormField type="text" name="business_name" label="Business Name (Optional)" placeholder="Business name if applicable" />
            <FormField
                type="select"
                name="preferred_contact_time"
                label="Preferred Contact Time"
                placeholder="Select preferred time"
                options={[
                    { label: 'Morning (9 AM – 12 PM)', value: 'morning' },
                    { label: 'Afternoon (12 PM – 4 PM)', value: 'afternoon' },
                    { label: 'Evening (4 PM – 8 PM)', value: 'evening' },
                    { label: 'Night (8 PM – 10 PM)', value: 'night' },
                    { label: 'Anytime', value: 'anytime' },
                ]}
            />
            <FormField
                type="select"
                name="preferred_contact_channels"
                label="Preferred Contact Channel"
                options={[
                    { label: 'Email', value: 'email' },
                    { label: 'Phone', value: 'phone' },
                    { label: 'SMS', value: 'sms' },
                    { label: 'WhatsApp', value: 'whatsapp' },
                    { label: 'Messenger', value: 'messenger' },
                ]}
            />
        </div>
    );
}

function ContactDetailsSection({ currentLogoUrl, currentProfilePhotoUrl }: { currentLogoUrl?: string; currentProfilePhotoUrl?: string }) {
    // Hooks
    const contactType = useWatch({ name: 'type' });

    // Derived state
    const isCompany = String(contactType) === '2';

    return (
        <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-purple-50/50 to-white p-6 shadow-sm">
            <div className="mb-5 flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-purple-500">
                    {isCompany ? <Building2 className="h-5 w-5 text-purple-500" /> : <User className="h-5 w-5 text-purple-500" />}
                </div>
                <div>
                    <h3 className="text-lg font-semibold text-gray-900">{isCompany ? 'Company Details' : 'Individual Details'}</h3>
                    <p className="text-sm text-gray-600">{isCompany ? 'Company-specific information' : 'Personal information'}</p>
                </div>
            </div>
            <CompanyFields currentLogoUrl={currentLogoUrl} />
            <IndividualFields currentProfilePhotoUrl={currentProfilePhotoUrl} />
        </div>
    );
}

function AddressSection() {
    // Hooks
    const { setValue, getValues } = useFormContext();

    // State
    const [sameAsBilling, setSameAsBilling] = useState(false);

    // Watch billing address fields
    const billingStreet = useWatch({ name: 'billing_address.street' });
    const billingCity = useWatch({ name: 'billing_address.city' });
    const billingState = useWatch({ name: 'billing_address.state' });
    const billingZip = useWatch({ name: 'billing_address.zip' });
    const billingCountry = useWatch({ name: 'billing_address.country' });

    // Effects
    useEffect(() => {
        if (sameAsBilling) {
            setValue('shipping_address.street', billingStreet || '');
            setValue('shipping_address.city', billingCity || '');
            setValue('shipping_address.state', billingState || '');
            setValue('shipping_address.zip', billingZip || '');
            setValue('shipping_address.country', billingCountry || '');
        }
    }, [sameAsBilling, billingStreet, billingCity, billingState, billingZip, billingCountry, setValue]);

    // Handlers
    const handleSameAsBillingChange = (checked: boolean | 'indeterminate') => {
        const isChecked = checked === true;
        setSameAsBilling(isChecked);

        if (isChecked) {
            const billing = getValues('billing_address');
            setValue('shipping_address.street', billing?.street || '');
            setValue('shipping_address.city', billing?.city || '');
            setValue('shipping_address.state', billing?.state || '');
            setValue('shipping_address.zip', billing?.zip || '');
            setValue('shipping_address.country', billing?.country || '');
        }
    };

    return (
        <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-indigo-50/50 to-white p-6 shadow-sm">
            <div className="mb-5 flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-indigo-500">
                    <MapPin className="h-5 w-5 text-indigo-500" />
                </div>
                <div>
                    <h3 className="text-lg font-semibold text-gray-900">Address Information</h3>
                    <p className="text-sm text-gray-600">Billing and shipping addresses</p>
                </div>
            </div>

            {/* Billing Address Section */}
            <div className="mb-6">
                <div className="mb-3 flex items-center gap-2">
                    <CreditCard className="h-4 w-4 text-indigo-500" />
                    <h4 className="font-medium text-gray-800">Billing Address</h4>
                </div>
                <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
                    <FormField type="text" name="billing_address.street" label="Street Address" placeholder="123 Main St" className="md:col-span-3" />
                    <FormField type="text" name="billing_address.city" label="City" placeholder="New York" />
                    <FormField type="text" name="billing_address.state" label="State/Province" placeholder="NY" />
                    <FormField type="text" name="billing_address.zip" label="ZIP/Postal Code" placeholder="10001" />
                    <FormField type="text" name="billing_address.country" label="Country" placeholder="United States" />
                </div>
            </div>

            {/* Divider with Checkbox */}
            <div className="mb-6 border-t border-gray-200 pt-4">
                <div className="flex items-center gap-2">
                    <Checkbox id="same-as-billing" checked={sameAsBilling} onCheckedChange={handleSameAsBillingChange} />
                    <Label htmlFor="same-as-billing" className="cursor-pointer text-sm font-medium text-gray-700">
                        Shipping address is the same as billing address
                    </Label>
                </div>
            </div>

            {/* Shipping Address Section */}
            <div className={sameAsBilling ? 'pointer-events-none opacity-50' : ''}>
                <div className="mb-3 flex items-center gap-2">
                    <MapPin className="h-4 w-4 text-teal-500" />
                    <h4 className="font-medium text-gray-800">Shipping Address</h4>
                </div>
                <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
                    <FormField
                        type="text"
                        name="shipping_address.street"
                        label="Street Address"
                        placeholder="123 Main St"
                        className="md:col-span-3"
                        disabled={sameAsBilling}
                    />
                    <FormField type="text" name="shipping_address.city" label="City" placeholder="New York" disabled={sameAsBilling} />
                    <FormField type="text" name="shipping_address.state" label="State/Province" placeholder="NY" disabled={sameAsBilling} />
                    <FormField type="text" name="shipping_address.zip" label="ZIP/Postal Code" placeholder="10001" disabled={sameAsBilling} />
                    <FormField type="text" name="shipping_address.country" label="Country" placeholder="United States" disabled={sameAsBilling} />
                </div>
            </div>
        </div>
    );
}

function ContactRelationsSection({ companyOptions, individualOptions, existingRelations = [] }: ContactRelationsSectionProps) {
    // Hooks
    const contactType = useWatch({ name: 'type' });
    const { setValue } = useFormContext();

    // State
    const [relations, setRelations] = useState<Array<{ id?: number; contact_id: string; level: string }>>(() => {
        if (existingRelations && existingRelations.length > 0) {
            return existingRelations.map((rel) => {
                // For individual_parent type, the related contact is company_id
                // For company_parent type, the related contact is contact_id (the individual)
                const relatedId = rel.type === 'individual_parent' ? String(rel.company_id || '') : String(rel.contact_id || '');

                return {
                    id: rel.id,
                    contact_id: relatedId,
                    level: rel.level || 'additional',
                };
            });
        }
        return [{ contact_id: '', level: 'additional' }];
    });

    // Effects
    useEffect(() => {
        setValue('relations', relations, { shouldDirty: true });
    }, [relations, setValue]);

    // Derived state
    const isCompanyContact = String(contactType) === '2';
    const baseContactOptions = isCompanyContact ? individualOptions : companyOptions;
    const relationLabel = isCompanyContact ? 'Individual Contact' : 'Company Contact';
    const relationDescription = isCompanyContact ? 'Link individuals to this company' : 'Link this individual to parent companies';

    // Helper functions
    const getAvailableOptions = (currentIndex: number) => {
        const selectedIds = relations
            .filter((_, i) => i !== currentIndex)
            .map((rel) => rel.contact_id)
            .filter((id) => id !== '');

        return baseContactOptions.filter((option) => !selectedIds.includes(option.value));
    };

    // Handlers
    const addRelation = () => {
        setRelations([...relations, { contact_id: '', level: 'additional' }]);
    };

    const removeRelation = (index: number) => {
        if (relations.length > 1) {
            setRelations(relations.filter((_, i) => i !== index));
        }
    };

    const updateRelation = (index: number, field: 'contact_id' | 'level', value: string) => {
        const updated = [...relations];

        if (field === 'level' && value === 'primary') {
            updated.forEach((rel, i) => {
                if (i !== index) {
                    rel.level = 'additional';
                }
            });
        }

        updated[index][field] = value;
        setRelations(updated);
    };

    return (
        <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-rose-50/50 to-white p-6 shadow-sm">
            <div className="mb-5 flex items-center justify-between">
                <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-rose-500">
                        <Link2 className="h-5 w-5 text-rose-500" />
                    </div>
                    <div>
                        <h3 className="text-lg font-semibold text-gray-900">Contact Relations</h3>
                        <p className="text-sm text-gray-600">{relationDescription}</p>
                    </div>
                </div>
                <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={addRelation}
                    className="flex items-center gap-1 border-rose-300 text-rose-600 hover:bg-rose-50"
                >
                    <Plus className="h-4 w-4" />
                    Add More
                </Button>
            </div>

            <div className="space-y-4">
                {relations.map((relation, index) => {
                    const availableOptions = getAvailableOptions(index);
                    return (
                        <div key={index} className="flex items-end gap-4">
                            <div className="flex-1">
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">{relationLabel}</label>
                                <select
                                    value={relation.contact_id}
                                    onChange={(e) => updateRelation(index, 'contact_id', e.target.value)}
                                    className="h-10 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-rose-500 focus:ring-1 focus:ring-rose-500 focus:outline-none"
                                >
                                    <option value="">Select {relationLabel.toLowerCase()}</option>
                                    {availableOptions.map((option) => (
                                        <option key={option.value} value={option.value}>
                                            {option.label}
                                        </option>
                                    ))}
                                </select>
                                <input type="hidden" name={`relations[${index}].contact_id`} value={relation.contact_id} />
                            </div>
                            <div className="flex-1">
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">Level</label>
                                <select
                                    value={relation.level}
                                    onChange={(e) => updateRelation(index, 'level', e.target.value)}
                                    className="h-10 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-rose-500 focus:ring-1 focus:ring-rose-500 focus:outline-none"
                                >
                                    <option value="primary">Primary</option>
                                    <option value="additional">Additional</option>
                                </select>
                                <input type="hidden" name={`relations[${index}].level`} value={relation.level} />
                            </div>
                            {relations.length > 1 && (
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => removeRelation(index)}
                                    className="h-10 w-10 text-red-500 hover:bg-red-50 hover:text-red-600"
                                >
                                    <Trash2 className="h-4 w-4" />
                                </Button>
                            )}
                        </div>
                    );
                })}
            </div>

            <input type="hidden" name="relation_type" value={isCompanyContact ? 'individual_parent' : 'company_parent'} />
        </div>
    );
}

function TagsInput() {
    // Hooks
    const { setValue, getValues } = useFormContext();

    // State
    const [inputValue, setInputValue] = useState('');
    const [tags, setTags] = useState<string[]>(() => {
        const existingTags = getValues('tags');
        if (Array.isArray(existingTags)) return existingTags;
        if (typeof existingTags === 'string' && existingTags)
            return existingTags
                .split(',')
                .map((t: string) => t.trim())
                .filter(Boolean);
        return [];
    });

    // Effects
    useEffect(() => {
        setValue('tags', tags);
    }, [tags, setValue]);

    // Handlers
    const addTag = () => {
        const trimmedValue = inputValue.trim().replace(/,/g, '');
        if (trimmedValue && !tags.includes(trimmedValue)) {
            setTags([...tags, trimmedValue]);
            setInputValue('');
        } else {
            setInputValue('');
        }
    };

    const removeTag = (index: number) => {
        setTags(tags.filter((_, i) => i !== index));
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === ',' || e.key === 'Enter') {
            e.preventDefault();
            addTag();
        } else if (e.key === 'Backspace' && inputValue === '' && tags.length > 0) {
            removeTag(tags.length - 1);
        }
    };

    const handleBlur = () => {
        if (inputValue.trim()) {
            addTag();
        }
    };

    return (
        <div className="space-y-1.5">
            <label className="block text-sm font-medium text-gray-700">Tags</label>
            <div className="flex min-h-[42px] flex-wrap items-center gap-2 rounded-lg border border-gray-300 bg-white px-3 py-2 shadow-sm focus-within:border-cyan-500 focus-within:ring-1 focus-within:ring-cyan-500">
                {tags.map((tag, index) => (
                    <span
                        key={index}
                        className="inline-flex items-center gap-1 rounded-full bg-cyan-100 px-2.5 py-0.5 text-sm font-medium text-cyan-800"
                    >
                        {tag}
                        <button
                            type="button"
                            onClick={() => removeTag(index)}
                            className="ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded-full text-cyan-600 hover:bg-cyan-200 hover:text-cyan-800"
                        >
                            <X className="h-3 w-3" />
                        </button>
                    </span>
                ))}
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyDown={handleKeyDown}
                    onBlur={handleBlur}
                    placeholder={tags.length === 0 ? 'Type and press comma to add tags' : ''}
                    className="min-w-[120px] flex-1 border-none bg-transparent text-sm outline-none placeholder:text-gray-400"
                />
            </div>
            <p className="text-xs text-gray-500">Press comma or Enter to add a tag</p>
            <input type="hidden" name="tags" value={JSON.stringify(tags)} />
        </div>
    );
}

// ============================================================================
// MAIN EDIT COMPONENT
// ============================================================================

function Edit() {
    const pageProps = usePage<EditContactPageProps>().props;
    const {
        contact,
        companyContacts = [],
        individualContacts = [],
        availableUsers = [],
        countries = {},
        currencies = [],
        languages = [],
        returnUrl,
    } = pageProps;
    const [isSubmitting, setIsSubmitting] = useState(false);
    const countryOptions = countries
        ? Object.entries(countries).map(([code, data]: [string, CountryData]) => ({
              label: `${data.flag} ${data.name}`,
              value: `${code}:${data.name}`,
          }))
        : [];

    const userOptions = availableUsers.map((user) => ({
        label: user.name,
        value: user.id.toString(),
    }));

    const companyOptions = companyContacts
        .filter((c) => c.id !== contact?.id)
        .map((company) => ({
            label: company.name,
            value: company.id.toString(),
        }));

    const individualOptions = individualContacts
        .filter((c) => c.id !== contact?.id)
        .map((individual) => ({
            label: individual.name,
            value: individual.id.toString(),
        }));

    // -------------------------------------------------------------------------
    // Handlers
    // -------------------------------------------------------------------------
    const handleEditSubmit: SubmitHandler<any> = async (data) => {
        console.log('=== FORM SUBMISSION DEBUG ===');
        console.log('Contact Edit Form Data:', data);
        setIsSubmitting(true);

        try {
            const updateRoute = route('contacts.update', contact.uid || contact.id);

            // Check if we have file uploads (logo or profile_photo)
            const hasFiles = data.logo instanceof File || data.profile_photo instanceof File;

            // Remove file fields if they are not actual File objects (i.e., they are existing URL strings)
            if (!(data.logo instanceof File)) {
                delete data.logo;
            }
            if (!(data.profile_photo instanceof File)) {
                delete data.profile_photo;
            }

            if (hasFiles) {
                // Use POST with _method for file uploads
                router.post(
                    updateRoute,
                    {
                        _method: 'PUT',
                        ...data,
                    },
                    {
                        forceFormData: true,
                        preserveScroll: false,
                        preserveState: false,
                        onSuccess: () => {
                            toast.success('Contact information updated successfully!');
                            router.visit(returnUrl || route('contacts.show', contact.uid || contact.id));
                        },
                        onError: (errors) => {
                            console.error('Update errors:', errors);

                            if (typeof errors === 'object' && errors !== null) {
                                const errorMessages = Object.values(errors).flat();
                                if (errorMessages.length > 0) {
                                    toast.error(errorMessages[0] as string);
                                    return;
                                }
                            }

                            toast.error('Failed to update contact. Please check the form and try again.');
                        },
                        onFinish: () => {
                            setIsSubmitting(false);
                        },
                    },
                );
            } else {
                // Use regular PUT for non-file updates
                router.put(updateRoute, data, {
                    preserveScroll: false,
                    preserveState: false,
                    onSuccess: () => {
                        toast.success('Contact information updated successfully!');
                        router.visit(returnUrl || route('contacts.show', contact.uid || contact.id));
                    },
                    onError: (errors) => {
                        console.error('Update errors:', errors);

                        if (typeof errors === 'object' && errors !== null) {
                            const errorMessages = Object.values(errors).flat();
                            if (errorMessages.length > 0) {
                                toast.error(errorMessages[0] as string);
                                return;
                            }
                        }

                        toast.error('Failed to update contact. Please check the form and try again.');
                    },
                    onFinish: () => {
                        setIsSubmitting(false);
                    },
                });
            }
        } catch (error) {
            console.error('Error updating contact:', error);
            toast.error('An unexpected error occurred');
            setIsSubmitting(false);
        }
    };

    const handleCancel = () => {
        router.visit(returnUrl || route('contacts.show', contact.uid || contact.id));
    };

    // -------------------------------------------------------------------------
    // Render
    // -------------------------------------------------------------------------
    return (
        <div className="p-4">
            <div className="mb-6 flex items-center justify-between">
                <div className="flex items-start gap-4">
                    <Button type="button" variant="outline" size="sm" onClick={handleCancel} className="mt-1 flex items-center gap-2">
                        <ArrowLeft className="h-4 w-4" />
                    </Button>
                    <div>
                        <h1 className="text-2xl font-bold text-primary">Edit Contact </h1>
                        <p className="text-sm text-secondary">Update the contact details below. Fields marked with * are required.</p>
                    </div>
                </div>
            </div>

            <div className="">
                <Form
                    submitHandler={handleEditSubmit}
                    defaultValues={{
                        // Contact table fields
                        name: contact.name || '',
                        contact_code: contact.contact_code || '',
                        primary_email: contact.primary_email || '',
                        is_login: contact.is_login || false,
                        primary_phone: contact.primary_phone || '',
                        category: contact.category ?? 1,
                        type: contact.type ?? 1,
                        status: contact.status ?? 1, // Use ?? to allow 0 (inactive) status
                        app_name: contact.app_name || 'main',
                        source: contact.source || '',
                        uid: contact.uid || '',

                        // Contact Details table fields
                        billing_address: contact.details?.billing_address || {},
                        shipping_address: contact.details?.shipping_address || {},
                        tags: contact.details?.tags || [],
                        country: contact.details?.country || '',
                        branch: contact.details?.branch || '',
                        level: contact.details?.level || 'General',
                        life_cycle_stage: contact.details?.life_cycle_stage || 'Lead',
                        contact_group: contact.details?.contact_group || '',
                        additional_country_code: contact.details?.additional_country_code || '',
                        additional_phone: contact.details?.additional_phone || '',
                        additional_email: contact.details?.additional_email || '',
                        currency: contact.details?.currency || '',
                        language: contact.details?.language || '',

                        // Company Contact Details fields (for type = 2)
                        logo: contact.company_details?.logo || '',
                        website: contact.company_details?.website || '',
                        industry: contact.company_details?.industry || '',
                        company_size: contact.company_details?.company_size || '',
                        yearly_revenue: contact.company_details?.yearly_revenue || '',
                        vat: contact.company_details?.vat || '',
                        tax_no: contact.company_details?.tax_no || '',
                        company_legal_name: contact.company_details?.company_legal_name || '',
                        time_zone: contact.company_details?.time_zone || '',
                        description: contact.company_details?.description || '',
                        company_linkedin: contact.company_details?.linkedin || '',

                        // Individual Contact Details fields (for type = 1)
                        profile_photo: contact.individual_details?.profile_photo || '',
                        dob: contact.individual_details?.dob || '',
                        nid: contact.individual_details?.nid || '',
                        passport: contact.individual_details?.passport || '',
                        education: contact.individual_details?.education || '',
                        occupation: contact.individual_details?.occupation || '',
                        company: contact.individual_details?.company || '',
                        business_name: contact.individual_details?.business_name || '',
                        gender: contact.individual_details?.gender || '',
                        preferred_contact_time: contact.individual_details?.preferred_contact_time || '',
                        preferred_contact_channels: contact.individual_details?.preferred_contact_channels || '',

                        // Assignment fields
                        assigned_users: contact.assigned_users?.map((user) => user.id.toString()) || [],
                        contact_owner: contact.manager?.id?.toString() || null,

                        // Relations
                        relations:
                            contact.relations?.map((rel) => ({
                                id: rel.id,
                                contact_id: String(rel.contact_id || rel.company_id || ''),
                                level: rel.level || 'additional',
                            })) || [],
                    }}
                    formClassNames="space-y-6"
                >
                    {/* Basic Information - contacts table */}
                    <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-blue-50/50 to-white p-6">
                        <div className="mb-5 flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-blue-500">
                                <User className="h-5 w-5 text-blue-500" />
                            </div>
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">Basic Information</h3>
                                <p className="text-sm text-gray-600">Primary contact details</p>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
                            <FormField type="text" name="name" label="Full Name" placeholder="John Doe" required />
                            <FormField type="text" name="contact_code" label="Contact Code" placeholder="Auto-generated" disabled />
                            <FormField type="text" name="uid" label="UID" placeholder="Auto-generated" disabled />
                            <FormField type="email" name="primary_email" label="Primary Email" placeholder="john@example.com" required />
                            <PhoneInputField name="primary_phone" label="Primary Phone" />
                            <LoginAccessField />
                        </div>
                    </div>

                    {/* Contact Classification - contacts table */}
                    <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-emerald-50/50 to-white p-6">
                        <div className="mb-5 flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-emerald-500">
                                <Tag className="h-5 w-5 text-emerald-500" />
                            </div>
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">Contact Classification</h3>
                                <p className="text-sm text-gray-600">Categorize and organize this contact</p>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
                            <FormField
                                type="select"
                                name="type"
                                label="Contact Type"
                                options={[
                                    { label: 'Individual', value: '1' },
                                    { label: 'Company', value: '2' },
                                ]}
                            />
                            <FormField
                                type="select"
                                name="category"
                                label="Category"
                                options={[
                                    { label: 'General', value: '1' },
                                    { label: 'Customer', value: '2' },
                                    { label: 'Supplier', value: '3' },
                                    { label: 'Partner', value: '4' },
                                ]}
                            />
                            <FormField
                                type="select"
                                name="status"
                                label="Status"
                                options={[
                                    { label: 'Active', value: '1' },
                                    { label: 'Inactive', value: '0' },
                                ]}
                            />
                            <FormField
                                type="select"
                                name="source"
                                label="Source"
                                options={[
                                    { label: 'Lead', value: 'lead' },
                                    { label: 'Direct', value: 'direct' },
                                    { label: 'Referral', value: 'referral' },
                                    { label: 'Official', value: 'official' },
                                    { label: 'Website', value: 'website' },
                                    { label: 'Facebook', value: 'facebook' },
                                ]}
                            />
                            <FormField
                                type="select"
                                name="app_name"
                                label="App Name"
                                options={[
                                    { label: 'Main', value: 'main' },
                                    { label: 'CRM', value: 'crm' },
                                    { label: 'Inventory', value: 'inventory' },
                                    { label: 'Productivity', value: 'productivity' },
                                ]}
                            />
                        </div>
                    </div>

                    {/* Contact Details - contact_details table */}
                    <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-cyan-50/50 to-white p-6">
                        <div className="mb-5 flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-cyan-500">
                                <FileText className="h-5 w-5 text-cyan-500" />
                            </div>
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">Contact Details</h3>
                                <p className="text-sm text-gray-600">Additional contact information</p>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
                            <FormField
                                type="select"
                                name="level"
                                label="Contact Level"
                                options={[
                                    { label: 'General', value: 'General' },
                                    { label: 'VIP', value: 'VIP' },
                                    { label: 'Special', value: 'Special' },
                                ]}
                            />
                            <FormField
                                type="select"
                                name="life_cycle_stage"
                                label="Life Cycle Stage"
                                options={[
                                    { label: 'Lead', value: 'Lead' },
                                    { label: 'Prospect', value: 'Prospect' },
                                    { label: 'Customer', value: 'Customer' },
                                    { label: 'Recurring Customer', value: 'Recurring_Customer' },
                                ]}
                            />
                            <FormField
                                type="select"
                                name="contact_group"
                                label="Contact Group"
                                options={[
                                    { label: 'Retail', value: 'Retail' },
                                    { label: 'Wholesale', value: 'Wholesale' },
                                    { label: 'Garments', value: 'Garments' },
                                    { label: 'Supplier', value: 'Supplier' },
                                ]}
                            />
                            <FormField type="select" name="country" label="Country" placeholder="Select country" options={countryOptions} />
                            <FormField type="text" name="branch" label="Branch" placeholder="Company branch" />
                            <FormField type="select" name="currency" label="Preferred Currency" placeholder="Select currency" options={currencies} />
                            <FormField type="select" name="language" label="Preferred Language" placeholder="Select language" options={languages} />
                            <TagsInput />
                        </div>
                    </div>

                    {/* Additional Contact Info */}
                    <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-orange-50/50 to-white p-6">
                        <div className="mb-5 flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-orange-500">
                                <Phone className="h-5 w-5 text-orange-500" />
                            </div>
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">Additional Contact Info</h3>
                                <p className="text-sm text-gray-600">Secondary contact details</p>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                            <PhoneInputField name="additional_phone" label="Additional Phone" />
                            <FormField type="email" name="additional_email" label="Additional Email" placeholder="alternate@example.com" />
                        </div>
                    </div>

                    {/* Combined Billing & Shipping Address */}
                    <AddressSection />

                    {/* Company/Individual Specific Fields */}
                    <ContactDetailsSection
                        currentLogoUrl={contact.company_details?.logo}
                        currentProfilePhotoUrl={contact.individual_details?.profile_photo}
                    />

                    {/* User Assignment */}
                    <div className="rounded-lg border border-gray-200 bg-gradient-to-br from-amber-50/50 to-white p-6 shadow-sm">
                        <div className="mb-5 flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-amber-500">
                                <Users className="h-5 w-5 text-amber-500" />
                            </div>
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900">Contact Assignment</h3>
                                <p className="text-sm text-gray-600">Assign users to manage this contact</p>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                            <FormField
                                type="multiselect"
                                name="assigned_users"
                                label="Assigned To"
                                placeholder="Select users to assign"
                                options={userOptions}
                            />
                            <FormField
                                type="select"
                                name="contact_owner"
                                label="Contact Owner"
                                placeholder="Select contact owner"
                                options={userOptions}
                            />
                        </div>
                    </div>

                    {/* Contact Relations */}
                    <ContactRelationsSection
                        companyOptions={companyOptions}
                        individualOptions={individualOptions}
                        existingRelations={contact.relations}
                    />

                    {/* Action Buttons */}
                    <div className="flex justify-end gap-3 border-t pt-6">
                        <Button type="button" variant="outline" onClick={handleCancel} disabled={isSubmitting} className="min-w-[120px]">
                            Cancel
                        </Button>
                        <Button type="submit" disabled={isSubmitting} className="min-w-[120px] bg-blue-600 hover:bg-blue-700">
                            {isSubmitting ? 'Saving...' : 'Save Changes'}
                        </Button>
                    </div>
                </Form>
            </div>
        </div>
    );
}

// ============================================================================
// LAYOUT & EXPORT
// ============================================================================

Edit.layout = (page: ReactNode) => {
    const breadcrumbs = [
        { title: 'Home', href: '/' },
        { title: 'Contacts', href: route('contacts.index') },
        { title: 'Edit Contact', href: '#' },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs} title="Edit Contact">
            {page}
        </AppLayout>
    );
};

export default Edit;
