"use client";

import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronLeft, ChevronRight, CheckCircle2, AlertCircle, Loader2 } from "lucide-react";
import { TEAM_MEMBERS, REQUIREMENT_OPTIONS } from "@/config/siteContent";
import { inquirySchema } from "@/lib/inquirySchema";

export default function TeamContact() {
  const [currentAgentIdx, setCurrentAgentIdx] = useState(0);
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    houseType: REQUIREMENT_OPTIONS[0] || "1BHK",
    customHouseType: "",
    message: "",
  });

  const handlePrev = () => {
    setCurrentAgentIdx((prev) => (prev === 0 ? TEAM_MEMBERS.length - 1 : prev - 1));
  };

  const handleNext = () => {
    setCurrentAgentIdx((prev) => (prev === TEAM_MEMBERS.length - 1 ? 0 : prev + 1));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setServerError(null);
    setFieldErrors({});

    // Client-side Zod validation
    const parseResult = inquirySchema.safeParse(formData);
    if (!parseResult.success) {
      const formattedErrors: Record<string, string> = {};
      parseResult.error.issues.forEach((issue) => {
        const fieldName = issue.path[0] as string;
        if (fieldName && !formattedErrors[fieldName]) {
          formattedErrors[fieldName] = issue.message;
        }
      });
      setFieldErrors(formattedErrors);
      return;
    }

    setIsSubmitting(true);
    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(parseResult.data),
      });

      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data?.error || "Failed to send inquiry email.");
      }

      setFormSubmitted(true);
      setTimeout(() => {
        setFormSubmitted(false);
        setFormData({
          name: "",
          email: "",
          phone: "",
          houseType: REQUIREMENT_OPTIONS[0] || "1BHK",
          customHouseType: "",
          message: "",
        });
      }, 4000);
    } catch (err: any) {
      console.error("Inquiry Error:", err);
      setServerError(err?.message || "Failed to dispatch email.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <section id="team" className="py-20 lg:py-28 bg-[#e9eae8] text-zinc-900 overflow-hidden">
      <div className="max-w-7xl mx-auto px-6 lg:px-12">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-start">
          
          {/* Left Column Team Carousel */}
          <motion.div 
            initial={{ opacity: 0, x: -20 }}
            whileInView={{ opacity: 1, x: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.3 }}
            className="lg:col-span-7 space-y-8"
          >
            <div className="flex items-center justify-between">
              <h2 className="text-4xl sm:text-5xl font-black font-serif tracking-tight text-zinc-900">
                Our Team
              </h2>

              {/* Slider Arrows */}
              <div className="flex items-center gap-2">
                <motion.button
                  whileTap={{ scale: 0.9 }}
                  onClick={handlePrev}
                  className="w-10 h-10 rounded-lg bg-white shadow flex items-center justify-center hover:bg-amber-600 hover:text-white transition duration-150"
                  aria-label="Previous Team Member"
                >
                  <ChevronLeft size={20} />
                </motion.button>
                <motion.button
                  whileTap={{ scale: 0.9 }}
                  onClick={handleNext}
                  className="w-10 h-10 rounded-lg bg-white shadow flex items-center justify-center hover:bg-amber-600 hover:text-white transition duration-150"
                  aria-label="Next Team Member"
                >
                  <ChevronRight size={20} />
                </motion.button>
              </div>
            </div>

            {/* Team Cards Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
              {TEAM_MEMBERS.slice(0, 2).map((member, idx) => (
                <motion.div 
                  key={idx}
                  whileHover={{ y: -4 }}
                  className="group relative h-[380px] rounded-2xl overflow-hidden shadow-lg bg-zinc-300 transition-shadow duration-200"
                >
                  <img
                    src={member.image}
                    alt={member.name}
                    className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                  />
                  {/* Bottom White Overlay Box */}
                  <div className="absolute bottom-6 inset-x-6 bg-white/95 backdrop-blur-sm p-5 text-center shadow-md rounded-xl">
                    <h3 className="text-base font-extrabold text-zinc-900 uppercase tracking-wider">
                      {member.name}
                    </h3>
                    <p className="text-xs text-zinc-500 italic mt-1 font-medium">
                      {member.role}
                    </p>
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>

          {/* Right Column Appointment Contact Form */}
          <motion.div 
            initial={{ opacity: 0, x: 20 }}
            whileInView={{ opacity: 1, x: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.3 }}
            className="lg:col-span-5 bg-white/70 backdrop-blur-md p-8 sm:p-10 rounded-2xl border border-zinc-300/80 shadow-xl"
          >
            <h3 className="text-2xl sm:text-3xl font-extrabold font-serif text-zinc-900 mb-6 leading-tight">
              Building Your Future. <br />
              <span className="text-[#c5a059]">Connect With Our Agent.</span>
            </h3>

            {serverError && (
              <div className="mb-4 p-3.5 bg-red-50 border border-red-200 text-red-700 text-xs rounded-xl flex items-center gap-2">
                <AlertCircle size={16} className="shrink-0" />
                <span>{serverError}</span>
              </div>
            )}

            {formSubmitted ? (
              <motion.div 
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.2 }}
                className="p-6 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl text-center space-y-3"
              >
                <CheckCircle2 size={40} className="mx-auto text-emerald-600" />
                <h4 className="font-bold text-lg font-serif">Inquiry Received!</h4>
                <p className="text-xs text-emerald-700 font-medium">
                  Thank you, {formData.name || "valued client"}. Our property agent will contact you shortly regarding your {formData.houseType === "Custom" ? (formData.customHouseType || "custom") : formData.houseType} requirement.
                </p>
              </motion.div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-5">
                <div>
                  <label className="block text-[11px] font-extrabold uppercase tracking-wider text-zinc-500 mb-1">
                    NAME
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => {
                      setFormData({ ...formData, name: e.target.value });
                      if (fieldErrors.name) setFieldErrors({ ...fieldErrors, name: "" });
                    }}
                    placeholder="Enter full name"
                    className={`w-full bg-transparent border-b ${
                      fieldErrors.name ? "border-red-500" : "border-zinc-400"
                    } py-2 text-sm font-semibold text-zinc-900 focus:outline-none focus:border-amber-600 transition`}
                  />
                  {fieldErrors.name && (
                    <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.name}</p>
                  )}
                </div>

                <div>
                  <label className="block text-[11px] font-extrabold uppercase tracking-wider text-zinc-500 mb-1">
                    PHONE NUMBER <span className="text-zinc-400 font-normal">(OPTIONAL)</span>
                  </label>
                  <input
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => {
                      setFormData({ ...formData, phone: e.target.value });
                      if (fieldErrors.phone) setFieldErrors({ ...fieldErrors, phone: "" });
                    }}
                    placeholder="Enter phone number"
                    className={`w-full bg-transparent border-b ${
                      fieldErrors.phone ? "border-red-500" : "border-zinc-400"
                    } py-2 text-sm font-semibold text-zinc-900 focus:outline-none focus:border-amber-600 transition`}
                  />
                  {fieldErrors.phone && (
                    <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.phone}</p>
                  )}
                </div>

                <div>
                  <label className="block text-[11px] font-extrabold uppercase tracking-wider text-zinc-500 mb-1">
                    EMAIL
                  </label>
                  <input
                    type="email"
                    value={formData.email}
                    onChange={(e) => {
                      setFormData({ ...formData, email: e.target.value });
                      if (fieldErrors.email) setFieldErrors({ ...fieldErrors, email: "" });
                    }}
                    placeholder="Enter email address"
                    className={`w-full bg-transparent border-b ${
                      fieldErrors.email ? "border-red-500" : "border-zinc-400"
                    } py-2 text-sm font-semibold text-zinc-900 focus:outline-none focus:border-amber-600 transition`}
                  />
                  {fieldErrors.email && (
                    <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.email}</p>
                  )}
                </div>

                <div>
                  <label className="block text-[11px] font-extrabold uppercase tracking-wider text-zinc-500 mb-1">
                    REQUIREMENT TYPE
                  </label>
                  <select
                    value={formData.houseType}
                    onChange={(e) => setFormData({ ...formData, houseType: e.target.value })}
                    className="w-full bg-transparent border-b border-zinc-400 py-2 text-sm font-semibold text-zinc-900 focus:outline-none focus:border-amber-600 transition cursor-pointer"
                  >
                    {REQUIREMENT_OPTIONS.map((opt) => (
                      <option key={opt} value={opt}>
                        {opt}
                      </option>
                    ))}
                  </select>
                </div>

                <AnimatePresence>
                  {formData.houseType === "Custom" && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: "auto" }}
                      exit={{ opacity: 0, height: 0 }}
                      transition={{ duration: 0.2 }}
                      className="overflow-hidden"
                    >
                      <label className="block text-[11px] font-extrabold uppercase tracking-wider text-zinc-500 mb-1 mt-2">
                        SPECIFY CUSTOM REQUIREMENT
                      </label>
                      <input
                        type="text"
                        value={formData.customHouseType}
                        onChange={(e) => setFormData({ ...formData, customHouseType: e.target.value })}
                        placeholder="Enter your custom requirement..."
                        className="w-full bg-transparent border-b border-zinc-400 py-2 text-sm font-semibold text-zinc-900 focus:outline-none focus:border-amber-600 transition"
                      />
                    </motion.div>
                  )}
                </AnimatePresence>

                <div>
                  <label className="block text-[11px] font-extrabold uppercase tracking-wider text-zinc-500 mb-1">
                    MESSAGE <span className="text-zinc-400 font-normal">(OPTIONAL)</span>
                  </label>
                  <textarea
                    rows={3}
                    value={formData.message}
                    onChange={(e) => {
                      setFormData({ ...formData, message: e.target.value });
                      if (fieldErrors.message) setFieldErrors({ ...fieldErrors, message: "" });
                    }}
                    placeholder="Enter your message..."
                    className={`w-full bg-transparent border-b ${
                      fieldErrors.message ? "border-red-500" : "border-zinc-400"
                    } py-2 text-sm font-semibold text-zinc-900 focus:outline-none focus:border-amber-600 transition resize-none`}
                  />
                  {fieldErrors.message && (
                    <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.message}</p>
                  )}
                </div>

                <motion.button
                  whileHover={{ scale: 1.01 }}
                  whileTap={{ scale: 0.98 }}
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full mt-4 bg-zinc-900 hover:bg-amber-600 disabled:opacity-60 disabled:cursor-not-allowed text-white font-extrabold text-xs uppercase tracking-widest py-3.5 border border-zinc-900 transition duration-200 shadow-md rounded-md flex items-center justify-center gap-2.5"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 size={16} className="animate-spin text-white" />
                      <span>SENDING INQUIRY...</span>
                    </>
                  ) : (
                    <span>SEND INQUIRY</span>
                  )}
                </motion.button>
              </form>
            )}
          </motion.div>

        </div>
      </div>
    </section>
  );
}
