"use client";

import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { X, Search, ChevronLeft, ChevronRight, Download, CheckCircle, Shield, AlertCircle, Loader2 } from "lucide-react";
import { PEXELS_FALLBACKS } from "@/lib/pexels";
import { REQUIREMENT_OPTIONS, GALLERY_CONTENT } from "@/config/siteContent";
import { inquirySchema } from "@/lib/inquirySchema";

interface ModalsProps {
  // Search
  searchOpen: boolean;
  onCloseSearch: () => void;

  // Schedule Visit
  scheduleOpen: boolean;
  onCloseSchedule: () => void;
  onOpenSchedule: () => void;

  // Video
  videoOpen: boolean;
  onCloseVideo: () => void;

  // Image Lightbox
  lightboxOpen: boolean;
  lightboxIndex: number;
  onCloseLightbox: () => void;
  onNavigateLightbox?: (index: number) => void;
  lightboxPhotos?: Array<{ title: string; image: string }>;

  // PDF Viewer
  pdfOpen: boolean;
  pdfTitle: string;
  onClosePdf: () => void;

  // Sale Modal (Optional)
  saleModalOpen?: boolean;
  onCloseSaleModal?: () => void;
  onOpenSaleModal?: () => void;
}

export default function Modals({
  searchOpen,
  onCloseSearch,
  scheduleOpen,
  onCloseSchedule,
  videoOpen,
  onCloseVideo,
  lightboxOpen,
  lightboxIndex,
  onCloseLightbox,
  onNavigateLightbox,
  lightboxPhotos,
  pdfOpen,
  pdfTitle,
  onClosePdf,
  saleModalOpen,
  onCloseSaleModal,
  onOpenSaleModal,
}: ModalsProps) {
  // Search state
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState<Array<any>>([]);
  const [isSearching, setIsSearching] = useState(false);

  // Active Lightbox index & Photos list
  const [currentPhotoIdx, setCurrentPhotoIdx] = useState(lightboxIndex);
  const photosList = lightboxPhotos && lightboxPhotos.length > 0 ? lightboxPhotos : GALLERY_CONTENT.categoryPhotos.ALL;

  // Update lightbox photo index on change
  React.useEffect(() => {
    setCurrentPhotoIdx(lightboxIndex);
  }, [lightboxIndex]);

  // Schedule state & Zod Validation
  const [scheduleSent, setScheduleSent] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

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

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

    // Client-side Zod validation
    const parseResult = inquirySchema.safeParse(scheduleData);
    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.");
      }

      setScheduleSent(true);
      setScheduleData({
        name: "",
        phone: "",
        email: "",
        houseType: REQUIREMENT_OPTIONS[0] || "1BHK",
        customHouseType: "",
        message: "",
      });
    } catch (err: any) {
      console.error("Inquiry Submission Error:", err);
      setServerError(err?.message || "Failed to connect to email service.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const backdropVariants = {
    hidden: { opacity: 0 },
    visible: { opacity: 1 },
  };

  const modalVariants = {
    hidden: { opacity: 0, scale: 0.96, y: 15 },
    visible: { opacity: 1, scale: 1, y: 0 },
  };

  return (
    <>
      {/* 1. SEARCH MODAL */}
      <AnimatePresence>
        {searchOpen && (
          <motion.div
            variants={backdropVariants}
            initial="hidden"
            animate="visible"
            exit="hidden"
            onClick={onCloseSearch}
            className="fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-start justify-center pt-20 px-4"
          >
            <motion.div
              variants={modalVariants}
              onClick={(e) => e.stopPropagation()}
              className="bg-zinc-900 border border-zinc-800 text-white w-full max-w-2xl rounded-2xl p-6 shadow-2xl relative"
            >
              <button
                onClick={onCloseSearch}
                className="absolute top-6 right-6 text-zinc-400 hover:text-white transition"
              >
                <X size={20} />
              </button>

              <h3 className="text-lg font-bold mb-4 flex items-center gap-2 font-serif">
                <Search size={18} className="text-[#c5a059]" />
                Search Property Portfolio
              </h3>

              <div className="flex gap-2 mb-6">
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && searchQuery) {
                      setIsSearching(true);
                      setTimeout(() => {
                        setIsSearching(false);
                        setSearchResults([
                          { title: "TRICITY Master Penthouse Suite", category: "BEDROOM", img: PEXELS_FALLBACKS.galleryBedroom },
                          { title: "Infinity Pool Ocean Deck", category: "GARDEN", img: PEXELS_FALLBACKS.amenitiesPool },
                          { title: "Subterranean Wine Lounge", category: "BASEMENT", img: PEXELS_FALLBACKS.galleryBasement },
                        ]);
                      }, 500);
                    }
                  }}
                  placeholder="Enter location, room type, or requirement..."
                  className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-4 py-3 text-sm focus:outline-none focus:border-[#c5a059] text-white"
                />
                <button
                  onClick={() => {
                    if (!searchQuery) return;
                    setIsSearching(true);
                    setTimeout(() => {
                      setIsSearching(false);
                      setSearchResults([
                        { title: "TRICITY Master Penthouse Suite", category: "BEDROOM", img: PEXELS_FALLBACKS.galleryBedroom },
                        { title: "Infinity Pool Ocean Deck", category: "GARDEN", img: PEXELS_FALLBACKS.amenitiesPool },
                        { title: "Subterranean Wine Lounge", category: "BASEMENT", img: PEXELS_FALLBACKS.galleryBasement },
                      ]);
                    }, 500);
                  }}
                  className="bg-[#c5a059] hover:bg-amber-600 text-white font-bold text-xs uppercase px-6 py-3 rounded-lg transition flex items-center gap-2 shrink-0"
                >
                  {isSearching ? <Loader2 size={16} className="animate-spin" /> : null}
                  Search
                </button>
              </div>

              {isSearching && (
                <div className="py-12 text-center text-zinc-400 text-sm flex flex-col items-center gap-3">
                  <Loader2 size={28} className="animate-spin text-[#c5a059]" />
                  <span className="font-medium">Searching Pexels & Portfolio...</span>
                </div>
              )}

              {searchResults.length > 0 && !isSearching && (
                <div className="space-y-3 max-h-64 overflow-y-auto pr-2">
                  {searchResults.map((item, idx) => (
                    <div key={idx} className="flex items-center gap-4 bg-zinc-800/60 p-3 rounded-xl border border-zinc-700/50 hover:border-[#c5a059] transition cursor-pointer">
                      <img src={item.img} alt={item.title} className="w-14 h-14 object-cover rounded-lg" />
                      <div>
                        <span className="text-[10px] font-bold text-[#c5a059] uppercase tracking-wider">{item.category}</span>
                        <h4 className="text-sm font-bold text-white">{item.title}</h4>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 2. SCHEDULE VISIT MODAL */}
      <AnimatePresence>
        {scheduleOpen && (
          <motion.div
            variants={backdropVariants}
            initial="hidden"
            animate="visible"
            exit="hidden"
            onClick={onCloseSchedule}
            className="fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-center justify-center p-4"
          >
            <motion.div
              variants={modalVariants}
              onClick={(e) => e.stopPropagation()}
              className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-white w-full max-w-md rounded-2xl p-6 sm:p-8 shadow-2xl relative"
            >
              <button
                onClick={onCloseSchedule}
                className="absolute top-6 right-6 text-zinc-400 hover:text-zinc-600 dark:hover:text-white transition"
              >
                <X size={20} />
              </button>

              {scheduleSent ? (
                <div className="text-center py-6 space-y-4">
                  <CheckCircle size={56} className="mx-auto text-emerald-500" />
                  <h3 className="text-2xl font-bold font-serif">Inquiry Dispatched!</h3>
                  <p className="text-xs text-zinc-500 leading-relaxed max-w-xs mx-auto">
                    Thank you. Our luxury property manager will contact you shortly to confirm your requirement details.
                  </p>
                  <button
                    onClick={() => {
                      setScheduleSent(false);
                      onCloseSchedule();
                    }}
                    className="mt-4 bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 font-bold text-xs uppercase tracking-wider px-6 py-3 rounded-lg shadow transition"
                  >
                    Close Window
                  </button>
                </div>
              ) : (
                <div>
                  <h3 className="text-2xl font-black font-serif text-zinc-900 dark:text-white mb-2">
                    Property Inquiry
                  </h3>
                  <p className="text-xs text-zinc-500 mb-6">
                    Get details & schedule an exclusive viewing with our lead agent.
                  </p>

                  {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>
                  )}

                  <form onSubmit={handleScheduleSubmit} className="space-y-4">
                    <div>
                      <label className="block text-xs font-bold uppercase text-zinc-500 mb-1">Full Name</label>
                      <input
                        type="text"
                        value={scheduleData.name}
                        onChange={(e) => {
                          setScheduleData({ ...scheduleData, name: e.target.value });
                          if (fieldErrors.name) setFieldErrors({ ...fieldErrors, name: "" });
                        }}
                        placeholder="Enter full name"
                        className={`w-full px-4 py-2.5 bg-zinc-100 dark:bg-zinc-800 border ${
                          fieldErrors.name ? "border-red-500" : "border-zinc-200 dark:border-zinc-700"
                        } rounded-lg text-sm focus:outline-none focus:border-amber-500 dark:text-white`}
                      />
                      {fieldErrors.name && (
                        <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.name}</p>
                      )}
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase text-zinc-500 mb-1">
                        Phone Number <span className="text-zinc-400 font-normal">(Optional)</span>
                      </label>
                      <input
                        type="tel"
                        value={scheduleData.phone}
                        onChange={(e) => {
                          setScheduleData({ ...scheduleData, phone: e.target.value });
                          if (fieldErrors.phone) setFieldErrors({ ...fieldErrors, phone: "" });
                        }}
                        placeholder="Enter phone number"
                        className={`w-full px-4 py-2.5 bg-zinc-100 dark:bg-zinc-800 border ${
                          fieldErrors.phone ? "border-red-500" : "border-zinc-200 dark:border-zinc-700"
                        } rounded-lg text-sm focus:outline-none focus:border-amber-500 dark:text-white`}
                      />
                      {fieldErrors.phone && (
                        <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.phone}</p>
                      )}
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase text-zinc-500 mb-1">Email Address</label>
                      <input
                        type="email"
                        value={scheduleData.email}
                        onChange={(e) => {
                          setScheduleData({ ...scheduleData, email: e.target.value });
                          if (fieldErrors.email) setFieldErrors({ ...fieldErrors, email: "" });
                        }}
                        placeholder="Enter email address"
                        className={`w-full px-4 py-2.5 bg-zinc-100 dark:bg-zinc-800 border ${
                          fieldErrors.email ? "border-red-500" : "border-zinc-200 dark:border-zinc-700"
                        } rounded-lg text-sm focus:outline-none focus:border-amber-500 dark:text-white`}
                      />
                      {fieldErrors.email && (
                        <p className="text-[11px] text-red-500 font-medium mt-1">{fieldErrors.email}</p>
                      )}
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase text-zinc-500 mb-1">Requirement Type</label>
                      <select
                        value={scheduleData.houseType}
                        onChange={(e) => setScheduleData({ ...scheduleData, houseType: e.target.value })}
                        className="w-full px-4 py-2.5 bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg text-sm focus:outline-none focus:border-amber-500 dark:text-white cursor-pointer font-medium"
                      >
                        {REQUIREMENT_OPTIONS.map((opt) => (
                          <option key={opt} value={opt}>
                            {opt}
                          </option>
                        ))}
                      </select>
                    </div>

                    <AnimatePresence>
                      {scheduleData.houseType === "Custom" && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: "auto" }}
                          exit={{ opacity: 0, height: 0 }}
                          className="overflow-hidden"
                        >
                          <label className="block text-xs font-bold uppercase text-zinc-500 mb-1">Specify Custom Requirement</label>
                          <input
                            type="text"
                            value={scheduleData.customHouseType}
                            onChange={(e) => setScheduleData({ ...scheduleData, customHouseType: e.target.value })}
                            placeholder="Enter custom requirement..."
                            className="w-full px-4 py-2.5 bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg text-sm focus:outline-none focus:border-amber-500 dark:text-white"
                          />
                        </motion.div>
                      )}
                    </AnimatePresence>

                    <div>
                      <label className="block text-xs font-bold uppercase text-zinc-500 mb-1">
                        Message <span className="text-zinc-400 font-normal">(Optional)</span>
                      </label>
                      <textarea
                        rows={3}
                        value={scheduleData.message}
                        onChange={(e) => {
                          setScheduleData({ ...scheduleData, message: e.target.value });
                          if (fieldErrors.message) setFieldErrors({ ...fieldErrors, message: "" });
                        }}
                        placeholder="Enter your message..."
                        className={`w-full px-4 py-2.5 bg-zinc-100 dark:bg-zinc-800 border ${
                          fieldErrors.message ? "border-red-500" : "border-zinc-200 dark:border-zinc-700"
                        } rounded-lg text-sm focus:outline-none focus:border-amber-500 dark:text-white 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-amber-600 hover:bg-amber-700 disabled:opacity-60 disabled:cursor-not-allowed text-white font-extrabold text-xs uppercase tracking-widest py-3.5 rounded-lg transition shadow-lg 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>
                </div>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 3. LIGHTBOX MODAL */}
      <AnimatePresence>
        {lightboxOpen && (
          <motion.div
            variants={backdropVariants}
            initial="hidden"
            animate="visible"
            exit="hidden"
            onClick={onCloseLightbox}
            className="fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-4"
          >
            <button
              onClick={onCloseLightbox}
              className="absolute top-6 right-6 text-white/80 hover:text-white bg-white/10 p-3 rounded-full transition z-10"
            >
              <X size={24} />
            </button>

            <button
              onClick={(e) => {
                e.stopPropagation();
                const nextIdx = currentPhotoIdx === 0 ? photosList.length - 1 : currentPhotoIdx - 1;
                setCurrentPhotoIdx(nextIdx);
                onNavigateLightbox?.(nextIdx);
              }}
              className="absolute left-6 text-white/80 hover:text-white bg-white/10 p-3 rounded-full transition z-10"
            >
              <ChevronLeft size={24} />
            </button>

            <button
              onClick={(e) => {
                e.stopPropagation();
                const nextIdx = currentPhotoIdx === photosList.length - 1 ? 0 : currentPhotoIdx + 1;
                setCurrentPhotoIdx(nextIdx);
                onNavigateLightbox?.(nextIdx);
              }}
              className="absolute right-6 text-white/80 hover:text-white bg-white/10 p-3 rounded-full transition z-10"
            >
              <ChevronRight size={24} />
            </button>

            <div onClick={(e) => e.stopPropagation()} className="max-w-4xl max-h-[85vh] relative text-center">
              <img
                src={photosList[currentPhotoIdx]?.image}
                alt={photosList[currentPhotoIdx]?.title}
                className="max-w-full max-h-[75vh] object-contain mx-auto rounded-lg shadow-2xl"
              />
              <p className="text-white text-sm font-bold mt-4 tracking-wider uppercase">
                {photosList[currentPhotoIdx]?.title}
              </p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 4. PDF VIEWER MODAL */}
      <AnimatePresence>
        {pdfOpen && (
          <motion.div
            variants={backdropVariants}
            initial="hidden"
            animate="visible"
            exit="hidden"
            onClick={onClosePdf}
            className="fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-center justify-center p-4"
          >
            <motion.div
              variants={modalVariants}
              onClick={(e) => e.stopPropagation()}
              className="bg-zinc-900 border border-zinc-800 text-white w-full max-w-3xl h-[80vh] rounded-2xl p-6 shadow-2xl relative flex flex-col"
            >
              <div className="flex items-center justify-between pb-4 border-b border-zinc-800">
                <h3 className="text-base font-bold flex items-center gap-2 font-serif">
                  <Download size={18} className="text-[#c5a059]" />
                  {pdfTitle}
                </h3>
                <button onClick={onClosePdf} className="text-zinc-400 hover:text-white transition">
                  <X size={20} />
                </button>
              </div>

              <div className="grow my-4 bg-zinc-950 rounded-xl p-8 flex flex-col items-center justify-center text-center space-y-4 border border-zinc-800">
                <Shield size={48} className="text-[#c5a059]" />
                <h4 className="text-lg font-bold text-white font-serif">Verified TRICITY Document</h4>
                <p className="text-xs text-zinc-400 max-w-md">
                  Official certified documentation for {pdfTitle}. Standard architectural specification verified by TRICITY Management.
                </p>
                <a
                  href="/images/hero_luxury_villa.jpg"
                  download={pdfTitle}
                  className="bg-[#c5a059] hover:bg-amber-600 text-white font-bold text-xs uppercase tracking-widest px-6 py-3 rounded-lg transition shadow-lg"
                >
                  Download Complete Document
                </a>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
