"use client";

import React, { useState } from "react";
import { OFFICES_DATA, OfficeBranch } from "@/data/portalData";
import { submitContactInquiry } from "@/services/inquiryService";
import {
  Building2,
  Phone,
  Mail,
  MapPin,
  Clock,
  MessageSquare,
  CheckCircle2,
  Send,
  Sparkles,
  ShieldCheck,
  Compass,
  AlertCircle,
  Loader2
} from "lucide-react";

export default function ContactPage() {
  const [selectedOffice, setSelectedOffice] = useState<OfficeBranch>(OFFICES_DATA[0]);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [interestType, setInterestType] = useState("Acquiring Luxury Property");
  const [message, setMessage] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);
    setIsSubmitting(true);

    try {
      const fullMessage = message.trim() 
        ? message.trim() 
        : `Customer expressed interest in: ${interestType} through our ${selectedOffice.name} office.`;

      const res = await submitContactInquiry({
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim(),
        subject: `${interestType} — ${selectedOffice.name}`,
        message: `${fullMessage}\n\n[Office: ${selectedOffice.name} | Interest: ${interestType}]`,
        office: selectedOffice.name,
        interest_type: interestType,
      });

      if (res.success) {
        setSubmitted(true);
      } else {
        setErrorMessage(res.message || "Unable to send inquiry. Please check your information.");
      }
    } catch (err: any) {
      setErrorMessage("Something went wrong while submitting. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleResetForm = () => {
    setName("");
    setEmail("");
    setPhone("");
    setMessage("");
    setSubmitted(false);
    setErrorMessage(null);
  };

  return (
    <div className="min-h-screen py-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-white">

      {/* Header */}
      <div className="mb-12 text-center max-w-3xl mx-auto space-y-4">
        <div className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-extrabold bg-[#0A0A0A] text-[#FFE259] border border-[#FFA726]/40">
          <Compass className="w-3.5 h-3.5 text-[#FFE259]" /> Central Head Office • Colombo District
        </div>
        <h1 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight font-display-lg">
          Contact Dream Homes <span className="text-[#FFE259]">Head Office</span>
        </h1>
        <p className="text-slate-400 text-sm sm:text-base leading-relaxed">
          Visit our headquarters in Thalawathugoda, Colombo for private consultations, property valuations, or send an inquiry to our advisory team.
        </p>
      </div>

      {/* 2-Column: Form + Office Details */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-start mb-16">

        {/* Contact Form (6 cols) */}
        <div className="lg:col-span-6 bg-[#0e0e10] rounded-3xl border border-[#FFE259]/30 text-white p-8 shadow-xl space-y-6">
          <div>
            <span className="text-xs font-bold uppercase tracking-wider text-[#FFE259]">
              Direct Inquiries
            </span>
            <h2 className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight font-display-lg">
              Send a Confidential Brief
            </h2>
            <p className="text-xs text-slate-400 mt-1">
              Our Senior Partners respond within 2 hours during business hours.
            </p>
          </div>

          {errorMessage && (
            <div className="p-4 bg-rose-50 border border-rose-200 rounded-2xl flex items-center gap-2.5 text-xs text-rose-700 font-semibold animate-in fade-in duration-150">
              <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
              <span>{errorMessage}</span>
            </div>
          )}

          {submitted ? (
            <div className="p-8 bg-[#18181b] border border-[#059669]/40 rounded-3xl text-center space-y-3">
              <div className="w-14 h-14 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>
              <h3 className="text-xl font-bold text-white font-display-lg">Brief Received!</h3>
              <p className="text-xs text-slate-300">
                Thank you <strong>{name}</strong>. A Senior Property Advisor from our <strong>{selectedOffice.name}</strong> will contact you at <strong>{phone || email}</strong> shortly.
              </p>
              <div className="p-3 bg-white/80 rounded-2xl border border-emerald-200 text-[11px] text-slate-600 text-left space-y-0.5">
                <p><strong>Tracking Ref:</strong> DH-INQ-{Math.floor(100000 + Math.random() * 900000)}</p>
                <p><strong>Department:</strong> Client Support &amp; Sales Advisory</p>
                <p><strong>Branch:</strong> {selectedOffice.name}</p>
              </div>
              <button
                onClick={() => setSubmitted(false)}
                className="mt-2 bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold px-6 py-2.5 rounded-full cursor-pointer transition-all"
              >
                Send Another Inquiry
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Full Name *</label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. Ruwan Jayasuriya"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#FFE259] transition-colors"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Email Address *</label>
                  <input
                    type="email"
                    required
                    placeholder="ruwan@example.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#FFE259] transition-colors"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Mobile / WhatsApp *</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 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#FFE259] transition-colors"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Preferred Office</label>
                  <select
                    value={selectedOffice.name}
                    onChange={(e) => {
                      const off = OFFICES_DATA.find((o) => o.name === e.target.value);
                      if (off) setSelectedOffice(off);
                    }}
                    className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#FFE259] transition-colors cursor-pointer"
                  >
                    {OFFICES_DATA.map((o) => (
                      <option key={o.name} value={o.name}>{o.name}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Primary Area of Interest</label>
                <select
                  value={interestType}
                  onChange={(e) => setInterestType(e.target.value)}
                  className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#FFE259] transition-colors cursor-pointer"
                >
                  <option>Acquiring Luxury Property (Houses / Lands / Apartments)</option>
                  <option>Listing &amp; Selling a Prime Property</option>
                  <option>Turnkey Custom Architectural Construction</option>
                  <option>House Plans &amp; Blueprint Orders</option>
                  <option>Institutional Off-Plan Project Investment</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Brief Requirements / Notes</label>
                <textarea
                  rows={3}
                  placeholder="Specify location, approximate budget, or timeline..."
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#FFE259] transition-colors"
                />
              </div>

              <button
                type="submit"
                className="w-full bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs uppercase tracking-wider py-4 rounded-full shadow-lg shadow-[#059669]/25 transition-all flex items-center justify-center gap-2 cursor-pointer"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin text-white" />
                    <span>Transmitting Inquiry to Support...</span>
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4" />
                    <span>Submit Confidential Inquiry</span>
                  </>
                )}
              </button>
            </form>
          )}
        </div>

        {/* Selected Office Spotlight & Map Simulation (6 cols) */}
        <div className="lg:col-span-6 space-y-6">
          <div className="bg-[#0e0e10] rounded-3xl overflow-hidden shadow-2xl border border-[#FFE259]/30 text-white">
            <div className="relative aspect-[16/9] bg-zinc-900 overflow-hidden">
              <img
                src={selectedOffice.image}
                alt={selectedOffice.name}
                className="w-full h-full object-cover opacity-85"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-[#0e0e10] via-[#0e0e10]/30 to-transparent" />
              <div className="absolute top-4 left-4 px-3 py-1 rounded-full text-xs font-bold bg-[#059669] text-white shadow-md">
                {selectedOffice.type}
              </div>
              <div className="absolute bottom-4 left-4 right-4">
                <h3 className="text-2xl font-bold font-display-lg text-white">{selectedOffice.name}</h3>
                <p className="text-xs text-slate-300 flex items-center gap-1.5 mt-1">
                  <MapPin className="w-3.5 h-3.5 text-[#FFE259] shrink-0" />
                  <span>{selectedOffice.address}</span>
                </p>
              </div>
            </div>

            <div className="p-6 space-y-4 text-xs">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div className="p-3.5 bg-[#18181b] rounded-2xl border border-zinc-800 space-y-0.5">
                  <span className="text-slate-400 block text-[10px] uppercase font-semibold">Direct Telephone</span>
                  <strong className="text-[#FFE259] text-sm block">{selectedOffice.phone}</strong>
                </div>
                <div className="p-3.5 bg-[#18181b] rounded-2xl border border-zinc-800 space-y-0.5">
                  <span className="text-slate-400 block text-[10px] uppercase font-semibold">Email Desk</span>
                  <strong className="text-white text-sm block">{selectedOffice.email}</strong>
                </div>
              </div>

              <div className="flex items-center gap-2 text-slate-300 pt-1">
                <Clock className="w-4 h-4 text-[#FFE259] shrink-0" />
                <span>Gallery Hours: <strong className="text-white">{selectedOffice.hours}</strong></span>
              </div>

              <div className="pt-2 flex gap-3">
                <a
                  href={`tel:${selectedOffice.phone.replace(/[^0-9+]/g, '')}`}
                  className="flex-1 py-3 rounded-full bg-[#18181b] hover:bg-zinc-800 text-[#FFE259] border border-[#FFE259]/40 font-bold text-xs text-center transition-all flex items-center justify-center gap-1.5 shadow-sm cursor-pointer"
                >
                  <Phone className="w-3.5 h-3.5 text-[#FFE259]" />
                  <span>Call Reception</span>
                </a>
                <a
                  href="https://wa.me/+94774446063"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex-1 py-3 rounded-full bg-[#059669] hover:bg-[#047857] text-white font-bold text-xs text-center transition-all flex items-center justify-center gap-1.5 shadow-lg shadow-[#059669]/25 cursor-pointer"
                >
                  <MessageSquare className="w-3.5 h-3.5" />
                  <span>WhatsApp Concierge</span>
                </a>
              </div>
            </div>
          </div>

          {/* Quick Office Switcher Pills (If multiple offices) */}
          {OFFICES_DATA.length > 1 && (
            <div className="grid grid-cols-2 gap-2">
              {OFFICES_DATA.map((office) => (
                <button
                  key={office.name}
                  onClick={() => setSelectedOffice(office)}
                  className={`p-3 rounded-2xl text-left border text-xs font-bold transition-all cursor-pointer ${selectedOffice.name === office.name
                      ? "bg-[#059669] text-white border-[#059669] shadow-md"
                      : "bg-[#18181b] text-slate-300 border-zinc-700 hover:bg-zinc-800"
                    }`}
                >
                  <span className="block truncate">{office.name}</span>
                  <span className={`text-[10px] block mt-0.5 ${selectedOffice.name === office.name ? "text-slate-200" : "text-slate-400"
                    }`}>
                    {office.city}
                  </span>
                </button>
              ))}
            </div>
          )}

        </div>

      </div>

    </div>
  );
}