'use client'

import { useState } from 'react'
import { motion } from 'framer-motion'
import { Container } from '../ui/Container'
import { Button } from '../ui/Button'
import { cn } from '@/lib/utils'

interface ContactFormBlockProps {
  block: Record<string, unknown>
}

export function ContactFormBlock({ block }: ContactFormBlockProps) {
  const title = (block.title as string) || (block.headline as string) || 'Kontakt'
  const subtitle = (block.subtitle as string) || 'Haben Sie Fragen? Schreiben Sie mir.'
  const [status, setStatus] = useState<'idle' | 'sending' | 'success' | 'error'>('idle')

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setStatus('sending')

    try {
      const formData = new FormData(e.currentTarget)
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formData.get('name'),
          email: formData.get('email'),
          subject: formData.get('subject'),
          message: formData.get('message'),
        }),
      })

      if (response.ok) {
        setStatus('success')
      } else {
        setStatus('error')
      }
    } catch {
      setStatus('error')
    }
  }

  const inputClasses = cn(
    'w-full h-[40px] px-0',
    'border-0 border-b border-gray-light',
    'bg-transparent',
    'font-body text-[14px] tracking-[0.2px] text-dark',
    'transition-colors duration-300',
    'focus:outline-none focus:border-dark',
    'placeholder:text-gray-light'
  )

  return (
    <section className="bg-light-bg">
      <Container>
        <motion.div
          className={cn(
            'my-ws-l mx-auto max-w-3xl',
            'py-ws-l px-8 md:px-[100px] pb-ws-m',
            'border-t border-light-soft',
            'bg-white',
            'shadow-card'
          )}
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6 }}
        >
          {/* Header */}
          <header className="text-center mb-ws-m">
            <h2 className="font-heading font-bold text-[1.5em] tracking-[4px] uppercase text-dark mt-0 mb-[30px]">
              {title}
            </h2>
            <p className="text-gray-light">{subtitle}</p>
          </header>

          {/* Success Message */}
          {status === 'success' && (
            <div className="bg-success/10 border border-success text-success p-4 mb-8 text-center">
              Vielen Dank! Ich werde mich schnellstmöglich bei Ihnen melden.
            </div>
          )}

          {/* Error Message */}
          {status === 'error' && (
            <div className="bg-error/10 border border-error text-error p-4 mb-8 text-center">
              Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-8">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div>
                <input
                  type="text"
                  name="name"
                  placeholder="Name"
                  required
                  className={inputClasses}
                />
              </div>
              <div>
                <input
                  type="email"
                  name="email"
                  placeholder="E-Mail"
                  required
                  className={inputClasses}
                />
              </div>
            </div>

            <div>
              <input
                type="text"
                name="subject"
                placeholder="Betreff"
                required
                className={inputClasses}
              />
            </div>

            <div>
              <textarea
                name="message"
                placeholder="Nachricht"
                required
                rows={5}
                className={cn(
                  inputClasses,
                  'h-auto min-h-[120px] resize-none py-2'
                )}
              />
            </div>

            <div className="text-center pt-4">
              <Button
                type="submit"
                disabled={status === 'sending'}
              >
                {status === 'sending' ? 'Wird gesendet...' : 'Nachricht senden'}
              </Button>
            </div>
          </form>
        </motion.div>
      </Container>
    </section>
  )
}
