"use client";

import { useState } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

const INDUSTRIES = [
  "Technology", "Financial Services", "Healthcare", "Manufacturing",
  "Retail", "Education", "Media", "Government", "Telecommunications",
  "Energy", "Real Estate", "Transportation", "Hospitality",
];

const SENIORITY = ["Entry", "Senior", "Manager", "Director", "VP", "CXO", "Partner", "Owner"];

const JOB_FUNCTIONS = [
  "Engineering", "Marketing", "IT", "Finance", "Operations",
  "Sales", "HR", "Legal", "Consulting", "Product Management",
];

const COMPANY_SIZES = ["1", "2-10", "11-50", "51-200", "201-500", "501-1000", "1001-5000", "5001-10000", "10000+"];

const LANGUAGES = ["English", "Chinese", "Japanese", "Korean", "German", "French", "Spanish"];

const LOCATION_PRESETS: Record<string, string[]> = {
  APAC: ["China", "Japan", "South Korea", "Singapore", "Australia", "India", "Southeast Asia"],
  EMEA: ["United Kingdom", "Germany", "France", "Netherlands", "UAE", "Saudi Arabia", "South Africa"],
  NA: ["United States", "Canada"],
};

export interface LinkedInTargeting {
  industries: string[];
  seniority: string[];
  jobFunctions: string[];
  locations: string[];
  languages: string[];
  companySizes: string[];
  estimatedReach: string;
}

interface LinkedInTargetingPanelProps {
  value: LinkedInTargeting;
  onChange: (value: LinkedInTargeting) => void;
}

export function LinkedInTargetingPanel({ value, onChange }: LinkedInTargetingPanelProps) {
  const [open, setOpen] = useState(false);
  const [locationSearch, setLocationSearch] = useState("");

  const update = <K extends keyof LinkedInTargeting>(key: K, val: LinkedInTargeting[K]) => {
    onChange({ ...value, [key]: val });
  };

  const toggleArray = (key: "industries" | "seniority" | "jobFunctions" | "companySizes", item: string) => {
    const arr = value[key];
    update(key, arr.includes(item) ? arr.filter((v) => v !== item) : [...arr, item]);
  };

  const addLocations = (locs: string[]) => {
    const unique = [...new Set([...value.locations, ...locs])];
    update("locations", unique);
  };

  const removeLocation = (loc: string) => {
    update("locations", value.locations.filter((l) => l !== loc));
  };

  return (
    <div className="rounded-xl border border-gray-100 shadow-sm bg-white border-l-4 border-l-[#E3322D]">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="flex w-full items-center justify-between p-4 text-sm font-semibold text-[#1A1F36] hover:bg-gray-50 transition-colors"
      >
        LinkedIn Audience Targeting
        {open ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
      </button>

      {open && (
        <div className="space-y-4 border-t p-3">
          <div>
            <Label className="text-xs mb-1.5">Industry</Label>
            <div className="flex flex-wrap gap-1.5">
              {INDUSTRIES.map((ind) => (
                <button
                  key={ind}
                  type="button"
                  onClick={() => toggleArray("industries", ind)}
                  className={`rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
                    value.industries.includes(ind) ? "bg-primary text-primary-foreground border-primary" : "hover:bg-muted"
                  }`}
                >
                  {ind}
                </button>
              ))}
            </div>
          </div>

          <div>
            <Label className="text-xs mb-1.5">Seniority</Label>
            <div className="flex flex-wrap gap-1.5">
              {SENIORITY.map((s) => (
                <label key={s} className="flex items-center gap-1.5 text-xs">
                  <input
                    type="checkbox"
                    checked={value.seniority.includes(s)}
                    onChange={() => toggleArray("seniority", s)}
                    className="rounded"
                  />
                  {s}
                </label>
              ))}
            </div>
          </div>

          <div>
            <Label className="text-xs mb-1.5">Job Functions</Label>
            <div className="flex flex-wrap gap-1.5">
              {JOB_FUNCTIONS.map((jf) => (
                <button
                  key={jf}
                  type="button"
                  onClick={() => toggleArray("jobFunctions", jf)}
                  className={`rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
                    value.jobFunctions.includes(jf) ? "bg-primary text-primary-foreground border-primary" : "hover:bg-muted"
                  }`}
                >
                  {jf}
                </button>
              ))}
            </div>
          </div>

          <div>
            <Label className="text-xs mb-1.5">Locations</Label>
            <div className="flex gap-1.5 mb-2">
              {Object.entries(LOCATION_PRESETS).map(([name, locs]) => (
                <Button key={name} type="button" variant="outline" size="sm" onClick={() => addLocations(locs)}>
                  {name}
                </Button>
              ))}
            </div>
            <Input
              placeholder="Search locations..."
              value={locationSearch}
              onChange={(e) => setLocationSearch(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && locationSearch.trim()) {
                  e.preventDefault();
                  addLocations([locationSearch.trim()]);
                  setLocationSearch("");
                }
              }}
              className="text-sm"
            />
            {value.locations.length > 0 && (
              <div className="flex flex-wrap gap-1 mt-2">
                {value.locations.map((loc) => (
                  <Badge key={loc} variant="secondary" className="text-xs">
                    {loc}
                    <button type="button" onClick={() => removeLocation(loc)} className="ml-1">×</button>
                  </Badge>
                ))}
              </div>
            )}
          </div>

          <div>
            <Label className="text-xs mb-1.5">Language</Label>
            <select
              value={value.languages[0] || ""}
              onChange={(e) => update("languages", e.target.value ? [e.target.value] : [])}
              className="w-full rounded-md border px-3 py-1.5 text-sm"
            >
              <option value="">Select language</option>
              {LANGUAGES.map((l) => (
                <option key={l} value={l}>{l}</option>
              ))}
            </select>
          </div>

          <div>
            <Label className="text-xs mb-1.5">Company Size</Label>
            <div className="flex flex-wrap gap-1.5">
              {COMPANY_SIZES.map((size) => (
                <label key={size} className="flex items-center gap-1.5 text-xs">
                  <input
                    type="checkbox"
                    checked={value.companySizes.includes(size)}
                    onChange={() => toggleArray("companySizes", size)}
                    className="rounded"
                  />
                  {size}
                </label>
              ))}
            </div>
          </div>

          <div>
            <Label className="text-xs mb-1.5">Estimated Reach</Label>
            <div className="flex gap-2">
              <Input
                value={value.estimatedReach}
                onChange={(e) => update("estimatedReach", e.target.value)}
                placeholder="e.g. 50,000"
                className="text-sm"
              />
              <Button type="button" variant="outline" size="sm">Calculate</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
