import React, { useState, useEffect } from 'react';
import { MapPin, Phone, Mail, Clock, CheckCircle2, ArrowRight, Send, Calendar, Users } from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Textarea } from './ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { BrandedTag } from './about/BrandedTag';
import { PrimaryCTAButton } from './PrimaryCTAButton';
import { ImageWithFallback } from './figma/ImageWithFallback';
import { navigateTo } from './Router';
import kautilyabg from '../assets/Kautilya.png';
import { useCreateLeadMutation, useGetLeadCategoriesQuery } from '../redux/services/contactUsApi';

interface ContactProps {
  topic?: string;
}

export function Contact({ topic }: ContactProps) {
  const [formData, setFormData] = useState({
    name: '',
    mobileNumber: '',
    emailId: '',
    interestedIn: '',
    message: ''
  });

  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const { data: categoryData } = useGetLeadCategoriesQuery({
    limit: 20,
    offset: 0,
    status: "active"
  });

  const categories = categoryData?.data?.items || [];

  const [createLead] = useCreateLeadMutation();

  useEffect(() => {
    console.log('Contact component mounted with topic:', topic);
    // Set default interested in based on topic parameter
    if (topic) {
      const interestedIn = getTopicSubject(topic);
      console.log('Setting form interestedIn to:', interestedIn);
      setFormData(prev => ({
        ...prev,
        interestedIn: interestedIn
      }));
    }
  }, [topic]);

  const getTopicSubject = (topicParam: string) => {
    switch (topicParam) {
      case 'leadership-pipeline':
        return 'Leadership Pipeline Development';
      case 'consulting':
        return 'Consulting Services';
      case 'executive-coaching':
        return 'Executive Coaching';
      case 'learning-facility':
        return 'Learning Facility';
      default:
        return topicParam.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
    }
  };

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      await createLead({
        full_name: formData.name,
        phone_number: formData.mobileNumber,
        email_address: formData.emailId,
        lead_category_xid: formData.interestedIn,
        message: formData.message,
        lead_status: "NEW"
      }).unwrap();

      setIsSubmitted(true);

    } catch (error) {
      console.error("Lead creation failed", error);
    }

    setIsSubmitting(false);
  };

  if (isSubmitted) {
    return (
      <div className="min-h-screen" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="section-margin-x py-24">
          <div className="max-w-2xl mx-auto text-center">
            <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
              <CheckCircle2 className="w-10 h-10 text-green-600" />
            </div>

            <h1 className="text-h2 mb-4">Thank You!</h1>

            <p className="text-body-lg text-muted mb-8">
              We've received your message and will get back to you within 24 hours.
              Our leadership development experts are excited to help transform your organization.
            </p>

            <div className="flex justify-center">
              <PrimaryCTAButton
                text="Return to Home"
                onClick={() => navigateTo('/')}
                ariaLabel="Return to homepage"
              />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#FFFFFF' }}>
      {/* Hero Section with Google Map Background */}
      <section className="relative h-[600px] overflow-hidden">
        {/* Google Map Background */}
        <div className="absolute inset-0">
          <ImageWithFallback
            src={kautilyabg}
            alt="Google Maps showing office location and navigation"
            className="w-full h-full object-cover"
          />

          {/* Dark overlay for better text readability */}
          <div className="absolute inset-0 bg-black/60" />
        </div>

        {/* Content Container */}
        <div className="relative h-full flex items-center justify-center section-margin-x">
          {/* Hero Content Block */}
          <div className="text-center max-w-4xl mx-auto">
            {/* Branded Tag */}
            <BrandedTag text="Contact Us" variant="white" />

            {/* Main Headline */}
            <h1 className="text-h1-white mb-6">
              Reach us
            </h1>

            {/* Supporting Text */}
            <p className="text-body-lg-white opacity-90 max-w-3xl mx-auto">
              Get in touch with us to start your leadership development journey.
            </p>
          </div>
        </div>
      </section>

      {/* Main Content Section */}
      <div className="section-margin-x py-16">
        <div className="max-w-7xl mx-auto">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-12">
            {/* Contact Information - Enhanced Design */}
            <div className="lg:col-span-1">
              <div className="bg-white rounded-xl shadow-lg border border-gray-100 h-fit overflow-hidden">
                {/* Contact Info Header */}
                <div
                  className="p-8 text-white"
                  style={{ backgroundColor: 'var(--color-brand-primary)' }}
                >
                  <h2 className="text-h3-white mb-2">Contact Information</h2>
                  <p className="text-body-white opacity-90">
                    We're here to help you on your leadership journey
                  </p>
                </div>

                {/* Contact Details */}
                <div className="p-8 space-y-8">
                  {/* Corporate Office */}
                  <div className="flex items-start gap-4">
                    <div
                      className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0"
                      style={{ backgroundColor: 'rgba(248, 195, 1, 0.1)' }}
                    >
                      <MapPin className="w-6 h-6" style={{ color: 'var(--color-brand-primary)' }} />
                    </div>
                    <div>
                      <h3 className="text-h3 mb-2">Corporate Office</h3>
                      <p className="text-body text-muted">
                        Leadership Centre Pvt. Ltd.<br />
                        No. 107, 1st Floor<br />
                        T.V. Industrial Estate, Worli<br />
                        Mumbai 400030
                      </p>
                    </div>
                  </div>

                  {/* Registered Office */}
                  <div className="flex items-start gap-4">
                    <div
                      className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0"
                      style={{ backgroundColor: 'rgba(248, 195, 1, 0.1)' }}
                    >
                      <MapPin className="w-6 h-6" style={{ color: 'var(--color-brand-primary)' }} />
                    </div>
                    <div>
                      <h3 className="text-h3 mb-2">Registered Office</h3>
                      <p className="text-body text-muted">
                        Kautilya Leadership Services<br />
                        R.S. No. 5/6, Savaroli Kharpada Road<br />
                        Dhamani Taluk, Khalapur District<br />
                        Raigad – 410202
                      </p>
                    </div>
                  </div>

                  {/* Email */}
                  <div className="flex items-start gap-4">
                    <div
                      className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0"
                      style={{ backgroundColor: 'rgba(248, 195, 1, 0.1)' }}
                    >
                      <Mail className="w-6 h-6" style={{ color: 'var(--color-brand-primary)' }} />
                    </div>
                    <div>
                      <h3 className="text-h3 mb-2">Email</h3>
                      <p className="text-body text-muted">
                        connect@leadershipcentre.in<br />
                        connect@kautilyaservices.in
                      </p>
                    </div>
                  </div>

                  {/* Phone */}
                  <div className="flex items-start gap-4">
                    <div
                      className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0"
                      style={{ backgroundColor: 'rgba(248, 195, 1, 0.1)' }}
                    >
                      <Phone className="w-6 h-6" style={{ color: 'var(--color-brand-primary)' }} />
                    </div>
                    <div>
                      <h3 className="text-h3 mb-2">Phone</h3>
                      <p className="text-body text-muted">
                        +91-22-2084 0097<br />
                        +91-8928738661
                      </p>
                    </div>
                  </div>
                </div>

                {/* Quick Actions */}
                <div
                  className="p-8 border-t"
                  style={{ borderColor: 'var(--color-border)' }}
                >
                  <h3 className="text-h3 mb-4">Quick Actions</h3>
                  <div className="space-y-3">
                    <Button
                      variant="outline"
                      className="w-full justify-start hover:bg-blue-50 hover:border-blue-200 transition-all duration-300"
                      onClick={() => navigateTo('/services/learning-facility')}
                      style={{
                        borderColor: 'var(--color-brand-primary)',
                        color: 'var(--color-brand-primary)'
                      }}
                    >
                      <Calendar className="w-4 h-4 mr-2" />
                      Schedule Facility Tour
                    </Button>
                    <Button
                      variant="outline"
                      className="w-full justify-start hover:bg-blue-50 hover:border-blue-200 transition-all duration-300"
                      onClick={() => navigateTo('/leadership-journey')}
                      style={{
                        borderColor: 'var(--color-brand-primary)',
                        color: 'var(--color-brand-primary)'
                      }}
                    >
                      <Users className="w-4 h-4 mr-2" />
                      Start Leadership Assessment
                    </Button>
                  </div>
                </div>
              </div>
            </div>

            {/* Contact Form - Enhanced Design */}
            <div className="lg:col-span-2">
              <div className="bg-white rounded-xl shadow-lg border border-gray-100">
                {/* Form Header */}
                <div className="p-8 border-b" style={{ borderColor: 'var(--color-border)' }}>
                  <div className="flex items-center gap-3 mb-2">
                    <div
                      className="w-10 h-10 rounded-lg flex items-center justify-center"
                      style={{ backgroundColor: 'rgba(248, 195, 1, 0.1)' }}
                    >
                      <Send className="w-5 h-5" style={{ color: 'var(--color-brand-primary)' }} />
                    </div>
                    <h2 className="text-h3">Enquiry Form</h2>
                  </div>
                  <p className="text-body text-muted">
                    Fill out the form below and we'll get back to you within 24 hours.
                  </p>
                </div>

                {/* Form Content */}
                <div className="p-8">
                  <form onSubmit={handleSubmit} className="space-y-6">
                    <div>
                      <label className="text-body font-medium mb-3 block" style={{ color: 'var(--color-black)' }}>
                        Name *
                      </label>
                      <Input
                        type="text"
                        required
                        value={formData.name}
                        onChange={(e) => handleInputChange('name', e.target.value)}
                        placeholder="Enter your full name"
                        className="w-full h-12 border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                        style={{
                          fontFamily: 'var(--font-family-base)',
                          fontSize: 'var(--font-body)'
                        }}
                      />
                    </div>

                    <div>
                      <label className="text-body font-medium mb-3 block" style={{ color: 'var(--color-black)' }}>
                        Mobile Number *
                      </label>
                      <Input
                        type="tel"
                        required
                        value={formData.mobileNumber}
                        onChange={(e) => handleInputChange('mobileNumber', e.target.value)}
                        placeholder="+91 98765 43210"
                        className="w-full h-12 border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                        style={{
                          fontFamily: 'var(--font-family-base)',
                          fontSize: 'var(--font-body)'
                        }}
                      />
                    </div>

                    <div>
                      <label className="text-body font-medium mb-3 block" style={{ color: 'var(--color-black)' }}>
                        Email Id *
                      </label>
                      <Input
                        type="email"
                        required
                        value={formData.emailId}
                        onChange={(e) => handleInputChange('emailId', e.target.value)}
                        placeholder="example@company.com"
                        className="w-full h-12 border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                        style={{
                          fontFamily: 'var(--font-family-base)',
                          fontSize: 'var(--font-body)'
                        }}
                      />
                    </div>

                    <div>
                      <label className="text-body font-medium mb-3 block" style={{ color: 'var(--color-black)' }}>
                        Interested In *
                      </label>
                      <Select
                        value={formData.interestedIn}
                        onValueChange={(value: string) => handleInputChange('interestedIn', value)}
                      >
                        <SelectTrigger
                          className="w-full h-12 border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                          style={{
                            fontFamily: 'var(--font-family-base)',
                            fontSize: 'var(--font-body)'
                          }}
                        >
                          <SelectValue placeholder="Select your area of interest" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectContent>
                            {categories.map((cat: any) => (
                              <SelectItem key={cat.id} value={cat.id}>
                                {cat.category_type}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </SelectContent>
                      </Select>
                    </div>

                    <div>
                      <label className="text-body font-medium mb-3 block" style={{ color: 'var(--color-black)' }}>
                        Enter Message *
                      </label>
                      <Textarea
                        required
                        value={formData.message}
                        onChange={(e) => handleInputChange('message', e.target.value)}
                        placeholder="Please enter your message or inquiry..."
                        rows={6}
                        className="w-full border-gray-200 focus:border-blue-500 focus:ring-blue-500 resize-none"
                        style={{
                          fontFamily: 'var(--font-family-base)',
                          fontSize: 'var(--font-body)'
                        }}
                      />
                    </div>

                    <div className="pt-6 border-t" style={{ borderColor: 'var(--color-border)' }}>
                      <div className="flex flex-col sm:flex-row gap-4 justify-between items-start sm:items-center">
                        <div className="text-small text-muted">
                          * Required fields. We'll respond within 24 hours.
                        </div>
                        <PrimaryCTAButton
                          text={isSubmitting ? "Sending Message..." : "Send Message"}
                          onClick={() => { handleSubmit }}
                          ariaLabel="Send contact message"
                          className="w-full sm:w-auto"
                        />
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Enhanced CTA Section - Matching Landing Page Style */}
      <section className="relative h-[800px] overflow-hidden">
        {/* Background Image */}
        <div className="absolute inset-0">
          <ImageWithFallback
            src="https://images.unsplash.com/photo-1552664730-d307ca884978?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2940&q=80"
            alt="Professional team collaborating in modern office"
            className="w-full h-full object-cover"
          />

          {/* Subtle dark overlay for overall image */}
          <div className="absolute inset-0 bg-black/30" />


        </div>

        {/* Content Container */}
        <div className="relative h-full flex items-center justify-end section-margin-x">
          {/* CTA Content Block */}
          <div
            className="bg-opacity-95 backdrop-blur-sm rounded-lg p-16 max-w-2xl"
            style={{
              backgroundColor: 'var(--color-brand-primary)'
            }}
          >
            {/* Branded Tag */}
            <BrandedTag text="Next Steps" variant="white" />

            {/* Main Headline */}
            <h2 className="text-h2-white mb-8">
              Ready to transform your leadership?
              <span
                className="italic"
                style={{ color: 'var(--color-brand-accent)' }}
              >
                {" "}Get in touch{" "}
              </span>
              to start your development journey now.
            </h2>

            <PrimaryCTAButton
              text="Schedule a Consultation"
              onClick={() => navigateTo('/contact?topic=consulting')}
              ariaLabel="Schedule a consultation with our leadership experts"
              className="cta-banner-yellow"
            />

            {/* Supporting Text */}
            <p className="text-body-white opacity-90">
              Connect with our leadership experts to discuss your organization's specific development needs.
            </p>
          </div>
        </div>
      </section>
    </div>
  );
}