"use client";

/**
 * Industry Search — Comprehensive, categorized, searchable industry selector.
 * 250+ industries across 18 categories with search-as-you-type.
 */

import { useState, useRef, useEffect } from "react";
import { Building2, Search, X } from "lucide-react";

export interface IndustryOption { category: string; name: string }

const INDUSTRIES: Record<string, string[]> = {
  "Healthcare": ["General Practice / Family Medicine","Cardiology / Vascular","Orthopedics","Dermatology","Dentistry / Oral Surgery","Pediatrics","OB/GYN","Mental Health / Psychology","Chiropractic","Physical Therapy","Ophthalmology / Optometry","Urgent Care / ER","Plastic Surgery / Cosmetics","Veterinary","Home Health / Hospice","Pharmacy","Medical Devices / Equipment","Health & Wellness"],
  "Home Services": ["Lawn Care & Landscaping","Irrigation & Sprinkler Systems","HVAC (Heating, Cooling, Air)","Plumbing","Electrical","Roofing","General Contracting / Remodeling","Pest Control","Cleaning / Janitorial","Pool & Spa","Fencing","Painting","Flooring","Tree Service","Garage Doors","Locksmith","Appliance Repair","Handyman Services","Moving & Storage","Window & Door Installation","Solar Installation","Home Inspection","Foundation Repair","Waterproofing"],
  "Legal": ["Personal Injury","Criminal Defense","Family Law / Divorce","Estate Planning / Probate","Immigration","Bankruptcy","Employment Law","Real Estate Law","Business / Corporate Law","DUI / DWI","Medical Malpractice","Workers' Compensation","Intellectual Property","Tax Law","Civil Litigation"],
  "Automotive": ["Auto Dealership (New)","Auto Dealership (Used)","Auto Repair / Mechanic","Auto Body / Collision","Tires & Wheels","Car Wash / Detailing","Towing","Auto Parts","RV / Powersports","Motorcycle"],
  "Real Estate": ["Residential Real Estate","Commercial Real Estate","Property Management","Mortgage / Lending","Title & Escrow","Appraisal","Home Staging","Real Estate Investment"],
  "Finance & Insurance": ["Accounting / CPA","Financial Planning / Advisory","Insurance (General)","Auto Insurance","Health Insurance","Life Insurance","Home / Renters Insurance","Tax Preparation","Bookkeeping","Wealth Management","Credit Repair","Lending / Loans"],
  "Education": ["K-12 Schools (Private)","Higher Education / University","Trade / Vocational School","Tutoring / Test Prep","Online Learning / EdTech","Driving School","Music / Art School","Language School","Daycare / Preschool","After-School Programs"],
  "Food & Beverage": ["Restaurant (Fine Dining)","Restaurant (Casual / Fast Casual)","Restaurant (QSR / Fast Food)","Catering","Bakery","Coffee Shop / Cafe","Bar / Nightclub","Food Truck","Brewery / Winery / Distillery","Meal Prep / Delivery"],
  "Fitness & Recreation": ["Gym / Fitness Center","Personal Training","Yoga / Pilates","Martial Arts","Dance Studio","Sports Facility","Golf Course","Bowling / Entertainment","Outdoor Recreation / Adventure"],
  "Beauty & Personal Care": ["Hair Salon / Barbershop","Nail Salon","Med Spa / Aesthetics","Day Spa / Massage","Tattoo / Piercing","Skincare / Esthetics","Lash & Brow"],
  "Retail & E-commerce": ["General E-commerce","Fashion / Apparel","Jewelry","Electronics","Furniture / Home Decor","Pet Supplies","Sporting Goods","Grocery / Specialty Food","Liquor / Wine / Spirits","Gifts & Novelty","Thrift / Consignment","CBD / Cannabis"],
  "Technology & SaaS": ["SaaS / Software","IT Services / MSP","Cybersecurity","Web Development / Design","App Development","Cloud Services","Data Analytics / BI","AI / Machine Learning","Telecom / ISP"],
  "Marketing & Agency": ["Digital Marketing Agency","SEO Agency","PPC / Paid Media Agency","Social Media Agency","PR / Communications","Branding / Creative Agency","Content Marketing","Video Production","Photography","Print / Signage"],
  "Construction & Trades": ["General Construction","Commercial Construction","Residential Construction","Concrete / Masonry","Demolition","Excavation / Grading","Welding / Fabrication","Cabinet / Millwork","Drywall / Plastering"],
  "Professional Services": ["Consulting (General)","Management Consulting","HR / Staffing / Recruiting","Translation / Interpretation","Notary / Process Serving","Coaching (Business / Life)","Event Planning","Interior Design","Architecture","Engineering"],
  "Travel & Hospitality": ["Hotel / Resort","Vacation Rental","Travel Agency","Tour Operator","Airline","Cruise","Transportation / Shuttle"],
  "Non-Profit & Government": ["Non-Profit Organization","Church / Religious Organization","Association / Membership Org","Government Agency","Political Campaign"],
  "Other": ["Agriculture / Farming","Manufacturing","Logistics / Warehousing","Mining / Energy","Marine / Boating","Aviation","Funeral / Cemetery","Self Storage","Laundromat / Dry Cleaning"],
};

// Build flat list for searching
const ALL_OPTIONS: IndustryOption[] = Object.entries(INDUSTRIES).flatMap(([cat, subs]) => subs.map(name => ({ category: cat, name })));

interface Props {
  value: string;
  onChange: (industry: string, category: string) => void;
}

export default function IndustrySearch({ value, onChange }: Props) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [displayVal, setDisplayVal] = useState(value || "");
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  // Auto-map legacy values
  useEffect(() => {
    if (value && !displayVal) setDisplayVal(value);
  }, [value, displayVal]);

  const q = query.toLowerCase();
  const results = q.length >= 2 ? ALL_OPTIONS.filter(o => o.name.toLowerCase().includes(q) || o.category.toLowerCase().includes(q)).slice(0, 20) : [];

  // Group results
  const grouped = new Map<string, IndustryOption[]>();
  for (const r of results) {
    const g = grouped.get(r.category) || [];
    g.push(r);
    grouped.set(r.category, g);
  }

  function select(opt: IndustryOption) {
    setDisplayVal(opt.name);
    setQuery("");
    setOpen(false);
    onChange(opt.name, opt.category);
  }

  function selectCustom() {
    const custom = query.trim();
    if (!custom) return;
    setDisplayVal(custom);
    setQuery("");
    setOpen(false);
    onChange(custom, "Other");
  }

  return (
    <div ref={containerRef} className="relative">
      <div className="flex items-center border border-slate-200 rounded-xl bg-white overflow-hidden focus-within:ring-2 focus-within:ring-brand-500/40 focus-within:border-brand-500">
        <Building2 className="w-4 h-4 text-slate-400 ml-3 shrink-0" />
        <input
          type="text"
          value={open && query !== "" ? query : displayVal}
          onChange={(e) => { setQuery(e.target.value); if (!open) setOpen(true); }}
          onFocus={() => { setQuery(""); setOpen(true); }}
          placeholder="Search industry..."
          className="w-full px-2 py-3 text-sm focus:outline-none bg-transparent"
        />
        {displayVal && (
          <button onClick={() => { onChange("", ""); setDisplayVal(""); setQuery(""); }} className="p-2 text-slate-300 hover:text-slate-500"><X className="w-3.5 h-3.5" /></button>
        )}
      </div>

      {open && q.length >= 2 && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-slate-200 rounded-xl shadow-lg z-50 max-h-72 overflow-y-auto py-1">
          {results.length > 0 ? (
            <>
              {Array.from(grouped.entries()).map(([cat, items]) => (
                <div key={cat}>
                  <p className="px-3 pt-2 pb-1 text-[9px] font-bold uppercase tracking-widest text-slate-400">{cat}</p>
                  {items.map(opt => (
                    <button key={`${cat}-${opt.name}`} onClick={() => select(opt)} className="w-full flex items-center gap-2 px-3 py-2 hover:bg-slate-50 text-left">
                      <span className="text-sm text-slate-800">{opt.name}</span>
                    </button>
                  ))}
                </div>
              ))}
              <div className="border-t border-slate-100 mt-1 pt-1">
                <button onClick={selectCustom} className="w-full text-left px-3 py-2 text-xs text-slate-500 hover:bg-slate-50">
                  Can&apos;t find it? Use &quot;<span className="font-semibold text-slate-700">{query}</span>&quot; as custom industry
                </button>
              </div>
            </>
          ) : (
            <div className="px-3 py-4 text-center">
              <p className="text-xs text-slate-400 mb-2">No industries found for &quot;{query}&quot;</p>
              <button onClick={selectCustom} className="text-xs text-brand-600 font-semibold hover:underline">
                Use &quot;{query}&quot; as custom industry
              </button>
            </div>
          )}
        </div>
      )}

      {/* Show all categories when focused with no query */}
      {open && q.length < 2 && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-slate-200 rounded-xl shadow-lg z-50 max-h-72 overflow-y-auto py-1">
          <p className="px-3 py-2 text-[10px] text-slate-400">Type to search 250+ industries, or browse categories:</p>
          {Object.keys(INDUSTRIES).map(cat => (
            <button key={cat} onClick={() => setQuery(cat.slice(0, 3))} className="w-full text-left px-3 py-2 text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-brand-400" /> {cat} <span className="text-[10px] text-slate-400 ml-auto">{INDUSTRIES[cat].length}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/** Export for mapping legacy values */
export function findIndustryMatch(legacy: string): IndustryOption | null {
  const lower = legacy.toLowerCase();
  return ALL_OPTIONS.find(o => o.name.toLowerCase().includes(lower) || lower.includes(o.name.toLowerCase().split("/")[0].trim())) ?? null;
}
