"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 { Badge } from "@/components/ui/badge";

const COUNTRIES = [
  "Thailand", "Indonesia", "Vietnam", "Philippines", "Malaysia", "Singapore",
  "United States", "India", "Brazil", "Japan", "Germany", "United Kingdom",
  "France", "Canada", "Australia", "South Korea", "Mexico",
];

interface FacebookGeoPanelProps {
  value: string[];
  onChange: (countries: string[]) => void;
}

export function FacebookGeoPanel({ value, onChange }: FacebookGeoPanelProps) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");

  const filtered = COUNTRIES.filter(
    (c) => c.toLowerCase().includes(search.toLowerCase()) && !value.includes(c)
  );

  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"
      >
        Facebook Geotargeting
        {open ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
      </button>

      {open && (
        <div className="space-y-3 border-t p-3">
          <div>
            <Label className="text-xs mb-1.5">Countries</Label>
            <Input
              placeholder="Search countries..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="text-sm"
            />
            {search && filtered.length > 0 && (
              <div className="mt-1 max-h-32 overflow-y-auto rounded border">
                {filtered.map((c) => (
                  <button
                    key={c}
                    type="button"
                    onClick={() => { onChange([...value, c]); setSearch(""); }}
                    className="w-full px-3 py-1.5 text-left text-sm hover:bg-muted"
                  >
                    {c}
                  </button>
                ))}
              </div>
            )}
          </div>

          {value.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {value.map((c) => (
                <Badge key={c} variant="secondary" className="text-xs">
                  {c}
                  <button type="button" onClick={() => onChange(value.filter((v) => v !== c))} className="ml-1">×</button>
                </Badge>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
