
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Search, Loader2, Home, User, AlertCircle } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { ScrollArea } from '@/components/ui/scroll-area';

export default function PropertySearchDialog({ open, onOpenChange, clientId, onSelect }) {
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [debouncedTerm, setDebouncedTerm] = useState('');
  const { toast } = useToast();

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedTerm(searchTerm), 500);
    return () => clearTimeout(timer);
  }, [searchTerm]);

  useEffect(() => {
    const searchProperties = async () => {
      if (!clientId || debouncedTerm.length < 2) { setResults([]); return; }
      setLoading(true);
      try {
        const { data, error } = await supabase
          .from('owners').select('id, property_address, owner_name, unit_id, units(account_number)')
          .eq('association_id', clientId)
          .eq('status', 'active')
          .or(`property_address.ilike.%${debouncedTerm}%,owner_name.ilike.%${debouncedTerm}%`)
          .limit(20);
        if (error) throw error;
        setResults(data || []);
      } catch (error) {
        console.error('Error searching properties:', error);
        toast({ variant: 'destructive', title: 'Search Failed', description: 'Could not fetch properties.' });
      } finally { setLoading(false); }
    };
    if (open) searchProperties();
  }, [debouncedTerm, clientId, open, toast]);

  const handleSelect = (property) => { onSelect(property); onOpenChange(false); setSearchTerm(''); };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px] h-[500px] flex flex-col p-0 gap-0 overflow-hidden">
        <DialogHeader className="p-4 pb-2 border-b bg-muted/50">
          <DialogTitle>Search Properties</DialogTitle>
          <DialogDescription>Find a property by address or owner name.</DialogDescription>
          <div className="relative mt-2">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Start typing address or owner..." className="pl-9" autoFocus />
          </div>
        </DialogHeader>
        <ScrollArea className="flex-1 p-0">
          <div className="flex flex-col">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <Loader2 className="w-8 h-8 animate-spin mb-2" /><span className="text-sm">Searching...</span>
              </div>
            ) : results.length > 0 ? (
              results.map((property) => (
                <button key={property.id} onClick={() => handleSelect(property)}
                  className="flex flex-col items-start p-4 hover:bg-muted/50 transition-colors border-b last:border-0 w-full text-left group">
                  <div className="flex items-center gap-2 mb-1 w-full">
                    <Home className="w-4 h-4 text-muted-foreground group-hover:text-primary transition-colors" />
                    <span className="font-semibold truncate">{property.property_address}</span>
                  </div>
                  <div className="flex items-center gap-2 pl-6 text-sm text-muted-foreground w-full">
                    <User className="w-3.5 h-3.5" /><span className="truncate">{property.owner_name}</span>
                    {property.units?.account_number && <span className="ml-auto text-xs bg-muted px-2 py-0.5 rounded">#{property.units.account_number}</span>}
                  </div>
                </button>
              ))
            ) : debouncedTerm.length > 1 ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <AlertCircle className="w-8 h-8 mb-2 opacity-50" /><span className="text-sm">No properties found matching "{debouncedTerm}"</span>
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <Search className="w-8 h-8 mb-2 opacity-20" /><span className="text-sm">Type to search properties</span>
              </div>
            )}
          </div>
        </ScrollArea>
        <div className="p-3 bg-muted/50 border-t text-xs text-center text-muted-foreground">Showing {results.length} result(s)</div>
      </DialogContent>
    </Dialog>
  );
}
