'use client';

import { useState, useRef, FormEvent } from 'react';

// EmailJS configuration - Replace with your actual IDs
const EMAILJS_SERVICE_ID = 'YOUR_SERVICE_ID';
const EMAILJS_TEMPLATE_ID = 'YOUR_TEMPLATE_ID';
const EMAILJS_PUBLIC_KEY = 'YOUR_PUBLIC_KEY';

interface ContactFormData {
  name: string;
  email: string;
  subject: string;
  message: string;
}

interface FormStatus {
  type: 'idle' | 'loading' | 'success' | 'error';
  message: string;
}

export default function ContactForm() {
  const formRef = useRef<HTMLFormElement>(null);
  const [formData, setFormData] = useState<ContactFormData>({
    name: '',
    email: '',
    subject: '',
    message: ''
  });
  const [status, setStatus] = useState<FormStatus>({ type: 'idle', message: '' });

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

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    
    // Validation
    if (!formData.name || !formData.email || !formData.message) {
      setStatus({ type: 'error', message: 'Lütfen tüm zorunlu alanları doldurun.' });
      return;
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      setStatus({ type: 'error', message: 'Geçerli bir e-posta adresi girin.' });
      return;
    }

    setStatus({ type: 'loading', message: 'Gönderiliyor...' });

    try {
      // Dynamic import for EmailJS to reduce bundle size
      const emailjs = await import('@emailjs/browser');
      
      await emailjs.sendForm(
        EMAILJS_SERVICE_ID,
        EMAILJS_TEMPLATE_ID,
        formRef.current!,
        EMAILJS_PUBLIC_KEY
      );

      setStatus({ type: 'success', message: 'Mesajınız başarıyla gönderildi! En kısa sürede dönüş yapacağız.' });
      setFormData({ name: '', email: '', subject: '', message: '' });
    } catch (error) {
      console.error('EmailJS Error:', error);
      setStatus({ 
        type: 'error', 
        message: 'Mesaj gönderilemedi. Lütfen daha sonra tekrar deneyin veya doğrudan e-posta gönderin.' 
      });
    }
  };

  const subjects = [
    'Web Geliştirme',
    'Mobil Uygulama',
    'Yapay Zeka Çözümleri',
    'Blockchain & Web3',
    'Danışmanlık',
    'Diğer'
  ];

  return (
    <form ref={formRef} onSubmit={handleSubmit} className="space-y-6">
      {/* Name Field */}
      <div>
        <label htmlFor="name" className="block text-sm font-mono text-slate-400 mb-2">
          İsim <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          placeholder="Adınız Soyadınız"
          className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder:text-slate-600 focus:outline-none focus:border-zsl-primary/50 focus:ring-1 focus:ring-zsl-primary/50 transition-all font-mono text-sm"
          disabled={status.type === 'loading'}
        />
      </div>

      {/* Email Field */}
      <div>
        <label htmlFor="email" className="block text-sm font-mono text-slate-400 mb-2">
          E-posta <span className="text-red-400">*</span>
        </label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          placeholder="ornek@email.com"
          className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder:text-slate-600 focus:outline-none focus:border-zsl-primary/50 focus:ring-1 focus:ring-zsl-primary/50 transition-all font-mono text-sm"
          disabled={status.type === 'loading'}
        />
      </div>

      {/* Subject Field */}
      <div>
        <label htmlFor="subject" className="block text-sm font-mono text-slate-400 mb-2">
          Konu
        </label>
        <select
          id="subject"
          name="subject"
          value={formData.subject}
          onChange={handleChange}
          className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white focus:outline-none focus:border-zsl-primary/50 focus:ring-1 focus:ring-zsl-primary/50 transition-all font-mono text-sm appearance-none cursor-pointer"
          disabled={status.type === 'loading'}
        >
          <option value="" className="bg-[#0a0f1a]">Konu Seçin</option>
          {subjects.map((subj) => (
            <option key={subj} value={subj} className="bg-[#0a0f1a]">
              {subj}
            </option>
          ))}
        </select>
      </div>

      {/* Message Field */}
      <div>
        <label htmlFor="message" className="block text-sm font-mono text-slate-400 mb-2">
          Mesaj <span className="text-red-400">*</span>
        </label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          placeholder="Projeniz hakkında detayları paylaşın..."
          rows={5}
          className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder:text-slate-600 focus:outline-none focus:border-zsl-primary/50 focus:ring-1 focus:ring-zsl-primary/50 transition-all font-mono text-sm resize-none"
          disabled={status.type === 'loading'}
        />
      </div>

      {/* Status Message */}
      {status.type !== 'idle' && (
        <div className={`p-4 rounded-lg border font-mono text-sm ${
          status.type === 'success' 
            ? 'bg-green-500/10 border-green-500/30 text-green-400' 
            : status.type === 'error'
            ? 'bg-red-500/10 border-red-500/30 text-red-400'
            : 'bg-zsl-primary/10 border-zsl-primary/30 text-zsl-primary'
        }`}>
          <div className="flex items-center gap-2">
            {status.type === 'loading' && (
              <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            )}
            {status.type === 'success' && (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            )}
            {status.type === 'error' && (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            )}
            {status.message}
          </div>
        </div>
      )}

      {/* Submit Button */}
      <button
        type="submit"
        disabled={status.type === 'loading'}
        className="w-full group relative overflow-hidden bg-linear-to-r from-zsl-primary to-cyan-400 text-black font-mono font-bold py-4 px-6 rounded-lg transition-all duration-300 hover:shadow-[0_0_30px_rgba(0,212,255,0.4)] disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <span className="relative z-10 flex items-center justify-center gap-2">
          {status.type === 'loading' ? (
            <>
              <svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              GÖNDERİLİYOR...
            </>
          ) : (
            <>
              MESAJ GÖNDER
              <svg className="w-5 h-5 group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
              </svg>
            </>
          )}
        </span>
        <div className="absolute inset-0 bg-linear-to-r from-cyan-400 to-zsl-primary opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
      </button>

      {/* Privacy Note */}
      <p className="text-xs text-slate-600 font-mono text-center">
        Formu göndererek <span className="text-slate-500">Gizlilik Politikamızı</span> kabul etmiş olursunuz.
      </p>
    </form>
  );
}
