import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Loader2, X } from 'lucide-react';

export default function OwnerUnitSelector({ clientId, value = { type: 'all', ids: [] }, onChange }) {
  const [owners, setOwners] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectorOpen, setSelectorOpen] = useState(false);

  useEffect(() => {
    if (clientId) fetchOwners();
  }, [clientId]);

  const fetchOwners = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('property_owners')
        .select('id, owner_name, property_address, unit_id')
        .eq('client_id', clientId)
        .order('owner_name');
      if (!error) setOwners(data || []);
    } finally {
      setLoading(false);
    }
  };

  const handleTypeChange = (type) => {
    onChange({ type, ids: type === 'all' ? [] : value.ids });
  };

  const handleAddOwner = (id) => {
    if (!value.ids.includes(id)) {
      onChange({ ...value, ids: [...value.ids, id] });
    }
  };

  const handleRemoveOwner = (id) => {
    onChange({ ...value, ids: value.ids.filter(i => i !== id) });
  };

  if (loading) return <div className="flex items-center text-sm text-slate-500"><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Loading owners...</div>;

  return (
    <div className="space-y-3 p-4 bg-slate-50 rounded-lg border border-slate-200">
      <div className="flex items-center justify-between">
        <Label className="text-slate-700 font-semibold">Assignment Scope</Label>
      </div>
      
      <Select value={value.type} onValueChange={handleTypeChange}>
        <SelectTrigger className="bg-white">
          <SelectValue placeholder="Select scope" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All Owners / Units</SelectItem>
          <SelectItem value="specific">Specific Owners / Units</SelectItem>
        </SelectContent>
      </Select>

      {value.type === 'specific' && (
        <div className="space-y-3 pt-2">
          <Select onValueChange={handleAddOwner} value="">
            <SelectTrigger className="bg-white">
              <SelectValue placeholder="Select an owner to add..." />
            </SelectTrigger>
            <SelectContent>
              {owners.filter(o => !value.ids.includes(o.id)).map(o => (
                <SelectItem key={o.id} value={o.id}>
                  {o.owner_name} {o.unit_id ? `(Unit ${o.unit_id})` : ''} - {o.property_address}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <div className="flex flex-wrap gap-2">
            {value.ids.length === 0 && <span className="text-xs text-slate-500 italic">No owners selected.</span>}
            {value.ids.map(id => {
              const owner = owners.find(o => o.id === id);
              if (!owner) return null;
              return (
                <Badge key={id} variant="secondary" className="bg-white border-slate-200 flex items-center gap-1 py-1">
                  <span className="max-w-[150px] truncate" title={owner.owner_name}>{owner.owner_name}</span>
                  <Button variant="ghost" size="icon" className="h-4 w-4 ml-1 hover:bg-slate-200 rounded-full" onClick={() => handleRemoveOwner(id)}>
                    <X className="w-3 h-3" />
                  </Button>
                </Badge>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}