import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { Tag, X, Plus } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export const UNIT_STATUS_TAGS = [
  { value: "in_collections", label: "In Collections", className: "bg-amber-100 text-amber-900 border-amber-300 hover:bg-amber-200" },
  { value: "in_foreclosure", label: "In Foreclosure", className: "bg-orange-100 text-orange-900 border-orange-300 hover:bg-orange-200" },
  { value: "foreclosed", label: "Foreclosed", className: "bg-red-200 text-red-900 border-red-300 hover:bg-red-300" },
  { value: "for_sale", label: "For Sale", className: "bg-blue-100 text-blue-900 border-blue-300 hover:bg-blue-200" },
  { value: "for_auction", label: "For Auction", className: "bg-purple-100 text-purple-900 border-purple-300 hover:bg-purple-200" },
] as const;

export type UnitStatusTagValue = typeof UNIT_STATUS_TAGS[number]["value"];

const tagMeta = (v: string) => UNIT_STATUS_TAGS.find((t) => t.value === v);

interface Props {
  unitId: string;
  value: string[] | null | undefined;
  onChange?: (next: string[]) => void;
  size?: "sm" | "md";
  showTriggerLabel?: boolean;
  className?: string;
  /** When true, omit edit affordance (display-only). */
  readOnly?: boolean;
}

export default function UnitStatusTagsEditor({
  unitId, value, onChange, size = "sm", showTriggerLabel = false, className, readOnly,
}: Props) {
  const tags = Array.isArray(value) ? value : [];
  const [saving, setSaving] = useState(false);
  const [open, setOpen] = useState(false);
  const { toast } = useToast();

  const persist = async (next: string[]) => {
    setSaving(true);
    try {
      const { error } = await supabase
        .from("units")
        .update({ status_tags: next } as any)
        .eq("id", unitId);
      if (error) throw error;
      onChange?.(next);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Failed to update tags", description: err.message });
    } finally {
      setSaving(false);
    }
  };

  const toggle = (v: string) => {
    const next = tags.includes(v) ? tags.filter((t) => t !== v) : [...tags, v];
    persist(next);
  };

  const remove = (v: string) => persist(tags.filter((t) => t !== v));

  const badgeSize = size === "sm" ? "text-[10px] px-1.5 py-0 h-5" : "text-xs px-2 py-0.5";

  return (
    <div className={`flex flex-wrap items-center gap-1 ${className ?? ""}`}>
      {tags.map((t) => {
        const meta = tagMeta(t);
        if (!meta) return null;
        return (
          <Badge
            key={t}
            variant="outline"
            className={`${meta.className} ${badgeSize} font-medium gap-1 group/tag`}
          >
            {meta.label}
            {!readOnly && (
              <button
                type="button"
                onClick={(e) => { e.stopPropagation(); remove(t); }}
                className="opacity-60 hover:opacity-100"
                aria-label={`Remove ${meta.label}`}
                disabled={saving}
              >
                <X className="h-3 w-3" />
              </button>
            )}
          </Badge>
        );
      })}
      {!readOnly && (
        <Popover open={open} onOpenChange={setOpen}>
          <PopoverTrigger asChild onClick={(e) => e.stopPropagation()}>
            <Button
              variant="outline"
              size="sm"
              className={`h-6 px-2 gap-1 text-[10px] border-dashed text-muted-foreground hover:text-foreground`}
              disabled={saving}
            >
              {tags.length === 0 ? <Tag className="h-3 w-3" /> : <Plus className="h-3 w-3" />}
              {showTriggerLabel || tags.length === 0 ? (tags.length === 0 ? "Add tag" : "Edit") : null}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-56 p-2" align="start" onClick={(e) => e.stopPropagation()}>
            <div className="text-xs font-medium text-muted-foreground px-2 py-1">Status tags</div>
            <div className="space-y-1">
              {UNIT_STATUS_TAGS.map((opt) => {
                const checked = tags.includes(opt.value);
                return (
                  <label
                    key={opt.value}
                    className="flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted cursor-pointer text-sm"
                  >
                    <Checkbox checked={checked} onCheckedChange={() => toggle(opt.value)} disabled={saving} />
                    <span className="flex-1">{opt.label}</span>
                  </label>
                );
              })}
            </div>
          </PopoverContent>
        </Popover>
      )}
    </div>
  );
}
