import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";
import { Search, Upload, Loader2, CheckCircle2, Phone } from "lucide-react";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

export default function FindPart() {
  const [searchParams] = useSearchParams();
  const [form, setForm] = useState({
    vehicle_year: searchParams.get("year") || "",
    make: searchParams.get("make") || "",
    model: searchParams.get("model") || "",
    engine: "",
    part_needed: searchParams.get("part") || "",
    vin: searchParams.get("vin") || "",
    budget: "",
    name: "",
    email: "",
    phone: "",
    notes: "",
  });
  const [vinLoading, setVinLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);

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

  const handleVinDecode = async () => {
    if (!form.vin || form.vin.length < 11) { toast.error("Enter a valid VIN"); return; }
    setVinLoading(true);
    try {
      const { data } = await axios.get(`${API}/vin-decode/${form.vin}`);
      setForm(f => ({ ...f, vehicle_year: data.year || f.vehicle_year, make: data.make || f.make, model: data.model || f.model, engine: data.engine || f.engine }));
      toast.success("VIN decoded successfully");
    } catch { toast.error("VIN decode failed"); }
    setVinLoading(false);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.part_needed || !form.name || !form.email) { toast.error("Part, name, and email are required"); return; }
    setSubmitLoading(true);
    try {
      const token = localStorage.getItem("user_token");
      const headers = token ? { Authorization: `Bearer ${token}` } : {};
      const endpoint = token ? `${API}/user/part-requests` : `${API}/part-requests`;
      await axios.post(endpoint, form, { headers });
      setSubmitted(true);
      toast.success("Request submitted!");
    } catch { toast.error("Failed to submit request"); }
    setSubmitLoading(false);
  };

  const inputCls = "w-full h-11 px-4 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[14px] text-white placeholder:text-[#666] focus:outline-none focus:border-[#3B82F6] transition-colors";
  const labelCls = "block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5";

  if (submitted) {
    return (
      <div className="min-h-screen bg-[#0B0B0B] pt-24 pb-16 flex items-center justify-center">
        <div className="text-center max-w-md mx-auto px-4">
          <CheckCircle2 className="h-14 w-14 text-[#28A745] mx-auto mb-6" />
          <h1 className="text-3xl font-bold tracking-[-0.03em] text-white mb-3">Request Received</h1>
          <p className="text-[14px] text-[#9A9A9A] mb-6">We'll get back to you within 24-48 hours with pricing. Check your email or dashboard for updates.</p>
          <a href="tel:+17049003512" className="inline-flex items-center gap-2 text-[#3B82F6] text-[14px] font-medium hover:underline">
            <Phone className="h-4 w-4" /> Need it faster? Call (704) 900-3512
          </a>
        </div>
      </div>
    );
  }

  return (
    <div data-testid="find-part-page" className="min-h-screen bg-[#0B0B0B] pt-24 pb-16">
      <div className="max-w-2xl mx-auto px-4">
        <div className="mb-8">
          <h1 className="text-3xl font-bold tracking-[-0.03em] text-white">Request a Part</h1>
          <p className="text-[14px] text-[#9A9A9A] mt-2">Tell us what you need. We source it. You save 40-70%.</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* VIN Decode */}
          <div className="bg-[#121212] border border-[#2A2A2A] rounded-sm p-5">
            <p className="text-[12px] font-semibold text-[#3B82F6] uppercase tracking-wide mb-3">Quick Fill — Enter VIN</p>
            <div className="flex gap-2">
              <input
                data-testid="fp-vin"
                type="text"
                value={form.vin}
                onChange={update("vin")}
                maxLength={17}
                placeholder="Enter VIN to auto-fill vehicle info"
                className={`${inputCls} flex-1 font-mono uppercase`}
              />
              <button
                type="button"
                data-testid="fp-vin-decode"
                onClick={handleVinDecode}
                disabled={vinLoading}
                className="h-11 px-5 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[12px] font-semibold uppercase tracking-wide rounded-sm transition-colors flex-shrink-0"
              >
                {vinLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <><Search className="h-4 w-4 mr-1.5 inline" />Decode</>}
              </button>
            </div>
          </div>

          {/* Vehicle Info */}
          <div>
            <p className="text-[12px] font-semibold text-[#9A9A9A] uppercase tracking-wide mb-4">Vehicle Information</p>
            <div className="grid grid-cols-2 gap-3">
              <div><label className={labelCls}>Year</label><input data-testid="fp-year" placeholder="2019" value={form.vehicle_year} onChange={update("vehicle_year")} className={inputCls} /></div>
              <div><label className={labelCls}>Make</label><input data-testid="fp-make" placeholder="Toyota" value={form.make} onChange={update("make")} className={inputCls} /></div>
              <div><label className={labelCls}>Model</label><input data-testid="fp-model" placeholder="Camry" value={form.model} onChange={update("model")} className={inputCls} /></div>
              <div><label className={labelCls}>Engine</label><input data-testid="fp-engine" placeholder="2.5L 4cyl" value={form.engine} onChange={update("engine")} className={inputCls} /></div>
            </div>
          </div>

          {/* Part Details */}
          <div>
            <p className="text-[12px] font-semibold text-[#9A9A9A] uppercase tracking-wide mb-4">Part Details</p>
            <div className="space-y-3">
              <div><label className={labelCls}>Part Needed *</label><input data-testid="fp-part" placeholder="e.g. Driver side headlight assembly" value={form.part_needed} onChange={update("part_needed")} className={inputCls} required /></div>
              <div><label className={labelCls}>Budget</label><input data-testid="fp-budget" placeholder="e.g. $200-300" value={form.budget} onChange={update("budget")} className={inputCls} /></div>
              <div><label className={labelCls}>Additional Notes</label><textarea data-testid="fp-notes" placeholder="Any specific requirements, OEM preferred, etc." value={form.notes} onChange={update("notes")} rows={3} className={`${inputCls} h-auto py-3 resize-none`} /></div>
            </div>
          </div>

          {/* Contact */}
          <div>
            <p className="text-[12px] font-semibold text-[#9A9A9A] uppercase tracking-wide mb-4">Contact Information</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div><label className={labelCls}>Name *</label><input data-testid="fp-name" placeholder="Full name" value={form.name} onChange={update("name")} className={inputCls} required /></div>
              <div><label className={labelCls}>Email *</label><input data-testid="fp-email" type="email" placeholder="email@example.com" value={form.email} onChange={update("email")} className={inputCls} required /></div>
              <div className="sm:col-span-2"><label className={labelCls}>Phone</label><input data-testid="fp-phone" placeholder="(704) 900-3512" value={form.phone} onChange={update("phone")} className={inputCls} /></div>
            </div>
          </div>

          <button
            data-testid="fp-submit"
            type="submit"
            disabled={submitLoading}
            className="w-full h-13 py-4 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[15px] font-bold uppercase tracking-wide rounded transition-colors flex items-center justify-center"
          >
            {submitLoading ? <Loader2 className="h-5 w-5 animate-spin mr-2" /> : null}
            Submit Part Request
          </button>
        </form>
      </div>
    </div>
  );
}
