import React, { useState } from 'react';
import { Helmet } from 'react-helmet';
import { motion } from 'framer-motion';
import Header from '@/components/Header.jsx';
import Footer from '@/components/Footer.jsx';
import WhatsAppButton from '@/components/WhatsAppButton.jsx';
import { Button } from '@/components/ui/button.jsx';
import { Input } from '@/components/ui/input.jsx';
import { Textarea } from '@/components/ui/textarea.jsx';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card.jsx';
import { Label } from '@/components/ui/label.jsx';
import { useToast } from '@/hooks/use-toast.js';
import { Phone, Mail, MapPin, Loader2 } from 'lucide-react';
import apiServerClient from '@/lib/apiServerClient.js';

export default function ContatoPage() {
  const { toast } = useToast();
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    telefone: '',
    message: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Form validation
    if (!formData.name.trim() || !formData.email.trim() || !formData.message.trim()) {
      toast({
        title: 'Campos obrigatórios',
        description: 'Por favor, preencha nome, email e mensagem.',
        variant: 'destructive'
      });
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await apiServerClient.fetch('/contact', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          nome: formData.name,
          email: formData.email,
          telefone: formData.telefone,
          mensagem: formData.message
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || data.message || 'Falha ao enviar a mensagem.');
      }

      // Success feedback
      toast({
        title: 'Mensagem enviada com sucesso!',
        description: 'Recebemos seu contato e retornaremos em breve.'
      });
      
      // Reset form
      setFormData({ name: '', email: '', telefone: '', message: '' });
    } catch (error) {
      console.error('Erro no envio do formulário:', error);
      
      // Error feedback
      toast({
        title: 'Erro ao enviar',
        description: error.message || 'Ocorreu um problema. Tente novamente mais tarde.',
        variant: 'destructive'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const contactInfo = [
    {
      icon: Phone,
      title: 'WhatsApp',
      value: '(47) 9740-5051',
      link: 'https://wa.me/5547974050051'
    },
    {
      icon: Mail,
      title: 'Email',
      value: 'contato@lcpvaluation.com.br',
      link: 'mailto:contato@lcpvaluation.com.br'
    },
    {
      icon: MapPin,
      title: 'Endereço',
      value: 'R. 3610, 237 - Centro, Balneário Camboriú - SC',
      link: 'https://maps.google.com/?q=R.+3610,+237+-+Centro,+Balneário+Camboriú+-+SC'
    }
  ];

  return (
    <>
      <Helmet>
        <title>Contato - LCP Valuation</title>
        <meta name="description" content="Fale com a LCP e descubra como valorizar seu imóvel com tecnologia. Atendimento especializado e análise personalizada." />
      </Helmet>

      <Header />

      <main className="pt-20">
        {/* Hero Section */}
        <section className="py-20 bg-gradient-to-br from-secondary via-secondary/95 to-secondary/90 text-secondary-foreground">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8 }}
              className="max-w-3xl mx-auto text-center"
            >
              <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 leading-tight" style={{ letterSpacing: '-0.02em' }}>
                Entre em contato
              </h1>
              <p className="text-xl md:text-2xl opacity-90">
                Estamos prontos para transformar seu imóvel em um patrimônio inteligente
              </p>
            </motion.div>
          </div>
        </section>

        {/* Contact Section */}
        <section className="py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
              {/* Contact Form */}
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                whileInView={{ opacity: 1, x: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.6 }}
              >
                <Card>
                  <CardHeader>
                    <CardTitle>Envie sua mensagem</CardTitle>
                    <CardDescription>
                      Preencha o formulário e entraremos em contato em breve
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <form onSubmit={handleSubmit} className="space-y-6">
                      <div className="space-y-2">
                        <Label htmlFor="name">Nome completo <span className="text-destructive">*</span></Label>
                        <Input
                          id="name"
                          name="name"
                          type="text"
                          placeholder="Seu nome"
                          value={formData.name}
                          onChange={handleChange}
                          required
                          disabled={isSubmitting}
                          className="text-foreground"
                        />
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-2">
                          <Label htmlFor="email">Email <span className="text-destructive">*</span></Label>
                          <Input
                            id="email"
                            name="email"
                            type="email"
                            placeholder="seu@email.com"
                            value={formData.email}
                            onChange={handleChange}
                            required
                            disabled={isSubmitting}
                            className="text-foreground"
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="telefone">Telefone / WhatsApp</Label>
                          <Input
                            id="telefone"
                            name="telefone"
                            type="tel"
                            placeholder="(00) 00000-0000"
                            value={formData.telefone}
                            onChange={handleChange}
                            disabled={isSubmitting}
                            className="text-foreground"
                          />
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="message">Mensagem <span className="text-destructive">*</span></Label>
                        <Textarea
                          id="message"
                          name="message"
                          placeholder="Conte-nos sobre seu projeto..."
                          value={formData.message}
                          onChange={handleChange}
                          required
                          disabled={isSubmitting}
                          rows={6}
                          className="text-foreground resize-none"
                        />
                      </div>

                      <Button
                        type="submit"
                        className="w-full"
                        disabled={isSubmitting}
                      >
                        {isSubmitting ? (
                          <>
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            Enviando...
                          </>
                        ) : (
                          'Enviar mensagem'
                        )}
                      </Button>
                    </form>
                  </CardContent>
                </Card>
              </motion.div>

              {/* Contact Info */}
              <motion.div
                initial={{ opacity: 0, x: 20 }}
                whileInView={{ opacity: 1, x: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.6 }}
                className="space-y-8"
              >
                <div>
                  <h2 className="text-2xl font-bold mb-6">
                    Informações de contato
                  </h2>
                  <div className="space-y-4">
                    {contactInfo.map((info, index) => (
                      <Card key={index} className="hover:shadow-lg transition-all duration-300">
                        <CardContent className="p-6">
                          <div className="flex items-start gap-4">
                            <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                              <info.icon className="h-6 w-6 text-primary" />
                            </div>
                            <div className="flex-1">
                              <p className="text-sm text-muted-foreground mb-1">
                                {info.title}
                              </p>
                              {info.link ? (
                                <a
                                  href={info.link}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-lg font-semibold hover:text-primary transition-colors"
                                >
                                  {info.value}
                                </a>
                              ) : (
                                <p className="text-lg font-semibold">{info.value}</p>
                              )}
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </div>

                <Card className="bg-primary/5 border-primary/20">
                  <CardContent className="p-8 text-center">
                    <h3 className="text-xl font-bold mb-4">
                      Prefere falar diretamente?
                    </h3>
                    <p className="text-muted-foreground mb-6">
                      Entre em contato pelo WhatsApp para um atendimento mais rápido
                    </p>
                    <WhatsAppButton
                      message="Olá! Gostaria de saber mais sobre automação residencial."
                      className="w-full bg-primary text-primary-foreground hover:bg-primary/90"
                    >
                      Abrir WhatsApp
                    </WhatsAppButton>
                  </CardContent>
                </Card>
              </motion.div>
            </div>
          </div>
        </section>
      </main>

      <Footer />
    </>
  );
}