import { useState } from 'react';
import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles';

interface ContactFormSectionProps {
    id: string;
    layout?: string;
    colorScheme?: string;
    title?: string;
    webhook_url?: string;
    redirect_url?: string;
    fields?: string[];
    elementStyles?: Record<string, any>;
}

export function ContactFormSection({
    id,
    layout = 'default',
    colorScheme = 'default',
    title,
    webhook_url,
    redirect_url,
    fields = ['name', 'email', 'message'],
    elementStyles,
    styles,
}: ContactFormSectionProps & { styles?: Record<string, any> }) {
    const heightMap: Record<string, string> = {
        'default': 'py-12 md:py-20',
        'small': 'py-8 md:py-12',
        'medium': 'py-16 md:py-24',
        'large': 'py-24 md:py-36',
        'fullscreen': 'min-h-screen flex flex-col justify-center',
    };
    const customPadding = styles?.paddingTop || styles?.paddingBottom;
    const heightClasses = customPadding ? '' : (heightMap[styles?.heightPreset || 'default'] || 'py-12 md:py-20');
    const [formData, setFormData] = useState<Record<string, string>>({});

    // Helper to get text styles (including font family)
    const getTextStyles = (elementName: string) => {
        const styles = elementStyles?.[elementName] || {};
        return {
            classNames: cn(
                styles.fontSize,
                styles.fontWeight,
                {
                    'font-sans': styles.fontFamily === 'secondary',
                    'font-serif': styles.fontFamily === 'primary',
                }
            ),
            style: {
                color: styles.color,
                textAlign: styles.textAlign,
                backgroundColor: styles.backgroundColor,
                borderColor: styles.borderColor,
                borderWidth: styles.borderWidth,
                borderRadius: styles.borderRadius,
            }
        };
    };

    const titleStyle = getTextStyles('title');
    const buttonStyle = getTextStyles('button');
    const fieldsStyle = getTextStyles('fields');
    const [submitting, setSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSubmitting(true);
        setError(null);

        try {
            // Submit to webhook if provided
            if (webhook_url) {
                await fetch(webhook_url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData),
                });
            }

            // Redirect after submission
            if (redirect_url) {
                // Replace placeholders in redirect URL
                let finalUrl = redirect_url;
                Object.entries(formData).forEach(([key, value]) => {
                    finalUrl = finalUrl.replace(`{${key}}`, encodeURIComponent(value));
                });
                window.location.href = finalUrl;
            }
        } catch (err) {
            setError('Failed to submit form. Please try again.');
        } finally {
            setSubmitting(false);
        }
    }; const hasCustomBackground = !!styles?.backgroundColor || !!styles?.backgroundImage || styles?.backgroundType === 'gradient';
    const sectionBg = getSectionBackground(styles);

    // Helper to get background style for dynamic schemes
    const getBackgroundStyle = (): React.CSSProperties | undefined => {
        if (hasCustomBackground) return sectionBg.style;
        if (colorScheme === 'primary') {
            return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
        }
        if (colorScheme === 'secondary') {
            return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
        }
        return undefined;
    };

    return (
        <section
            id={id}
            className={cn(
                'wn-section wn-contact-form',
                `wn-scheme--${colorScheme}`,
                heightClasses,
                {
                    'bg-muted': colorScheme === 'muted' && !hasCustomBackground,
                }
            )}
            style={getBackgroundStyle()}
        >
            <div className={cn(
                "mx-auto px-4",
                styles?.contentWidth === 'full' ? 'w-full'
                    : styles?.contentWidth === 'boxed' ? 'max-w-5xl'
                        : 'container'
            )}>
                <div className={cn(
                    'max-w-xl mx-auto',
                    {
                        'max-w-2xl': layout === 'wide',
                    }
                )}>
                    {title && (
                        <h2 className={cn(
                            "wn-contact__title text-center mb-12",
                            !elementStyles?.title?.fontSize && "text-3xl md:text-4xl lg:text-5xl",
                            !elementStyles?.title?.fontWeight && "font-bold",
                            titleStyle.classNames
                        )}
                            style={titleStyle.style}
                        >
                            {title}
                        </h2>
                    )}

                    <form onSubmit={handleSubmit} className="space-y-6">
                        {fields.map((field) => {
                            const fieldLabel = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                            const isTextarea = field === 'message' || field === 'content';

                            return (
                                <div key={field} className="wn-contact-form__field">
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        {fieldLabel}
                                    </label>
                                    {isTextarea ? (
                                        <textarea
                                            name={field}
                                            value={formData[field] || ''}
                                            onChange={handleChange}
                                            rows={5}
                                            className={cn(
                                                "w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary",
                                                fieldsStyle.classNames
                                            )}
                                            style={{
                                                backgroundColor: fieldsStyle.style?.backgroundColor,
                                                color: fieldsStyle.style?.color,
                                                borderColor: fieldsStyle.style?.borderColor,
                                                borderRadius: fieldsStyle.style?.borderRadius,
                                            }}
                                            placeholder={`Enter your ${fieldLabel.toLowerCase()}`}
                                            required
                                        />
                                    ) : (
                                        <input
                                            type={field === 'email' ? 'email' : 'text'}
                                            name={field}
                                            value={formData[field] || ''}
                                            onChange={handleChange}
                                            className={cn(
                                                "w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary",
                                                fieldsStyle.classNames
                                            )}
                                            style={{
                                                backgroundColor: fieldsStyle.style?.backgroundColor,
                                                color: fieldsStyle.style?.color,
                                                borderColor: fieldsStyle.style?.borderColor,
                                                borderRadius: fieldsStyle.style?.borderRadius,
                                            }}
                                            placeholder={`Enter your ${fieldLabel.toLowerCase()}`}
                                            required
                                        />
                                    )}
                                </div>
                            );
                        })}

                        {error && (
                            <div className="text-red-500 text-sm">{error}</div>
                        )}

                        <button
                            type="submit"
                            disabled={submitting}
                            className={cn(
                                'w-full py-3 px-6 rounded-lg font-semibold',
                                'hover:opacity-90 transition-colors',
                                'disabled:opacity-50 disabled:cursor-not-allowed',
                                !buttonStyle.style?.backgroundColor && 'bg-primary',
                                !buttonStyle.style?.color && 'text-primary-foreground',
                                buttonStyle.classNames
                            )}
                            style={buttonStyle.style}
                        >
                            {submitting ? 'Sending...' : 'Submit'}
                        </button>
                    </form>
                </div>
            </div>
        </section>
    );
}
