import { useMemo } from "react";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";

interface Owner {
  id: string;
  first_name: string;
  last_name: string;
  unit_id?: string | null;
  association_id?: string;
  balance?: number;
  units?: { unit_number?: string } | null;
}

interface UnitGroup {
  unitId: string;
  unitNumber: string;
  owners: Owner[];
  label: string;
}

interface UnitOwnerSelectProps {
  owners: Owner[];
  value: string;
  onValueChange: (ownerId: string) => void;
  placeholder?: string;
  associationId?: string;
  showBalance?: boolean;
  /** When true, shows individual owners instead of grouped units */
  showIndividual?: boolean;
}

export default function UnitOwnerSelect({
  owners,
  value,
  onValueChange,
  placeholder = "Select unit / owner",
  associationId,
  showBalance = false,
  showIndividual = false,
}: UnitOwnerSelectProps) {
  const filtered = useMemo(() => {
    if (!associationId) return owners;
    return owners.filter((o) => o.association_id === associationId);
  }, [owners, associationId]);

  const { groups, unassigned } = useMemo(() => {
    const unitMap = new Map<string, UnitGroup>();
    const noUnit: Owner[] = [];

    for (const o of filtered) {
      if (!o.unit_id) {
        noUnit.push(o);
        continue;
      }
      const existing = unitMap.get(o.unit_id);
      if (existing) {
        existing.owners.push(o);
        existing.label = existing.owners
          .map((ow) => `${ow.first_name} ${ow.last_name}`)
          .join(", ");
      } else {
        unitMap.set(o.unit_id, {
          unitId: o.unit_id,
          unitNumber: o.units?.unit_number || "—",
          owners: [o],
          label: `${o.first_name} ${o.last_name}`,
        });
      }
    }

    // Sort by unit number
    const sorted = Array.from(unitMap.values()).sort((a, b) =>
      a.unitNumber.localeCompare(b.unitNumber, undefined, { numeric: true })
    );

    return { groups: sorted, unassigned: noUnit };
  }, [filtered]);

  if (showIndividual) {
    return (
      <Select value={value} onValueChange={onValueChange}>
        <SelectTrigger>
          <SelectValue placeholder={placeholder} />
        </SelectTrigger>
        <SelectContent>
          {filtered.map((o) => (
            <SelectItem key={o.id} value={o.id}>
              {o.last_name}, {o.first_name}
              {o.units?.unit_number ? ` (Unit ${o.units.unit_number})` : ""}
              {showBalance ? ` — $${Number(o.balance || 0).toFixed(2)}` : ""}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    );
  }

  return (
    <Select value={value} onValueChange={onValueChange}>
      <SelectTrigger>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {groups.map((g) => (
          <SelectGroup key={g.unitId}>
            <SelectLabel className="text-xs text-muted-foreground px-2">
              Unit {g.unitNumber}
            </SelectLabel>
            {g.owners.map((o) => (
              <SelectItem key={o.id} value={o.id}>
                {o.first_name} {o.last_name} — Unit {g.unitNumber}
                {showBalance ? ` ($${Number(o.balance || 0).toFixed(2)})` : ""}
              </SelectItem>
            ))}
          </SelectGroup>
        ))}
        {unassigned.length > 0 && (
          <SelectGroup>
            <SelectLabel className="text-xs text-muted-foreground px-2">
              No Unit Assigned
            </SelectLabel>
            {unassigned.map((o) => (
              <SelectItem key={o.id} value={o.id}>
                {o.first_name} {o.last_name}
                {showBalance ? ` ($${Number(o.balance || 0).toFixed(2)})` : ""}
              </SelectItem>
            ))}
          </SelectGroup>
        )}
      </SelectContent>
    </Select>
  );
}
