"use client";

import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import React, { useState } from "react";
import { MaterialIcon } from "@/components/ui/MaterialIcon";

const COMPANY = [
  { label: "About Us", href: "/about" },
  { label: "Careers", href: "#" },
  { label: "Press & News", href: "#" },
  { label: "Help Center", href: "#" },
];

const PARTNERSHIPS = [
  { label: "Merchant Partner", href: "/businesses" },
  { label: "Delivery Partner", href: "#" },
  { label: "Corporate Gifting", href: "#" },
  { label: "Local Real Estate", href: "#" },
];

const LEGAL = [
  { label: "Privacy Policy", href: "#" },
  { label: "Terms of Service", href: "#" },
  { label: "Cookie Policy", href: "#" },
  { label: "Sitemap", href: "#" },
];

type FooterFormData = {
  name: string;
  phone: string;
  email: string;
  message: string;
};

type FooterFormErrors = {
  name?: string;
  phone?: string;
  email?: string;
  message?: string;
};

export function Footer() {
  const pathname = usePathname();
  const isContactPage = pathname === "/contact";

  // Form states
  const [formData, setFormData] = useState<FooterFormData>({
    name: "",
    phone: "",
    email: "",
    message: "",
  });
  const [errors, setErrors] = useState<FooterFormErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    if (errors[name as keyof FooterFormErrors]) {
      setErrors((prev) => ({
        ...prev,
        [name]: undefined,
      }));
    }
  };

  const validateForm = (): boolean => {
    const tempErrors: FooterFormErrors = {};
    let isValid = true;

    if (!formData.name.trim()) {
      tempErrors.name = "Name is required";
      isValid = false;
    }

    if (!formData.phone.trim()) {
      tempErrors.phone = "Phone is required";
      isValid = false;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!formData.email.trim()) {
      tempErrors.email = "Email is required";
      isValid = false;
    } else if (!emailRegex.test(formData.email)) {
      tempErrors.email = "Please enter a valid email address";
      isValid = false;
    }

    if (!formData.message.trim()) {
      tempErrors.message = "Message is required";
      isValid = false;
    }

    setErrors(tempErrors);
    return isValid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;

    setIsSubmitting(true);
    // Simulate API delay
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setIsSubmitting(false);
    setSubmitSuccess(true);
    setFormData({ name: "", phone: "", email: "", message: "" });

    // Hide success alert after 5 seconds
    setTimeout(() => {
      setSubmitSuccess(false);
    }, 5000);
  };

  return (
    <footer className="footer relative z-10 bg-brand-dark text-white border-t border-white/5 w-full mt-24">
      {/* Overlapping Contact Helpdesk Card */}
      <div className="footer-helpdesk-wrap">
        <div className="bg-brand-accent p-6 md:p-8 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-center gap-6 shadow-2xl border border-brand-accent/20">
          <div className="flex items-center gap-4 text-brand-dark">
            <div className="w-12 h-12 rounded-full bg-brand-dark text-brand-accent flex items-center justify-center shadow-lg">
              <MaterialIcon icon="headset_mic" size={24} />
            </div>
            <div>
              <h4 className="text-headline-md font-black">24/7 Neighborhood Helpdesk</h4>
              <p className="helpdesk-subtitle mt-0.5">
                Need immediate assistance with an order or local service?
              </p>
            </div>
          </div>
          <a
            href="tel:+918049123456"
            className="helpdesk-btn"
          >
            <MaterialIcon icon="phone" size={20} className="animate-pulse-subtle" />
            <span>+91 80 4912 3456</span>
          </a>
        </div>
      </div>

      <div className="footer-container">
        {/* Main content wrapper */}
        <div className="footer-main">
          {/* Main content grid: aligned on the same top baseline */}
          <div className={`${
            isContactPage 
              ? "footer-grid-contact-page" 
              : "footer-grid"
          }`}>
            {/* Brand Column */}
            <div className="footer-brand">
              <Link
                href="/"
                className="mb-4 inline-block"
              >
                <Image
                  src="/logo-v2.png"
                  alt="Nearle"
                  width={220}
                  height={36}
                  style={{ width: "210px", height: "auto" }}
                  className="object-contain"
                />
              </Link>
              <p className="footer-desc mb-4">
                India&apos;s leading hyperlocal neighborhood network, empowering communities and verified local businesses within 2km.
              </p>
              {/* Social Links */}
              <div className="flex gap-4">
                <a
                  href="#"
                  className="footer-social-link"
                  aria-label="Share"
                >
                  <MaterialIcon icon="share" size={24} />
                </a>
                <a
                  href="#"
                  className="footer-social-link"
                  aria-label="Website"
                >
                  <MaterialIcon icon="public" size={24} />
                </a>
              </div>
            </div>

            {/* Company Links */}
            <div className="footer-company">
              <FooterCol title="Company" links={COMPANY} />
            </div>

            {/* Partnerships Links */}
            <div className="footer-partnerships">
              <FooterCol title="Partnerships" links={PARTNERSHIPS} />
            </div>

            {/* Legal Links */}
            <div className="footer-legal">
              <FooterCol title="Legal" links={LEGAL} />
            </div>

            {/* Contact Form Card */}
            {!isContactPage && (
              <div className="footer-contact-wrap">
                <div className="footer-contact-card bg-white text-brand-dark shadow-2xl border border-outline-variant/15 relative overflow-hidden">
                  {/* Background Glow Decors */}
                  <div className="absolute top-0 right-0 w-24 h-24 bg-primary/5 rounded-full blur-2xl" />
                  <div className="absolute bottom-0 left-0 w-24 h-24 bg-secondary/5 rounded-full blur-2xl" />

                  <div className="relative z-10 text-center lg:text-left">
                    <h3 className="footer-contact-title font-display text-2xl md:text-3xl font-black text-brand-dark tracking-tight">
                      Send us a Message
                    </h3>
                    <p className="footer-contact-subtitle text-sm md:text-base mt-2">
                      We shall guide you through our Neighbourhood Experts.
                    </p>

                    <form onSubmit={handleSubmit} className="space-y-4">
                      {submitSuccess && (
                        <div className="p-3 bg-secondary/10 border border-secondary/20 text-secondary text-body-sm font-bold rounded-xl flex items-center justify-center gap-1.5 animate-bounce-subtle">
                          <MaterialIcon icon="check_circle" size={16} />
                          <span>Message sent successfully!</span>
                        </div>
                      )}

                      <div className="footer-form-row">
                        <div className="flex flex-col text-left">
                          <label htmlFor="footer-field-name" className="text-xs font-black text-brand-dark/70 mb-1.5">Your Name</label>
                          <input
                            type="text"
                            id="footer-field-name"
                            name="name"
                            value={formData.name}
                            onChange={handleInputChange}
                            placeholder="Your Name..."
                            className={`footer-input ${errors.name ? "has-error" : ""}`}
                          />
                          {errors.name && (
                            <span className="footer-error-text">
                              <MaterialIcon icon="error" size={16} />
                              {errors.name}
                            </span>
                          )}
                        </div>
                        <div className="flex flex-col text-left">
                          <label htmlFor="footer-field-phone" className="text-xs font-black text-brand-dark/70 mb-1.5">Your Phone</label>
                          <input
                            type="text"
                            id="footer-field-phone"
                            name="phone"
                            value={formData.phone}
                            onChange={handleInputChange}
                            placeholder="Your Phone..."
                            className={`footer-input ${errors.phone ? "has-error" : ""}`}
                          />
                          {errors.phone && (
                            <span className="footer-error-text">
                              <MaterialIcon icon="error" size={16} />
                              {errors.phone}
                            </span>
                          )}
                        </div>
                      </div>

                      <div className="flex flex-col text-left">
                        <label htmlFor="footer-field-email" className="text-xs font-black text-brand-dark/70 mb-1.5">Your Email Address</label>
                        <input
                          type="email"
                          id="footer-field-email"
                          name="email"
                          value={formData.email}
                          onChange={handleInputChange}
                          placeholder="Your Email Address..."
                          className={`footer-input ${errors.email ? "has-error" : ""}`}
                        />
                        {errors.email && (
                          <span className="footer-error-text">
                            <MaterialIcon icon="error" size={16} />
                            {errors.email}
                          </span>
                        )}
                      </div>

                      <div className="flex flex-col text-left">
                        <label htmlFor="footer-field-message" className="text-xs font-black text-brand-dark/70 mb-1.5">Your Message</label>
                        <textarea
                          id="footer-field-message"
                          name="message"
                          value={formData.message}
                          onChange={handleInputChange}
                          placeholder="Your Message..."
                          className={`footer-textarea ${errors.message ? "has-error" : ""}`}
                        />
                        {errors.message && (
                          <span className="footer-error-text">
                            <MaterialIcon icon="error" size={16} />
                            {errors.message}
                          </span>
                        )}
                      </div>

                      <button
                        type="submit"
                        disabled={isSubmitting}
                        className="footer-submit-btn"
                      >
                        {isSubmitting ? (
                          <>
                            <span className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                            <span>SUBMITTING...</span>
                          </>
                        ) : (
                          <span>SUBMIT</span>
                        )}
                      </button>
                    </form>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Divider */}
        <hr className="footer-divider" />

        {/* Bottom Bar */}
        <div className="footer-bottom">
          <div className="flex flex-col md:flex-row justify-between items-center gap-4">
            <p className="footer-bottom-text">
              © {new Date().getFullYear()} Nearle. All rights reserved.
            </p>
            <div className="flex items-center gap-2 footer-bottom-text">
              <span>Designed for neighborhoods in</span>
              <span className="flex items-center gap-1 font-bold text-white/80">
                India 🇮🇳
              </span>
            </div>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Ensure default export is also available for Next.js app router client components if needed
export default Footer;


function FooterCol({
  title,
  links,
}: {
  title: string;
  links: { label: string; href: string }[];
}) {
  return (
    <div>
      <h5 className="footer-column-title">
        {title}
      </h5>
      <ul className="footer-links-list">
        {links.map((l) => (
          <li key={l.label}>
            <Link
              href={l.href}
              className="footer-link inline-block"
            >
              {l.label}
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}
