import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Loader2, Search, User } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useAssociationBoardMembers } from '@/hooks/useAssociationBoardMembers';

export default function AssociationBoardMembersDialog({ open, onOpenChange, client, onSuccess }) {
  const { fetchAvailableUsers, fetchBoardMembers, saveBoardMembers, loading } = useAssociationBoardMembers();
  
  const [users, setUsers] = useState([]);
  const [selectedUserIds, setSelectedUserIds] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [initLoading, setInitLoading] = useState(false);

  useEffect(() => {
    if (open && client) {
      loadData();
    } else {
      setUsers([]);
      setSelectedUserIds([]);
      setSearchQuery('');
    }
  }, [open, client]);

  const loadData = async () => {
    setInitLoading(true);
    const [allUsers, currentMembers] = await Promise.all([
      fetchAvailableUsers(),
      fetchBoardMembers(client.id)
    ]);
    
    setUsers(allUsers || []);
    setSelectedUserIds(currentMembers.map(m => m.id) || []);
    setInitLoading(false);
  };

  const handleToggle = (userId) => {
    setSelectedUserIds(prev => {
      if (prev.includes(userId)) {
        return prev.filter(id => id !== userId);
      } else {
        return [...prev, userId];
      }
    });
  };

  const handleSave = async () => {
    const success = await saveBoardMembers(client.id, selectedUserIds);
    if (success) {
      if (onSuccess) onSuccess();
      onOpenChange(false);
    }
  };

  const filteredUsers = users.filter(u => 
    (u.email?.toLowerCase().includes(searchQuery.toLowerCase())) || 
    (u.full_name?.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Manage Board Members</DialogTitle>
          <DialogDescription>
            Select users to assign as board members for <strong>{client?.name}</strong>.
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4 py-2">
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Search users by name or email..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9"
            />
          </div>

          <div className="border rounded-md">
            <div className="bg-muted px-4 py-2 border-b text-xs font-medium text-muted-foreground uppercase flex justify-between">
              <span>User</span>
              <span>{selectedUserIds.length} Selected</span>
            </div>
            <ScrollArea className="h-[300px]">
              {initLoading ? (
                <div className="flex flex-col items-center justify-center h-full gap-2 text-muted-foreground">
                   <Loader2 className="h-6 w-6 animate-spin" />
                   <span className="text-xs">Loading users...</span>
                </div>
              ) : filteredUsers.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full p-4 text-center text-muted-foreground">
                  <p className="text-sm">No users found.</p>
                </div>
              ) : (
                <div className="divide-y">
                  {filteredUsers.map(user => {
                    const isSelected = selectedUserIds.includes(user.id);
                    return (
                      <div 
                        key={user.id} 
                        className={`flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors cursor-pointer ${isSelected ? 'bg-primary/5' : ''}`}
                        onClick={() => handleToggle(user.id)}
                      >
                        <Checkbox 
                          checked={isSelected}
                          onCheckedChange={() => handleToggle(user.id)}
                          id={`user-${user.id}`}
                        />
                        <div className="flex-1 min-w-0">
                          <label 
                            htmlFor={`user-${user.id}`} 
                            className="text-sm font-medium cursor-pointer block truncate"
                          >
                            {user.full_name || 'Unknown Name'}
                          </label>
                          <p className="text-xs text-muted-foreground truncate">{user.email}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </ScrollArea>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={loading || initLoading}>
            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Save Changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
