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

interface ContactFormSectionProps {
    id: string;
    layout?: string;
    colorScheme?: string;
    title?: string;
    webhook_url?: string;
    redirect_url?: string;
    fields?: string[];
}

export function ContactFormSection({
    id,
    layout = 'default',
    colorScheme = 'default',
    title,
    webhook_url,
    redirect_url,
    fields = ['name', 'email', 'message'],
}: ContactFormSectionProps) {
    const [formData, setFormData] = useState<Record<string, string>>({});
    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);
        }
    };

    return (
        <section
            id={id}
            className={cn(
                'wn-section wn-contact-form',
                `wn-scheme--${colorScheme}`,
                'py-16 md:py-20',
                {
                    'bg-white': colorScheme === 'default',
                    'bg-muted': colorScheme === 'muted',
                }
            )}
        >
            <div className="container mx-auto px-4">
                <div className={cn(
                    'max-w-xl mx-auto',
                    {
                        'max-w-2xl': layout === 'wide',
                    }
                )}>
                    {title && (
                        <h2 className="wn-contact-form__title text-3xl font-bold text-center mb-8">
                            {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="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary"
                                            placeholder={`Enter your ${fieldLabel.toLowerCase()}`}
                                            required
                                        />
                                    ) : (
                                        <input
                                            type={field === 'email' ? 'email' : 'text'}
                                            name={field}
                                            value={formData[field] || ''}
                                            onChange={handleChange}
                                            className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary"
                                            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 bg-primary text-primary-foreground rounded-lg font-semibold',
                                'hover:bg-primary/90 transition-colors',
                                'disabled:opacity-50 disabled:cursor-not-allowed'
                            )}
                        >
                            {submitting ? 'Sending...' : 'Submit'}
                        </button>
                    </form>
                </div>
            </div>
        </section>
    );
}
