'use client';

import { useState, useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { getDictionary } from '@/lib/i18n';
import { Card, CardBody, CardHeader, Button } from '@/components/ui';
import { FormField, FormInput, FormTextarea, FormError, FormSuccess } from '@/components/forms';

interface FormData {
  name: string;
  email: string;
  phone: string;
  subject: string;
  message: string;
}

export function ContactForm() {
  const pathname = usePathname();
  const locale = pathname.split('/')[1] || 'en';
  const [dict, setDict] = useState<any>({});
  const [formData, setFormData] = useState<FormData>({
    name: '',
    email: '',
    phone: '',
    subject: '',
    message: '',
  });
  
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [errors, setErrors] = useState<Partial<FormData>>({});

  // Load dictionary on component mount and when locale changes
  useEffect(() => {
    const loadDict = async () => {
      try {
        const loadedDict = await getDictionary(locale as 'en' | 'de');
        setDict(loadedDict);
      } catch (error) {
        console.error('Error loading dictionary:', error);
        // Set empty dictionary to prevent infinite loading
        setDict({});
      }
    };
    loadDict();
  }, [locale]);

  const t = (key: string): string => {
    if (!dict || Object.keys(dict).length === 0) return key;
    
    const keys = key.split('.');
    let value: any = dict;
    
    for (const k of keys) {
      value = value?.[k];
      if (value === undefined) return key;
    }
    
    return value || key;
  };

  const validateForm = (): boolean => {
    const newErrors: Partial<FormData> = {};
    
    if (!formData.name.trim()) {
      newErrors.name = t('contact.errors.nameRequired');
    }
    
    if (!formData.email.trim()) {
      newErrors.email = t('contact.errors.emailRequired');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = t('contact.errors.emailInvalid');
    }
    
    if (!formData.message.trim()) {
      newErrors.message = t('contact.errors.messageRequired');
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setStatus('loading');
    
    try {
      const response = await fetch(`/${locale}/api/contact`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formData,
          locale,
        }),
      });
      
      if (response.ok) {
        setStatus('success');
        setFormData({
          name: '',
          email: '',
          phone: '',
          subject: '',
          message: '',
        });
      } else {
        setStatus('error');
      }
    } catch (error) {
      console.error('Contact form error:', error);
      setStatus('error');
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
    
    // Clear error when user starts typing
    if (errors[name as keyof FormData]) {
      setErrors(prev => ({
        ...prev,
        [name]: undefined,
      }));
    }
  };

  return (
    <Card variant="elevated" padding="lg">
      <CardHeader
        title={t('contact.title')}
        subtitle={t('contact.subtitle')}
      />
      <CardBody>
        <FormSuccess message={status === 'success' ? t('contact.success') : undefined} />
        <FormError errors={status === 'error' ? t('contact.error') : undefined} />

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              name="name"
              label={t('contact.name')}
              required
              error={errors.name}
              type="text"
              value={formData.name}
              onChange={(value) => setFormData(prev => ({ ...prev, name: value }))}
              disabled={status === 'loading'}
              placeholder={t('contact.name')}
            />

            <FormField
              name="email"
              label={t('contact.email')}
              required
              error={errors.email}
              type="email"
              value={formData.email}
              onChange={(value) => setFormData(prev => ({ ...prev, email: value }))}
              disabled={status === 'loading'}
              placeholder={t('contact.email')}
            />
          </div>

          <FormField
            name="phone"
            label={t('contact.phone')}
            type="tel"
            value={formData.phone}
            onChange={(value) => setFormData(prev => ({ ...prev, phone: value }))}
            disabled={status === 'loading'}
            placeholder={t('contact.phone')}
          />

          <FormField
            name="subject"
            label={t('contact.subject')}
            type="text"
            value={formData.subject}
            onChange={(value) => setFormData(prev => ({ ...prev, subject: value }))}
            disabled={status === 'loading'}
            placeholder={t('contact.subject')}
          />

          <FormField
            name="message"
            label={t('contact.message')}
            required
            error={errors.message}
            type="textarea"
            value={formData.message}
            onChange={(value) => setFormData(prev => ({ ...prev, message: value }))}
            disabled={status === 'loading'}
            placeholder={t('contact.message')}
            rows={6}
          />
          
          <div className="flex items-center justify-between gap-4">
            <p className="text-sm text-gray-500">
              {t('contact.requiredFields')}
            </p>
            <Button
              type="submit"
              variant="primary"
              size="lg"
              loading={status === 'loading'}
              disabled={status === 'loading'}
            >
              {status === 'loading' ? t('contact.sending') : t('contact.submit')}
            </Button>
          </div>
        </form>
      </CardBody>
    </Card>
  );
}