import React, { useState } from 'react';
import type { ComponentConfig } from '@measured/puck';
import type { ContactFormProps } from '../../types';
import { Send, Loader2, CheckCircle, AlertCircle } from 'lucide-react';
import api from '../../../api/client';

const ContactFormRender: React.FC<ContactFormProps> = ({
  heading,
  subheading,
  submitButtonText,
  successMessage,
  showPhone,
  showSubject,
  subjectOptions,
  padding = 'large',
  backgroundVariant = 'white',
  contentMaxWidth = '640px',
  anchorId,
}) => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    subject: '',
    message: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitError, setSubmitError] = useState<string | null>(null);

  // Honeypot field for spam prevention
  const [honeypot, setHoneypot] = useState('');

  const paddingClasses: Record<string, string> = {
    none: 'py-0',
    small: 'py-8',
    medium: 'py-12',
    large: 'py-16 md:py-20',
    xlarge: 'py-20 md:py-28',
  };

  const backgroundClasses: Record<string, string> = {
    white: 'bg-white',
    light: 'bg-neutral-50',
    dark: 'bg-neutral-900 text-white',
    'gradient-primary': 'bg-gradient-to-br from-primary-600 to-primary-800 text-white',
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = 'Name is required';
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        newErrors.email = 'Please enter a valid email address';
      }
    }

    if (!formData.message.trim()) {
      newErrors.message = 'Message is required';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    // Honeypot check
    if (honeypot) {
      return;
    }

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);

    try {
      const payload = {
        name: formData.name,
        email: formData.email,
        phone: formData.phone || undefined,
        subject: formData.subject || 'Contact Form Submission',
        message: formData.message,
      };

      await api.post('/public/contact/', payload);
      setIsSubmitted(true);
    } catch (error: any) {
      console.error('Form submission error:', error);
      const errorMessage = error?.response?.data?.error || 'Failed to send message. Please try again.';
      setSubmitError(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  const isDark = backgroundVariant === 'dark' || backgroundVariant === 'gradient-primary';
  const inputClasses = isDark
    ? 'bg-white/10 border-white/20 text-white placeholder-white/50 focus:ring-white/50'
    : 'bg-white border-neutral-300 text-neutral-900 focus:ring-primary-500';
  const labelClasses = isDark ? 'text-white/90' : 'text-neutral-700';
  const errorClasses = isDark ? 'text-red-300' : 'text-red-500';

  if (isSubmitted) {
    return (
      <section
        id={anchorId}
        className={`${paddingClasses[padding] || paddingClasses.large} ${backgroundClasses[backgroundVariant] || backgroundClasses.white}`}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div style={{ maxWidth: contentMaxWidth }} className="mx-auto">
            <div className={`rounded-xl p-8 text-center ${isDark ? 'bg-white/10' : 'bg-green-50 border border-green-200'}`}>
              <CheckCircle className={`w-12 h-12 mx-auto mb-4 ${isDark ? 'text-green-400' : 'text-green-500'}`} />
              <p className={`text-lg ${isDark ? 'text-white' : 'text-green-700'}`}>
                {successMessage}
              </p>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section
      id={anchorId}
      className={`${paddingClasses[padding] || paddingClasses.large} ${backgroundClasses[backgroundVariant] || backgroundClasses.white}`}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div style={{ maxWidth: contentMaxWidth }} className="mx-auto">
          {/* Header */}
          {(heading || subheading) && (
            <div className="text-center mb-10">
              {heading && (
                <h2 className={`text-3xl md:text-4xl font-bold mb-4 ${isDark ? 'text-white' : 'text-neutral-900'}`}>
                  {heading}
                </h2>
              )}
              {subheading && (
                <p className={`text-lg ${isDark ? 'text-white/80' : 'text-neutral-600'}`}>
                  {subheading}
                </p>
              )}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Honeypot field - hidden from users */}
            <input
              type="text"
              name="website"
              value={honeypot}
              onChange={(e) => setHoneypot(e.target.value)}
              tabIndex={-1}
              autoComplete="off"
              style={{ position: 'absolute', left: '-9999px' }}
              aria-hidden="true"
            />

            {/* Name */}
            <div>
              <label htmlFor="support-name" className={`block text-sm font-medium mb-2 ${labelClasses}`}>
                Name <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                id="support-name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:outline-none transition-colors ${inputClasses} ${errors.name ? 'border-red-500' : ''}`}
                placeholder="Your name"
              />
              {errors.name && <p className={`mt-1 text-sm ${errorClasses}`}>{errors.name}</p>}
            </div>

            {/* Email */}
            <div>
              <label htmlFor="support-email" className={`block text-sm font-medium mb-2 ${labelClasses}`}>
                Email <span className="text-red-500">*</span>
              </label>
              <input
                type="email"
                id="support-email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:outline-none transition-colors ${inputClasses} ${errors.email ? 'border-red-500' : ''}`}
                placeholder="your@email.com"
              />
              {errors.email && <p className={`mt-1 text-sm ${errorClasses}`}>{errors.email}</p>}
            </div>

            {/* Phone (optional) */}
            {showPhone && (
              <div>
                <label htmlFor="support-phone" className={`block text-sm font-medium mb-2 ${labelClasses}`}>
                  Phone
                </label>
                <input
                  type="tel"
                  id="support-phone"
                  value={formData.phone}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:outline-none transition-colors ${inputClasses}`}
                  placeholder="(555) 123-4567"
                />
              </div>
            )}

            {/* Subject */}
            {showSubject && (
              <div>
                <label htmlFor="support-subject" className={`block text-sm font-medium mb-2 ${labelClasses}`}>
                  Subject
                </label>
                {subjectOptions && subjectOptions.length > 0 ? (
                  <select
                    id="support-subject"
                    value={formData.subject}
                    onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                    className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:outline-none transition-colors ${inputClasses}`}
                  >
                    <option value="">Select a topic...</option>
                    {subjectOptions.map((option, index) => (
                      <option key={index} value={option}>{option}</option>
                    ))}
                  </select>
                ) : (
                  <input
                    type="text"
                    id="support-subject"
                    value={formData.subject}
                    onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                    className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:outline-none transition-colors ${inputClasses}`}
                    placeholder="What is this about?"
                  />
                )}
              </div>
            )}

            {/* Message */}
            <div>
              <label htmlFor="support-message" className={`block text-sm font-medium mb-2 ${labelClasses}`}>
                Message <span className="text-red-500">*</span>
              </label>
              <textarea
                id="support-message"
                rows={5}
                value={formData.message}
                onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:outline-none transition-colors resize-none ${inputClasses} ${errors.message ? 'border-red-500' : ''}`}
                placeholder="How can we help you?"
              />
              {errors.message && <p className={`mt-1 text-sm ${errorClasses}`}>{errors.message}</p>}
            </div>

            {/* Error Message */}
            {submitError && (
              <div className={`flex items-center gap-2 p-4 rounded-lg ${isDark ? 'bg-red-500/20 text-red-200' : 'bg-red-50 border border-red-200 text-red-700'}`}>
                <AlertCircle className="w-5 h-5 flex-shrink-0" />
                <p className="text-sm">{submitError}</p>
              </div>
            )}

            {/* Submit Button */}
            <button
              type="submit"
              disabled={isSubmitting}
              className={`w-full sm:w-auto px-8 py-3 rounded-lg font-medium flex items-center justify-center gap-2 transition-colors disabled:opacity-50 ${
                isDark
                  ? 'bg-white text-neutral-900 hover:bg-neutral-100'
                  : 'bg-primary-600 text-white hover:bg-primary-700'
              }`}
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Sending...
                </>
              ) : (
                <>
                  <Send className="w-5 h-5" />
                  {submitButtonText}
                </>
              )}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
};

export const ContactForm: ComponentConfig<ContactFormProps> = {
  label: 'Contact Form',
  fields: {
    heading: {
      type: 'text',
      label: 'Heading',
    },
    subheading: {
      type: 'text',
      label: 'Subheading',
    },
    submitButtonText: {
      type: 'text',
      label: 'Submit Button Text',
    },
    successMessage: {
      type: 'textarea',
      label: 'Success Message',
    },
    showPhone: {
      type: 'radio',
      label: 'Show Phone Field',
      options: [
        { label: 'No', value: false },
        { label: 'Yes', value: true },
      ],
    },
    showSubject: {
      type: 'radio',
      label: 'Show Subject Field',
      options: [
        { label: 'No', value: false },
        { label: 'Yes', value: true },
      ],
    },
    subjectOptions: {
      type: 'array',
      label: 'Subject Options (leave empty for free text)',
      arrayFields: {
        value: { type: 'text' },
      },
      getItemSummary: (item: any) => item.value || 'Option',
    },
    padding: {
      type: 'select',
      label: 'Padding',
      options: [
        { label: 'None', value: 'none' },
        { label: 'Small', value: 'small' },
        { label: 'Medium', value: 'medium' },
        { label: 'Large', value: 'large' },
        { label: 'Extra Large', value: 'xlarge' },
      ],
    },
    backgroundVariant: {
      type: 'select',
      label: 'Background',
      options: [
        { label: 'White', value: 'white' },
        { label: 'Light Gray', value: 'light' },
        { label: 'Dark', value: 'dark' },
        { label: 'Primary Gradient', value: 'gradient-primary' },
      ],
    },
    contentMaxWidth: {
      type: 'text',
      label: 'Max Width',
    },
    anchorId: {
      type: 'text',
      label: 'Anchor ID (for linking)',
    },
  },
  defaultProps: {
    heading: 'Get in Touch',
    subheading: "Have a question or need help? We'd love to hear from you.",
    submitButtonText: 'Send Message',
    successMessage: "Thank you for your message! We'll get back to you as soon as possible.",
    showPhone: true,
    showSubject: true,
    subjectOptions: [],
    padding: 'large',
    backgroundVariant: 'white',
    contentMaxWidth: '640px',
  },
  render: ContactFormRender,
};

export default ContactForm;
