"use client";

import React, { useState, useEffect } from "react";
import { X, CheckCircle2, Send, Building2, ShieldCheck, User, Loader2 } from "lucide-react";
import { useAuth } from "@/context/AuthContext";
import { contactPropertyAgent } from "@/services/inquiryService";

interface AgentContactModalProps {
  isOpen: boolean;
  onClose: () => void;
  agent: {
    id?: string | number;
    name: string;
    image?: string;
    role?: string;
    division?: string;
  };
  propertyTitle?: string;
  propertyId?: string | number;
}

export default function AgentContactModal({
  isOpen,
  onClose,
  agent,
  propertyTitle,
  propertyId
}: AgentContactModalProps) {
  const { user, isLoggedIn } = useAuth();
  
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [message, setMessage] = useState(
    propertyTitle 
      ? `Hi ${agent.name}, I am interested in inquiring about "${propertyTitle}". Please get in touch with me with further details.`
      : `Hi ${agent.name}, I would like to get in touch regarding real estate opportunities in your represented areas.`
  );
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (user?.name) {
      const parts = user.name.trim().split(" ");
      setFirstName(parts[0] || "");
      setLastName(parts.slice(1).join(" ") || "");
    }
    if (user?.email) setEmail(user.email);
    if (user?.phone) setPhone(user.phone);
  }, [user, isOpen]);

  if (!isOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    const fullName = `${firstName.trim()} ${lastName.trim()}`.trim() || "Interested Buyer";
    const token = typeof window !== "undefined" ? localStorage.getItem("customer_token") : null;
    
    await contactPropertyAgent(
      String(propertyId || "general"),
      {
        name: fullName,
        email: email.trim(),
        phone: phone.trim(),
        message: message.trim(),
        agent_id: agent.id,
        agent_name: agent.name,
      },
      token
    );

    setIsSubmitting(false);
    setSubmitted(true);
  };

  const handleClose = () => {
    setSubmitted(false);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md animate-in fade-in duration-200">
      <div 
        className="bg-[#0e0e10] rounded-3xl max-w-lg w-full overflow-hidden shadow-2xl border border-[#FFE259]/30 animate-in zoom-in-95 duration-200 relative text-white"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header with Agent Info */}
        <div className="bg-[#0A0A0A] p-6 text-white relative border-b border-zinc-800">
          <button
            onClick={handleClose}
            className="absolute top-4 right-4 p-2 rounded-full bg-white/10 hover:bg-white/20 text-slate-300 hover:text-white transition-colors cursor-pointer"
            aria-label="Close"
          >
            <X className="w-5 h-5" />
          </button>

          <div className="flex items-center gap-4 pr-8">
            {agent.image && (
              <img
                src={agent.image}
                alt={agent.name}
                className="w-14 h-14 rounded-full object-cover border-2 border-[#FFE259]/40 shadow-md shrink-0"
              />
            )}
            <div>
              <span className="text-[10px] font-extrabold uppercase tracking-widest text-[#FFE259] bg-white/5 border border-[#FFE259]/30 px-2.5 py-0.5 rounded-full inline-block mb-1">
                Direct Inquiry
              </span>
              <h3 className="text-lg font-extrabold font-display-lg text-white">
                Contact {agent.name}
              </h3>
              <p className="text-xs text-slate-400">
                {agent.role || "DreamHomes Real Estate Specialist"} • {agent.division || "DreamHomes Realty"}
              </p>
            </div>
          </div>
        </div>

        {/* Content Body */}
        <div className="p-6 sm:p-8">
          {submitted ? (
            <div className="text-center py-6 space-y-4">
              <div className="w-16 h-16 rounded-full bg-[#059669]/20 text-[#10b981] border border-[#059669]/40 flex items-center justify-center mx-auto shadow-inner">
                <CheckCircle2 className="w-8 h-8" />
              </div>
              <div className="space-y-1 max-w-sm mx-auto">
                <h4 className="text-xl font-extrabold text-white font-display-lg">
                  Inquiry Dispatched Successfully!
                </h4>
                <p className="text-xs sm:text-sm text-slate-300">
                  Thank you, <strong>{firstName || "Customer"}</strong>. Your message has been forwarded directly to <strong>{agent.name}</strong>. You will receive a call/message shortly.
                </p>
              </div>

              <div className="pt-3">
                <button
                  type="button"
                  onClick={handleClose}
                  className="bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs px-6 py-3 rounded-full shadow-md transition-all cursor-pointer"
                >
                  Done &amp; Close
                </button>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4">
              
              {propertyTitle && (
                <div className="p-3 bg-[#18181b] border border-[#FFE259]/20 rounded-2xl text-xs text-slate-300 font-semibold">
                  <span className="text-slate-400 font-normal block text-[11px]">Inquiring about property:</span>
                  <span className="text-[#FFE259] font-bold line-clamp-1">{propertyTitle}</span>
                </div>
              )}

              {/* Name Row: First & Last Name */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div className="space-y-1">
                  <label className="text-xs font-semibold text-slate-300 block">
                    First Name *
                  </label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. Sarath"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 focus:border-[#FFE259] px-3.5 py-2.5 rounded-xl text-xs sm:text-sm text-white outline-none transition-all"
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-xs font-semibold text-slate-300 block">
                    Last Name *
                  </label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. Wijesinghe"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 focus:border-[#FFE259] px-3.5 py-2.5 rounded-xl text-xs sm:text-sm text-white outline-none transition-all"
                  />
                </div>
              </div>

              {/* Email & Contact Number */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div className="space-y-1">
                  <label className="text-xs font-semibold text-slate-300 block">
                    Email Address *
                  </label>
                  <input
                    type="email"
                    required
                    placeholder="hello@example.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 focus:border-[#FFE259] px-3.5 py-2.5 rounded-xl text-xs sm:text-sm text-white outline-none transition-all"
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-xs font-semibold text-slate-300 block">
                    Contact Number *
                  </label>
                  <input
                    type="tel"
                    required
                    placeholder="+94 77 123 4567"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 focus:border-[#FFE259] px-3.5 py-2.5 rounded-xl text-xs sm:text-sm text-white outline-none transition-all"
                  />
                </div>
              </div>

              {/* Message Feedback */}
              <div className="space-y-1">
                <label className="text-xs font-semibold text-slate-300 block">
                  Your Message
                </label>
                <textarea
                  rows={3}
                  required
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  className="w-full bg-[#18181b] border border-zinc-700 focus:border-[#FFE259] px-3.5 py-2.5 rounded-xl text-xs sm:text-sm text-white outline-none transition-all"
                />
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                className="w-full bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs sm:text-sm py-3.5 rounded-full shadow-lg shadow-[#059669]/25 transition-all flex items-center justify-center gap-2 cursor-pointer mt-2"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin text-white" />
                    <span>Transmitting to Support...</span>
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4" />
                    <span>Submit Inquiry to {agent.name.split(" ")[0]}</span>
                  </>
                )}
              </button>

              <p className="text-center text-[11px] text-slate-400">
                🔒 Privacy Protected: Your contact information is kept confidential and sent directly to the agent.
              </p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
