"use client";

import { useEffect, useState } from "react";
import { Phone, Mail, MapPin, Clock, CheckCircle2, Loader2 } from "lucide-react";
import { formsApi } from "@/lib/api/forms";
import { ApiException } from "@/lib/api/client";
import { getSiteConfig, type SiteConfig } from "@/lib/api/site";
import { z } from "zod";
import { apiFieldErrors, emailField, fieldErrors as validate, mobileField, normalizeMobile } from "@/lib/validation";
import FieldError from "@/components/ui/FieldError";

/**
 * Mirrors ContactController: mobile required (it is how the team calls
 * back), email optional. The two disagreed before, so the email error only
 * appeared after submit (B20).
 */
const contactSchema = z.object({
  name: z.string().trim().min(1, "Enter your name"),
  mobile: mobileField(),
  email: emailField(false),
  message: z.string().trim().min(1, "Tell us how we can help"),
});

/** API field → form field. */
const CONTACT_API_FIELD: Record<string, string> = { name: "name", phone: "mobile", email: "email", message: "message" };
import { BRAND } from "@/lib/constants";

export default function ContactPage() {
  const [form, setForm] = useState({ name: "", company: "", mobile: "", email: "", message: "", enquiryType: "general" });
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [siteConfig, setSiteConfig] = useState<SiteConfig | null>(null);

  useEffect(() => {
    let active = true;

    getSiteConfig({ cache: "no-store" })
      .then((config) => {
        if (active) setSiteConfig(config);
      })
      .catch(() => {
        if (active) setSiteConfig(null);
      });

    return () => {
      active = false;
    };
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError(null);
    const clientErrors = validate(contactSchema, form) as Record<string, string>;
    setFieldErrors(clientErrors);
    if (Object.keys(clientErrors).length > 0) return;

    setLoading(true);
    try {
      const subjectLine = form.company
        ? `Enquiry type: ${form.enquiryType} | Company: ${form.company}\n\n`
        : `Enquiry type: ${form.enquiryType}\n\n`;
      await formsApi.contact({
        name: form.name.trim(),
        email: form.email.trim() || undefined,
        phone: normalizeMobile(form.mobile),
        message: subjectLine + form.message.trim(),
      });
      setSubmitted(true);
    } catch (err) {
      if (err instanceof ApiException) {
        // Field errors go under their field, once; the banner is only for
        // failures no field owns.
        const fe: Record<string, string> = {};
        for (const [k, v] of Object.entries(apiFieldErrors(err.errors))) {
          if (v) fe[CONTACT_API_FIELD[k] ?? k] = v;
        }
        setFieldErrors(fe);
        if (Object.keys(fe).length === 0) setFormError(err.message);
      } else {
        setFormError("Something went wrong. Please try again.");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-gradient-to-r from-[#CC1414] to-[#8B0000] text-white py-14">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <h1 className="text-3xl md:text-4xl font-black mb-3">Contact Us</h1>
          <p className="text-red-100">We&apos;re here to help you with procurement, pricing and business growth</p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-10">
          {/* Info */}
          <div className="space-y-5">
            <h2 className="text-xl font-black text-gray-900">Get In Touch</h2>
            {[
              {
                icon: Phone,
                label: "Phone",
                value: siteConfig?.phone ?? BRAND.phone,
                href: `tel:${(siteConfig?.phone ?? BRAND.phone).replace(/\s+/g, "")}`,
              },
              {
                icon: Mail,
                label: "Email",
                value: siteConfig?.email ?? BRAND.email,
                href: `mailto:${siteConfig?.email ?? BRAND.email}`,
              },
              { icon: MapPin, label: "Office", value: siteConfig?.address ?? BRAND.address },
              { icon: Clock, label: "Hours", value: "Mon-Sat: 9:00 AM – 7:00 PM IST" },
            ].map(({ icon: Icon, label, value, href }) => (
              <div key={label} className="flex items-start gap-4 bg-white rounded-xl p-4 border border-gray-100 shadow-sm">
                <div className="w-10 h-10 bg-red-50 rounded-lg flex items-center justify-center shrink-0">
                  <Icon size={18} className="text-[#CC1414]" />
                </div>
                <div>
                  <div className="text-xs text-gray-400 font-semibold uppercase tracking-wider">{label}</div>
                  {href ? (
                    <a href={href} className="text-sm font-semibold text-gray-900 hover:text-[#CC1414] transition-colors">{value}</a>
                  ) : (
                    <div className="text-sm font-semibold text-gray-900">{value}</div>
                  )}
                </div>
              </div>
            ))}

            {/* Enquiry types */}
            <div className="bg-white rounded-xl p-4 border border-gray-100 shadow-sm">
              <div className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">
                Enquiry Types
              </div>
              {["General Enquiries", "Supplier Enquiries", "Partner Enquiries", "Investor Relations"].map((type) => (
                <div key={type} className="flex items-center gap-2 text-sm text-gray-600 py-1.5">
                  <CheckCircle2 size={14} className="text-[#CC1414]" /> {type}
                </div>
              ))}
            </div>
          </div>

          {/* Form */}
          <div className="lg:col-span-2 bg-white rounded-2xl border border-gray-100 shadow-sm p-5 sm:p-8">
            {submitted ? (
              <div className="text-center py-12">
                <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <CheckCircle2 size={32} className="text-green-600" />
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">Message Sent!</h3>
                <p className="text-gray-500 text-sm">Our team will get back to you soon.</p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} noValidate className="space-y-5">
                <h3 className="text-xl font-bold text-gray-900 mb-2">Send Us a Message</h3>
                {formError && (
                  <div role="alert" className="rounded-lg bg-red-50 border border-red-100 px-4 py-2 text-sm text-red-700">
                    {formError}
                  </div>
                )}
                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Name *</label>
                    <input required type="text" placeholder="Your full name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
                      aria-invalid={!!fieldErrors.name} aria-describedby="contact-name-err"
                      className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]" />
                    <FieldError id="contact-name-err" message={fieldErrors.name} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Company</label>
                    <input type="text" placeholder="Company name" value={form.company} onChange={(e) => setForm({ ...form, company: e.target.value })}
                      className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]" />
                  </div>
                </div>
                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Mobile *</label>
                    <input required type="tel" inputMode="numeric" maxLength={10} placeholder="10-digit number" value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value.replace(/\D/g, "") })}
                      aria-invalid={!!fieldErrors.mobile} aria-describedby="contact-mobile-err"
                      className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]" />
                    <FieldError id="contact-mobile-err" message={fieldErrors.mobile} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Email <span className="normal-case font-normal text-gray-400">(optional)</span></label>
                    <input type="email" placeholder="Work email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}
                      aria-invalid={!!fieldErrors.email} aria-describedby="contact-email-err"
                      className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]" />
                    <FieldError id="contact-email-err" message={fieldErrors.email} />
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Enquiry Type</label>
                  <select value={form.enquiryType} onChange={(e) => setForm({ ...form, enquiryType: e.target.value })}
                    className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]">
                    <option value="general">General Enquiry</option>
                    <option value="supplier">Supplier Enquiry</option>
                    <option value="partner">Partner Enquiry</option>
                    <option value="investor">Investor Relations</option>
                    <option value="procurement">Procurement Request</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Message *</label>
                  <textarea required rows={4} placeholder="Describe your requirements or questions..."
                    value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })}
                    aria-invalid={!!fieldErrors.message} aria-describedby="contact-message-err"
                    className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 bg-white focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414] resize-none" />
                  <FieldError id="contact-message-err" message={fieldErrors.message} />
                </div>
                <button type="submit" disabled={loading}
                  className="w-full bg-[#CC1414] hover:bg-[#A50E0E] disabled:opacity-70 text-white font-bold py-3.5 rounded-xl transition-colors text-sm flex items-center justify-center gap-2 shadow-md">
                  {loading ? <><Loader2 size={16} className="animate-spin" /> Sending...</> : "Send Message →"}
                </button>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
