"use client";

import { motion, Variants } from "framer-motion";
import { ChevronDown } from "lucide-react";
import NextImage from "next/image";
import { useState } from "react";
import { toast } from "react-hot-toast";

import { useSubmitContactUsMutation } from "@/api/contact.api";
import { parseApiError } from "@/api/utils/error-handler";

const lineContainerVariants: Variants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.025 } },
};

const letterVariants: Variants = {
  hidden: { y: "100%", opacity: 0 },
  visible: {
    y: 0,
    opacity: 1,
    transition: { duration: 0.55, ease: [0.22, 1, 0.36, 1] },
  },
};

interface AnimatedHeadingProps {
  text: string;
  className?: string;
  as?: "h1" | "h2" | "h3";
}

function AnimatedHeading({ text, className, as = "h1" }: AnimatedHeadingProps) {
  const MotionTag =
    as === "h1" ? motion.h1 : as === "h2" ? motion.h2 : motion.h3;
  return (
    <MotionTag
      aria-label={text}
      className={`overflow-hidden ${className ?? ""}`}
      variants={lineContainerVariants}
      initial="hidden"
      whileInView="visible"
      viewport={{ once: true, amount: 0.2 }}
    >
      {Array.from(text).map((char, i) => (
        <motion.span
          key={i}
          variants={letterVariants}
          className="inline-block whitespace-pre"
          aria-hidden
        >
          {char}
        </motion.span>
      ))}
    </MotionTag>
  );
}

const SUBJECT_OPTIONS = [
  { value: "General Inquiry", label: "General Inquiry" },
  { value: "Technical Support", label: "Technical Support" },
  { value: "Billing", label: "Billing" },
  { value: "Feedback", label: "Feedback" },
];

interface FormValues {
  name: string;
  email: string;
  subject: string;
  message: string;
}

interface FormErrors {
  name?: string;
  email?: string;
  subject?: string;
  message?: string;
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function validate(values: FormValues): FormErrors {
  const errors: FormErrors = {};
  if (!values.name.trim()) errors.name = "Name is required.";
  if (!values.email.trim()) {
    errors.email = "Email is required.";
  } else if (!EMAIL_RE.test(values.email)) {
    errors.email = "Please enter a valid email address.";
  }
  if (!values.subject.trim()) errors.subject = "Please select a subject.";
  if (!values.message.trim()) errors.message = "Message is required.";
  return errors;
}

export default function ContactUsContent() {
  const [values, setValues] = useState<FormValues>({
    name: "",
    email: "",
    subject: "",
    message: "",
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [submitContactUs, { isLoading }] = useSubmitContactUsMutation();

  const set =
    (field: keyof FormValues) =>
    (
      e: React.ChangeEvent<
        HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
      >,
    ) => {
      setValues((v) => ({ ...v, [field]: e.target.value }));
      if (errors[field]) setErrors((err) => ({ ...err, [field]: undefined }));
    };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const errs = validate(values);
    if (Object.keys(errs).length > 0) {
      setErrors(errs);
      return;
    }
    try {
      await submitContactUs(values).unwrap();
      toast.success("Message sent successfully!");
      setValues({ name: "", email: "", subject: "", message: "" });
    } catch (err) {
      toast.error(parseApiError(err));
    }
  };

  const fieldClass = (hasError: boolean) =>
    hasError
      ? "w-full border border-red-400 rounded-lg px-4 py-3 text-sm placeholder:text-gray-300 focus:outline-none focus:ring-2 focus:ring-red-400/50 focus:border-transparent transition bg-white"
      : "w-full border border-gray-300 rounded-xl px-4 py-3 text-sm placeholder:text-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition bg-white";

  return (
    <div className="text-gray-900 bg-[#f3f4f6]">
      <div className="max-w-[1074px] mx-auto px-6 py-16">
        <div className="flex flex-col lg:flex-row gap-10 md:gap-20">
          {/* Left info panel */}
          <div className="w-full lg:w-[320px] flex-shrink-0">
            <AnimatedHeading
              as="h1"
              text="Contact Us"
              className="text-2xl font-bold text-gray-900 mb-7"
            />

            <div className="space-y-4 mb-8">
              <div className="flex items-start gap-3 text-gray-700">
                <NextImage
                  src="/assets/icons/location-balck.svg"
                  alt="Location"
                  width={20}
                  height={20}
                  className="h-5 w-5 mt-0.5 flex-shrink-0"
                />
                <span className="text-[15px]">
                  404 Mayfair, Sector 70, Mohali 160071
                </span>
              </div>

              <div className="flex items-center gap-3 text-gray-700">
                <NextImage
                  src="/assets/icons/phone-black.svg"
                  alt="Phone"
                  width={20}
                  height={20}
                  className="h-5 w-5 flex-shrink-0"
                />
                <span className="text-[15px]">(0172) 4020731</span>
              </div>

              <div className="flex items-center gap-3 text-gray-700">
                <NextImage
                  src="/assets/icons/mail-black.svg"
                  alt="Email"
                  width={20}
                  height={20}
                  className="h-5 w-5 flex-shrink-0"
                />
                <span className="text-[15px]">support@myseatime.com</span>
              </div>
            </div>

            <AnimatedHeading
              as="h3"
              text="Connect with us"
              className="text-lg font-bold text-gray-900 mb-4"
            />
            <div className="flex items-center gap-1">
              {[
                {
                  name: "Facebook",
                  icon: "/assets/icons/facebook-black.svg",
                  href: "https://www.facebook.com/myseatime",
                },
                {
                  name: "Linkedin",
                  icon: "/assets/icons/linkedin-black.svg",
                  href: "https://www.linkedin.com/company/my-sea-time",
                },
                {
                  name: "Twitter",
                  icon: "/assets/icons/twitter.svg",
                  href: "https://www.twitter.com/myseatime",
                },
                {
                  name: "Google Plus",
                  icon: "/assets/icons/google-plus-black.svg",
                  href: "https://plus.google.com/115421335061692667021/about",
                },
              ].map((social) => (
                <a
                  key={social.name}
                  href={social.href}
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label={social.name}
                  className="flex items-center justify-center h-9 w-9 rounded-full hover:bg-gray-200 transition-colors text-gray-800 cursor-pointer"
                >
                  <NextImage
                    src={social.icon}
                    alt={social.name}
                    width={20}
                    height={20}
                    className="h-5 w-5"
                  />
                </a>
              ))}
            </div>
          </div>

          {/* Right form panel */}
          <div className="flex-1">
            <AnimatedHeading
              as="h2"
              text="Get in touch"
              className="text-2xl font-bold text-gray-900 mb-7"
            />

            <form onSubmit={handleSubmit} noValidate className="space-y-5">
              {/* Name */}
              <div>
                <label className="block text-sm font-medium text-gray-800 mb-1.5">
                  Name<span className="text-gray-800">*</span>
                </label>
                <input
                  type="text"
                  placeholder="Name"
                  value={values.name}
                  onChange={set("name")}
                  className={fieldClass(!!errors.name)}
                />
                {errors.name && (
                  <p className="text-red-500 text-sm mt-1">{errors.name}</p>
                )}
              </div>

              {/* Email */}
              <div>
                <label className="block text-sm font-medium text-gray-800 mb-1.5">
                  Email Address<span className="text-gray-800">*</span>
                </label>
                <input
                  type="email"
                  placeholder="Email"
                  value={values.email}
                  onChange={set("email")}
                  className={fieldClass(!!errors.email)}
                />
                {errors.email && (
                  <p className="text-red-500 text-sm mt-1">{errors.email}</p>
                )}
              </div>

              {/* Subject */}
              <div>
                <label className="block text-sm font-medium text-gray-800 mb-1.5">
                  Subject<span className="text-gray-800">*</span>
                </label>
                <div className="relative">
                  <select
                    value={values.subject}
                    onChange={set("subject")}
                    className={`${fieldClass(!!errors.subject)} appearance-none pr-10 text-gray-400`}
                  >
                    <option value="" disabled>
                      Choose option
                    </option>
                    {SUBJECT_OPTIONS.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  <ChevronDown
                    className="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400"
                    strokeWidth={2}
                  />
                </div>
                {errors.subject && (
                  <p className="text-red-500 text-sm mt-1">{errors.subject}</p>
                )}
              </div>

              {/* Message */}
              <div>
                <label className="block text-sm font-medium text-gray-800 mb-1.5">
                  Message<span className="text-gray-800">*</span>
                </label>
                <textarea
                  rows={6}
                  placeholder="Message"
                  value={values.message}
                  onChange={set("message")}
                  className={`${fieldClass(!!errors.message)} resize-none`}
                />
                {errors.message && (
                  <p className="text-red-500 text-sm mt-1">{errors.message}</p>
                )}
              </div>

              <button
                type="submit"
                disabled={isLoading}
                className="px-8 py-3 rounded-full bg-blue-400 hover:bg-blue-500 text-white font-semibold text-sm transition-colors shadow-sm cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed"
              >
                {isLoading ? "Sending…" : "Submit Question"}
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}
