import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Combobox } from '@/components/Combobox';

export function PropertySelect({ associationId, value, onChange, onSelectProperty, className }) {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    if (!associationId) {
      setOptions([]);
      return;
    }

    const fetchOwners = async () => {
      const { data, error } = await supabase
        .from('owners')
        .select('id, first_name, last_name, property_address, mailing_address, unit_id, status, units(unit_number, account_number)')
        .eq('association_id', associationId)
        .order('last_name');

      if (!error && data) {
        const sorted = [...data].sort((a, b) => {
          const aArch = a.status === 'archived' ? 1 : 0;
          const bArch = b.status === 'archived' ? 1 : 0;
          if (aArch !== bArch) return aArch - bArch;
          return (a.last_name || '').localeCompare(b.last_name || '');
        });
        setOptions(sorted.map(o => {
          const unitLabel = o.units?.account_number || o.units?.unit_number;
          const addr = o.property_address ? ` - ${o.property_address}` : '';
          const unit = unitLabel ? ` [${unitLabel}]` : '';
          const archived = o.status === 'archived' ? ' (archived)' : '';
          return {
            value: o.id,
            label: `${o.first_name} ${o.last_name}${unit}${addr}${archived}`,
            raw: o,
          };
        }));
      }
    };
    fetchOwners();
  }, [associationId]);

  const handleChange = (val) => {
    if (onChange) onChange(val);
    if (onSelectProperty) {
      const selected = options.find(o => o.value === val);
      if (selected) {
        onSelectProperty({
          id: selected.raw.id,
          property_address: selected.raw.property_address || '',
          owner_name: `${selected.raw.first_name} ${selected.raw.last_name}`,
          mailing_address: selected.raw.mailing_address
        });
      }
    }
  };

  return (
    <Combobox
      options={options}
      value={value}
      onChange={handleChange}
      placeholder="Select property/owner..."
      className={className}
    />
  );
}

export default PropertySelect;
