import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import { Phone, Mail, MapPin, Clock, Send, Save } from 'lucide-react';
import ParticlesBackground from '../components/ParticlesBackground';
import { supabase } from '../lib/supabase';
import { toast } from 'react-hot-toast';
import type { Database } from '../lib/database.types';
import { Helmet } from "react-helmet";
import useFormPersistence from '../hooks/useFormPersistence';
import { StorageKeys } from '../utils/localStorage';
import { useUserPreferences } from '../contexts/UserPreferencesContext';

type ContactInfo = Database['public']['Tables']['contact_info']['Row'];

interface DisplayContactInfo {
  icon: JSX.Element;
  title: string;
  details: string[];
  actions?: { href: string; text: string; isExternal?: boolean; }[];
}

const Contact = () => {
  const [ref, inView] = useInView({
    triggerOnce: true,
    threshold: 0.1,
  });
  const [contactData, setContactData] = useState<DisplayContactInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  // Get both preferences and addLastVisitedPage from the hook
  const { preferences, addLastVisitedPage } = useUserPreferences();
  
  // Use form persistence hook instead of useState
  const {
    formValues,
    handleInputChange,
    clearPersistedData,
    lastSaved,
    isSupported
  } = useFormPersistence({
    formId: 'contact-form',
    storageKey: StorageKeys.CONTACT_FORM,
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
      phone: '',
      message: ''
    },
    autoSaveDelay: 1000
  });

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    
    try {
      // Format message
      const fullName = `${formValues.firstName} ${formValues.lastName}`;
      const formattedMessage = `
Contact Form Submission
-----------------------
Name: ${fullName}
Email: ${formValues.email}
Phone: ${formValues.phone}
Message: ${formValues.message}
      `;
      
      // Insert into Supabase
      const { error } = await supabase.from('booking_forms').insert({
        form_type: 'Contact',
        name: fullName,
        email: formValues.email,
        phone: formValues.phone,
        message: formattedMessage,
        status: 'new'
      });
      
      if (error) throw error;
      
      // Send email notification
      const { error: emailError } = await supabase.functions.invoke('send-booking-notification', {
        body: {
          to: 'amoebaproductionsstudio@gmail.com',
          subject: `New Contact Form Submission`,
          name: fullName,
          email: formValues.email,
          phone: formValues.phone,
          message: formattedMessage
        }
      });
      
      if (emailError) {
        console.error('Email notification error:', emailError);
        // Continue with form completion even if email fails
      }
      
      toast.success('Your message has been sent successfully!');
      
      // Clear form data from localStorage after successful submission
      clearPersistedData();
    } catch (error) {
      console.error('Error submitting form:', error);
      toast.error('There was an error sending your message. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  // Add user preference tracking (fixed version)
  useEffect(() => {
    if (preferences && !preferences.lastVisitedPages?.includes('/contact')) {
      addLastVisitedPage('/contact');
    }
  }, [preferences, addLastVisitedPage]);

  useEffect(() => {
    const fetchAndFormatContactInfo = async () => {
      setLoading(true);
      const { data, error } = await supabase
        .from('contact_info')
        .select('*')
        .maybeSingle();

      if (error || !data) {
        console.error('Error fetching contact info for contact page:', error);
        setLoading(false);
        return;
      }

      const formatted: DisplayContactInfo[] = [];

      if (data.phone && data.phone.length > 0) {
        // Show both phone numbers if available
        formatted.push({
          icon: <Phone className="w-6 h-6" />,
          title: 'Phone',
          details: data.phone.slice(0, 2), // Show up to 2 phone numbers
          actions: data.phone.slice(0, 2).map((num: string) => ({
            href: `tel:${num.replace(/\s/g, '')}`,
            text: num,
          })),
        });
      }

      if (data.email && data.email.length > 0) {
        // Show only one email (the first one)
        const emailAddress = data.email[0];
        
        formatted.push({
          icon: <Mail className="w-6 h-6" />,
          title: 'Email',
          details: [emailAddress], // Only show one email address
          actions: [{
            href: `mailto:${emailAddress}`,
            text: emailAddress,
          }],
        });
      }

      if (data.address && data.address.length > 0) {
        formatted.push({
          icon: <MapPin className="w-6 h-6" />,
          title: 'Location',
          details: data.address,
          actions: [
            {
              href: 'https://www.google.com/maps/search/?api=1&query=' + encodeURIComponent(data.address.join(', ')),
              text: 'View on Map',
              isExternal: true,
            }
          ],
        });
      }

      if (data.business_hours && data.business_hours.length > 0) {
        formatted.push({
          icon: <Clock className="w-6 h-6" />,
          title: 'Business Hours',
          details: data.business_hours,
        });
      }

      setContactData(formatted);
      setLoading(false);
    };

    fetchAndFormatContactInfo();
  }, []);

  return (
    <div>
      <Helmet>
        <title>Contact Us | Amoeba Productions - Event Management Company Patna</title>
        <meta name="description" content="Contact Amoeba Productions for event management, marketing, and creative services in Patna, Bihar, Delhi, and Ranchi. Get in touch for a free consultation or event quote." />
        <meta name="keywords" content="Contact Amoeba Productions, Event Management Patna, Event Quote, Event Consultation, Event Planner Contact, Patna, Bihar, Delhi, Ranchi" />
        <link rel="canonical" href="https://www.amoebaproductions.com/contact" />
        <meta property="og:title" content="Contact Us | Amoeba Productions - Event Management Company Patna" />
        <meta property="og:description" content="Get in touch with Amoeba Productions for your next event. Contact our team for event planning, marketing, and creative services in Patna and beyond." />
        <meta property="og:image" content="https://www.amoebaproductions.com/images/logo.png" />
        <meta property="og:url" content="https://www.amoebaproductions.com/contact" />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content="Contact Us | Amoeba Productions - Event Management Company Patna" />
        <meta name="twitter:description" content="Contact Amoeba Productions for event management, marketing, and creative services in Patna, Bihar, Delhi, and Ranchi." />
        <meta name="twitter:image" content="https://www.amoebaproductions.com/images/logo.png" />
      </Helmet>
      {/* Hero Section */}
      <section className="relative h-[40vh] flex items-center justify-center overflow-hidden">
        <div className="absolute inset-0">
          <div className="absolute inset-0 bg-gradient-to-r from-primary to-secondary">
            <ParticlesBackground />
          </div>
        </div>
        <div className="relative z-10 text-center text-white px-4">
          <motion.h1
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-5xl md:text-7xl font-playfair font-bold mb-6"
          >
            Contact Us
          </motion.h1>
          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="text-xl text-gray-200"
          >
            Get in Touch with Our Team
          </motion.p>
        </div>
      </section>

      {/* Main Content */}
      <section className="py-20 relative" ref={ref}>
        <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: -50 }}
              animate={inView ? { opacity: 1, x: 0 } : {}}
              transition={{ duration: 0.6 }}
              className="backdrop-blur-xl bg-white/80 p-8 rounded-2xl shadow-lg"
            >
              <div className="flex justify-between items-center mb-8">
                <h2 className="text-3xl font-playfair font-bold">Send us a Message</h2>
                {isSupported && lastSaved && (
                  <div className="flex items-center text-xs text-gray-500">
                    <Save className="w-3 h-3 mr-1" />
                    <span>Autosaved {new Date(lastSaved).toLocaleTimeString()}</span>
                  </div>
                )}
              </div>
              <form className="space-y-6" onSubmit={handleSubmit}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      First Name
                    </label>
                    <input
                      type="text"
                      name="firstName"
                      value={formValues.firstName}
                      onChange={handleInputChange}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                      required
                      disabled={submitting}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Last Name
                    </label>
                    <input
                      type="text"
                      name="lastName"
                      value={formValues.lastName}
                      onChange={handleInputChange}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                      required
                      disabled={submitting}
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Email
                  </label>
                  <input
                    type="email"
                    name="email"
                    value={formValues.email}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                    required
                    disabled={submitting}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Phone
                  </label>
                  <input
                    type="tel"
                    name="phone"
                    value={formValues.phone}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                    required
                    disabled={submitting}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Message
                  </label>
                  <textarea
                    name="message"
                    value={formValues.message}
                    onChange={handleInputChange}
                    rows={4}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                    required
                    disabled={submitting}
                  />
                </div>
                <button
                  type="submit"
                  className="w-full px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors duration-200 flex items-center justify-center"
                  disabled={submitting}
                >
                  <Send className="w-5 h-5 mr-2" />
                  {submitting ? 'Sending...' : 'Send Message'}
                </button>
              </form>
            </motion.div>

            {/* Contact Information */}
            <motion.div
              initial={{ opacity: 0, x: 50 }}
              animate={inView ? { opacity: 1, x: 0 } : {}}
              transition={{ duration: 0.6 }}
              className="space-y-8"
            >
              {loading ? (
                <p className="text-center text-gray-600">Loading contact details...</p>
              ) : contactData.length === 0 ? (
                <p className="text-center text-gray-600">Contact information not available.</p>
              ) : (
                contactData.map((info, idx) => (
                  <motion.div
                    key={idx}
                    initial={{ opacity: 0, y: 20 }}
                    animate={inView ? { opacity: 1, y: 0 } : {}}
                    transition={{ duration: 0.5, delay: idx * 0.1 }}
                    className="backdrop-blur-xl bg-white/80 p-6 rounded-xl shadow-lg"
                  >
                    <div className="flex items-start">
                      <div className="p-3 bg-primary/10 rounded-lg text-primary">
                        {info.icon}
                      </div>
                      <div className="ml-4">
                        <h3 className="text-xl font-semibold mb-2">{info.title}</h3>
                        {info.details.map((detail, detailIdx) => (
                          <p key={detailIdx} className="text-gray-600 flex items-center">
                            {detail}
                            {/* Place clickable icon directly after each detail */}
                            {info.actions && info.actions[detailIdx] && (
                              <a
                                href={info.actions[detailIdx].href}
                                target={info.actions[detailIdx].isExternal ? "_blank" : "_self"}
                                rel={info.actions[detailIdx].isExternal ? "noopener noreferrer" : undefined}
                                className="inline-flex items-center text-primary hover:text-primary-dark text-sm ml-2"
                                aria-label={`Contact via ${info.title}`}
                              >
                                <Send className="w-4 h-4" />
                              </a>
                            )}
                          </p>
                        ))}
                        {/* Special handling for actions that aren't tied to details (like "View on Map") */}
                        {info.actions && info.title !== 'Phone' && info.title !== 'Email' && (
                          <div className="mt-2">
                            {info.actions.map((action, actionIdx) => (
                              <a
                                key={actionIdx}
                                href={action.href}
                                target={action.isExternal ? "_blank" : "_self"}
                                rel={action.isExternal ? "noopener noreferrer" : undefined}
                                className="inline-flex items-center text-primary hover:text-primary-dark text-sm mr-4"
                              >
                                {action.text}
                                <Send className="w-4 h-4 ml-1" />
                              </a>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </motion.div>
                ))
              )}

              {/* Map */}
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={inView ? { opacity: 1, y: 0 } : {}}
                transition={{ duration: 0.5, delay: loading ? 0.5 : contactData.length * 0.1 }}
                className="backdrop-blur-xl bg-white/80 p-6 rounded-xl shadow-lg"
              >
                <iframe
                  src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3597.5647563466147!2d85.09570000000001!3d25.631565!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2zMjXCsDM3JzUzLjYiTiA4NcKwMDUnNDQuNSJF!5e0!3m2!1sen!2sin!4v1648226144597!5m2!1sen!2sin"
                  width="100%"
                  height="300"
                  style={{ border: 0 }}
                  allowFullScreen
                  loading="lazy"
                  referrerPolicy="no-referrer-when-downgrade"
                  className="rounded-lg"
                />
              </motion.div>
            </motion.div>
          </div>
        </div>
      </section>
    </div>
  );
};

// Helper function to find primary item (marked with "Primary:" or first in the array)
const findPrimaryItem = (items: string[]): string => {
  // First check for any item marked as primary
  const primaryItem = items.find(item => 
    item.toLowerCase().includes('primary:') || 
    item.match(/:\s*.*\(primary\)/i)
  );
  
  if (primaryItem) {
    // Remove the "Primary:" prefix if it exists
    return primaryItem.replace(/primary:\s*/i, '').replace(/\s*\(primary\)/i, '');
  }
  
  // If no primary item found, return the first item
  return items[0];
};

export default Contact;