import { useState } from "react";
import { CheckCircle2, Loader2, Lock, Send, Upload } from "lucide-react";
import { submitEnquiry } from "../lib/api";
import { SOLUTIONS } from "../data/solutions";
import { INDUSTRIES } from "../data/site";

const REQUIREMENTS = [
  "New infrastructure / upgrade", "Security assessment", "Cloud migration", "Managed IT services",
  "Software / digital engineering", "Technology procurement", "Consultation / other",
];

const SOLUTION_OPTIONS = [...SOLUTIONS.map((s) => s.shortTitle), "Digital Engineering", "Not sure yet"];

const inputCls =
  "w-full bg-transparent border-b border-[#C9D2DE] text-[#14151A] placeholder:text-[#14151A]/30 text-sm px-0 py-3 outline-none focus:border-ember transition-colors rounded-none";
const labelCls = "block text-[11px] font-tech tracking-[0.22em] text-[#0089A1] mb-2 uppercase";
const sectionCls = "sm:col-span-2 flex items-center gap-3 pt-2 font-tech text-[11px] tracking-[0.28em] text-[#14151A]/45";

const EMPTY = { name: "", company: "", email: "", phone: "", industry: "", requirement: "", solutionInterested: "", message: "", attachmentName: "", attachmentData: "", website: "" };

export default function EnquiryForm() {
  const [form, setForm] = useState({ ...EMPTY });
  const [picked, setPicked] = useState<string[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [status, setStatus] = useState("idle");
  const [ref, setRef] = useState<string | null>(null);

  const onAttach = (e) => {
    const file = e.target.files?.[0];
    if (!file || file.size > 3 * 1024 * 1024) return;
    const reader = new FileReader();
    reader.onload = () => setForm((f) => ({ ...f, attachmentName: file.name, attachmentData: String(reader.result) }));
    reader.readAsDataURL(file);
  };

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const toggleSolution = (s) => {
    setPicked((prev) => {
      const next = prev.includes(s) ? prev.filter((x) => x !== s) : [...prev, s];
      setForm((f) => ({ ...f, solutionInterested: next.join(", ") }));
      return next;
    });
  };

  const validate = () => {
    const e: Record<string, string> = {};
    if (form.name.trim().length < 2) e.name = "Please enter your name";
    if (form.company.trim().length < 2) e.company = "Please enter your company name";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Enter a valid business email";
    if (form.phone.replace(/\D/g, "").length < 8) e.phone = "Enter a valid phone number";
    if (!form.industry) e.industry = "Select your industry";
    if (picked.length === 0) e.solutionInterested = "Select at least one solution";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setStatus("loading");
    try {
      const res = await submitEnquiry({ ...form, solution_interested: form.solutionInterested, attachment_name: form.attachmentName, attachment_data: form.attachmentData });
      setRef(res?.reference || null);
      setStatus("success");
    } catch (err) {
      setStatus("error");
    }
  };

  if (status === "success") {
    return (
      <div className="border border-cy/40 bg-cy/5 p-10 text-center rounded-md" data-testid="enquiry-success">
        <CheckCircle2 size={44} className="text-[#0089A1] mx-auto" />
        <h3 className="font-display font-black text-2xl text-[#101828] mt-5">Enquiry received.</h3>
        {ref && <p className="mt-3 inline-block border border-cydeep/30 bg-white px-4 py-2 font-tech text-sm text-[#101828]" data-testid="enquiry-reference">REFERENCE: <b>{ref}</b></p>}
        <p className="text-mist/70 text-sm mt-3 max-w-sm mx-auto leading-relaxed">
          Thank you — your query is registered and our consulting team will respond within one business day. A thank-you email from connect@aviokan.com with our company profile (PDF) is on its way to your inbox.
        </p>
        <button onClick={() => { setStatus("idle"); setRef(null); setForm({ ...EMPTY }); setPicked([]); }}
          className="mt-6 text-[#0089A1] text-sm font-bold hover:text-ember transition-colors" data-testid="enquiry-send-another">
          Send another enquiry
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} noValidate className="grid grid-cols-1 sm:grid-cols-2 gap-5" data-testid="enquiry-form">
      <p className={sectionCls}><span className="text-ember">( 01 )</span> YOUR DETAILS</p>

      <Field label="Full Name *" error={errors.name}>
        <input className={inputCls} value={form.name} onChange={set("name")} placeholder="Your full name" data-testid="enquiry-name-input" required />
      </Field>
      <Field label="Company *" error={errors.company}>
        <input className={inputCls} value={form.company} onChange={set("company")} placeholder="Company name" data-testid="enquiry-company-input" required />
      </Field>
      <Field label="Business Email *" error={errors.email}>
        <input type="email" className={inputCls} value={form.email} onChange={set("email")} placeholder="name@company.com" data-testid="enquiry-email-input" required />
      </Field>
      <Field label="Phone *" error={errors.phone}>
        <input type="tel" className={inputCls} value={form.phone} onChange={set("phone")} placeholder="+91 ..." data-testid="enquiry-phone-input" required />
      </Field>
      <div className="sm:col-span-2">
        <Field label="Industry *" error={errors.industry}>
          <select className={inputCls} value={form.industry} onChange={set("industry")} data-testid="enquiry-industry-select" required>
            <option value="">Select your industry</option>
            {INDUSTRIES.map((i) => <option key={i.name} value={i.name}>{i.name}</option>)}
            <option value="Other">Other</option>
          </select>
        </Field>
      </div>

      <p className={sectionCls}><span className="text-ember">( 02 )</span> YOUR REQUIREMENT</p>

      <div className="sm:col-span-2">
        <span className={labelCls}>Solutions Interested * </span>
        <div className="flex flex-wrap gap-2" data-testid="enquiry-solution-chips">
          {SOLUTION_OPTIONS.map((s) => {
            const on = picked.includes(s);
            return (
              <button
                key={s}
                type="button"
                onClick={() => toggleSolution(s)}
                aria-pressed={on}
                className={`text-xs font-bold px-3.5 py-2 border transition-all duration-300 rounded-sm ${on ? "border-ember bg-ember/10 text-ember" : "border-[#C9D2DE] text-mist/60 hover:border-cy hover:text-[#0089A1]"}`}
                data-testid={`enquiry-solution-chip-${s.toLowerCase().replace(/[^a-z]+/g, "-").replace(/-+$/, "")}`}
              >
                {s}
              </button>
            );
          })}
        </div>
        {errors.solutionInterested && <span className="block text-ember text-xs mt-2" role="alert">{errors.solutionInterested}</span>}
      </div>

      <div className="sm:col-span-2">
        <Field label="Requirement">
          <select className={inputCls} value={form.requirement} onChange={set("requirement")} data-testid="enquiry-requirement-select">
            <option value="">What do you need help with?</option>
            {REQUIREMENTS.map((r) => <option key={r} value={r}>{r}</option>)}
          </select>
        </Field>
      </div>
      <div className="sm:col-span-2">
        <Field label="Message">
          <textarea rows={4} className={inputCls} value={form.message} onChange={set("message")} placeholder="Briefly describe your requirement or environment…" data-testid="enquiry-message-input" />
        </Field>
      </div>
      <div className="sm:col-span-2">
        <Field label="Attachment (optional, max 3MB)">
          <label htmlFor="enquiry-attach" className="flex items-center justify-center gap-3 border border-dashed border-[#E2E7EF] hover:border-cy/50 cursor-pointer px-4 py-5 text-sm text-mist/60 hover:text-[#0089A1] transition-colors" data-testid="enquiry-attachment-upload">
            <Upload size={16} /> {form.attachmentName || "Attach a requirement document (PDF / DOC / image)"}
          </label>
          <input id="enquiry-attach" type="file" accept=".pdf,.doc,.docx,.png,.jpg,.jpeg" className="hidden" onChange={onAttach} />
        </Field>
      </div>
      {/* honeypot — invisible to humans */}
      <input type="text" name="website" value={form.website} onChange={set("website")} className="hidden" tabIndex={-1} autoComplete="off" aria-hidden="true" />
      <div className="sm:col-span-2 flex flex-col sm:flex-row sm:items-center gap-4 border-t border-[#E2E7EF] pt-6">
        <button
          type="submit"
          disabled={status === "loading"}
          className="btn-ember inline-flex items-center justify-center gap-2.5 bg-ember text-white font-bold px-10 py-4 hover:bg-[#E54D16] transition-colors duration-300 disabled:opacity-60 rounded-sm"
          data-testid="enquiry-submit-button"
        >
          {status === "loading" ? <Loader2 size={17} className="animate-spin" /> : <Send size={16} />}
          Request a Consultation
        </button>
        <p className="flex items-center gap-2 text-[11px] font-tech tracking-[0.16em] text-mist/50" data-testid="enquiry-secure-note">
          <Lock size={12} /> ENCRYPTED SUBMISSION · VALIDATED SERVER-SIDE
        </p>
        {status === "error" && <p className="text-ember text-sm" data-testid="enquiry-error">Something went wrong — please try again or email us directly.</p>}
      </div>
    </form>
  );
}

function Field({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className={labelCls}>{label}</span>
      {children}
      {error && <span className="block text-ember text-xs mt-1.5" role="alert">{error}</span>}
    </label>
  );
}
