---
import type { Form, FormField } from '@/types/schema';

interface Props {
  form_id?: string;
  title?: string;
  subtitle?: string;
  fields?: FormField[];
  button_text?: string;
  success_message?: string;
  style?: 'default' | 'card' | 'inline';
}

const { 
  form_id,
  title, 
  subtitle,
  fields = [
    { name: 'name', label: 'Your Name', type: 'text', required: true },
    { name: 'email', label: 'Email Address', type: 'email', required: true },
    { name: 'phone', label: 'Phone Number', type: 'phone', required: false },
    { name: 'message', label: 'Message', type: 'textarea', required: false }
  ],
  button_text = 'Submit',
  success_message = 'Thank you! We\'ll be in touch soon.',
  style = 'card'
} = Astro.props;

const formId = form_id || `form-${Math.random().toString(36).substr(2, 9)}`;
---

<section class={`max-w-2xl mx-auto px-6 py-12 ${style === 'card' ? '' : ''}`}>
  <div class={style === 'card' ? 'bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8' : ''}>
    {(title || subtitle) && (
      <div class="text-center mb-8">
        {title && (
          <h2 class="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white mb-2">
            {title}
          </h2>
        )}
        {subtitle && (
          <p class="text-gray-600 dark:text-gray-400">
            {subtitle}
          </p>
        )}
      </div>
    )}
    
    <form id={formId} class="space-y-6" data-success-message={success_message}>
      {fields.map((field) => (
        <div>
          <label 
            for={`${formId}-${field.name}`}
            class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
          >
            {field.label}
            {field.required && <span class="text-red-500 ml-1">*</span>}
          </label>
          
          {field.type === 'textarea' ? (
            <textarea
              id={`${formId}-${field.name}`}
              name={field.name}
              required={field.required}
              placeholder={field.placeholder}
              rows={4}
              class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-transparent transition-colors"
            />
          ) : field.type === 'select' && field.options ? (
            <select
              id={`${formId}-${field.name}`}
              name={field.name}
              required={field.required}
              class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-transparent transition-colors"
            >
              <option value="">Select an option</option>
              {field.options.map((option) => (
                <option value={option}>{option}</option>
              ))}
            </select>
          ) : field.type === 'checkbox' ? (
            <div class="flex items-center">
              <input
                type="checkbox"
                id={`${formId}-${field.name}`}
                name={field.name}
                required={field.required}
                class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary"
              />
              <label for={`${formId}-${field.name}`} class="ml-2 text-sm text-gray-600 dark:text-gray-400">
                {field.placeholder || field.label}
              </label>
            </div>
          ) : (
            <input
              type={field.type}
              id={`${formId}-${field.name}`}
              name={field.name}
              required={field.required}
              placeholder={field.placeholder}
              class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary focus:border-transparent transition-colors"
            />
          )}
        </div>
      ))}
      
      <button
        type="submit"
        class="w-full px-6 py-4 bg-gradient-to-r from-primary to-purple-600 text-white rounded-lg font-semibold text-lg shadow-lg hover:shadow-xl hover:scale-[1.02] transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <span class="submit-text">{button_text}</span>
        <span class="loading-text hidden">Submitting...</span>
      </button>
    </form>
    
    <div id={`${formId}-success`} class="hidden text-center py-8">
      <div class="w-16 h-16 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-4">
        <svg class="w-8 h-8 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
        </svg>
      </div>
      <p class="text-lg font-semibold text-gray-900 dark:text-white">{success_message}</p>
    </div>
  </div>
</section>

<script>
  document.querySelectorAll('form[id^="form-"]').forEach(form => {
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const formEl = e.target as HTMLFormElement;
      const formId = formEl.id;
      const submitBtn = formEl.querySelector('button[type="submit"]') as HTMLButtonElement;
      const submitText = submitBtn.querySelector('.submit-text');
      const loadingText = submitBtn.querySelector('.loading-text');
      
      // Show loading state
      submitBtn.disabled = true;
      submitText?.classList.add('hidden');
      loadingText?.classList.remove('hidden');
      
      try {
        const formData = new FormData(formEl);
        const data = Object.fromEntries(formData.entries());
        
        const response = await fetch('/api/lead', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        
        if (response.ok) {
          formEl.classList.add('hidden');
          document.getElementById(`${formId}-success`)?.classList.remove('hidden');
        }
      } catch (err) {
        console.error('Form submission error:', err);
      } finally {
        submitBtn.disabled = false;
        submitText?.classList.remove('hidden');
        loadingText?.classList.add('hidden');
      }
    });
  });
</script>
