import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Loader2, Search, User, X } from 'lucide-react';
import { toast } from 'sonner';
import { shareSummary } from '@/services/summaryApi';
import { searchUsers } from '@/services/userApi';

interface ShareSummaryModalProps {
  isOpen: boolean;
  onClose: () => void;
  summaryId: string;
  requestTitle: string;
  onSuccess?: () => void;
}

export function ShareSummaryModal({ isOpen, onClose, summaryId, requestTitle, onSuccess }: ShareSummaryModalProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [users, setUsers] = useState<Array<{ userId: string; email: string; displayName?: string; designation?: string; department?: string }>>([]);
  const [selectedUserIds, setSelectedUserIds] = useState<Set<string>>(new Set());
  const [searching, setSearching] = useState(false);
  const [sharing, setSharing] = useState(false);

  // Search users - only when input starts with @
  useEffect(() => {
    if (!isOpen) {
      setUsers([]);
      return;
    }

    // Only trigger search when using @ sign
    if (!searchTerm || !searchTerm.startsWith('@') || searchTerm.length < 2) {
      setUsers([]);
      setSearching(false);
      return;
    }

    const searchTimeout = setTimeout(async () => {
      try {
        setSearching(true);
        const term = searchTerm.slice(1); // Remove @ prefix
        const response = await searchUsers(term, 10);
        const results = response?.data?.data || response?.data || [];
        setUsers(Array.isArray(results) ? results : []);
      } catch (error) {
        console.error('Failed to search users:', error);
        toast.error('Failed to search users');
      } finally {
        setSearching(false);
      }
    }, 300);

    return () => clearTimeout(searchTimeout);
  }, [searchTerm, isOpen]);

  const handleToggleUser = (userId: string) => {
    setSelectedUserIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(userId)) {
        newSet.delete(userId);
      } else {
        newSet.add(userId);
      }
      return newSet;
    });
  };

  const handleShare = async () => {
    if (selectedUserIds.size === 0) {
      toast.error('Please select at least one user to share with');
      return;
    }

    try {
      setSharing(true);
      await shareSummary(summaryId, Array.from(selectedUserIds));
      toast.success(`Summary shared with ${selectedUserIds.size} user(s)`);
      setSelectedUserIds(new Set());
      setSearchTerm('');
      setUsers([]);
      onSuccess?.();
      onClose();
    } catch (error: any) {
      console.error('Failed to share summary:', error);
      toast.error(error?.response?.data?.message || 'Failed to share summary');
    } finally {
      setSharing(false);
    }
  };

  const handleClose = () => {
    setSelectedUserIds(new Set());
    setSearchTerm('');
    setUsers([]);
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Share Summary</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div>
            <Label className="text-sm font-medium text-gray-700">Request</Label>
            <p className="text-sm text-gray-600 mt-1">{requestTitle}</p>
          </div>

          <div>
            <Label htmlFor="user-search" className="text-sm font-medium text-gray-700">
              Search Users
            </Label>
            <div className="relative mt-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
              <Input
                id="user-search"
                placeholder="Type @ to search users..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            {searchTerm && !searchTerm.startsWith('@') && (
              <p className="text-xs text-gray-500 mt-1 ml-1">
                Start with @ to search users (e.g., @john)
              </p>
            )}
          </div>

          {searching && (
            <div className="flex items-center justify-center py-4">
              <Loader2 className="h-5 w-5 animate-spin text-blue-600" />
            </div>
          )}

          {!searching && users.length > 0 && (
            <div className="border rounded-lg max-h-[300px] overflow-y-auto">
              {users.map((user) => {
                const isSelected = selectedUserIds.has(user.userId);
                return (
                  <div
                    key={user.userId}
                    className="flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer"
                    onClick={() => handleToggleUser(user.userId)}
                  >
                    <div 
                      onClick={(e) => e.stopPropagation()}
                      onMouseDown={(e) => e.stopPropagation()}
                      className="flex items-center"
                    >
                      <Checkbox
                        checked={isSelected}
                        onCheckedChange={() => handleToggleUser(user.userId)}
                      />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <User className="h-4 w-4 text-gray-400 flex-shrink-0" />
                        <p className="text-sm font-medium text-gray-900 truncate">
                          {user.displayName || user.email}
                        </p>
                      </div>
                      {(user.designation || user.department) && (
                        <p className="text-xs text-gray-500 mt-0.5">{user.designation || user.department}</p>
                      )}
                      <p className="text-xs text-gray-400 truncate">{user.email}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {!searching && searchTerm && searchTerm.startsWith('@') && users.length === 0 && (
            <div className="text-center py-8 text-gray-500 text-sm">
              No users found
            </div>
          )}
          
          {!searching && searchTerm && !searchTerm.startsWith('@') && (
            <div className="text-center py-8 text-gray-500 text-sm">
              Start typing with @ to search users
            </div>
          )}

          {selectedUserIds.size > 0 && (
            <div className="border rounded-lg p-3 bg-blue-50">
              <p className="text-sm font-medium text-gray-700 mb-2">
                Selected ({selectedUserIds.size})
              </p>
              <div className="flex flex-wrap gap-2">
                {Array.from(selectedUserIds).map((userId) => {
                  const user = users.find(u => u.userId === userId);
                  return (
                    <div
                      key={userId}
                      className="flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs"
                    >
                      <span>{user?.displayName || user?.email || userId}</span>
                      <button
                        onClick={() => handleToggleUser(userId)}
                        className="ml-1 hover:text-red-600"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose} disabled={sharing}>
            Cancel
          </Button>
          <Button onClick={handleShare} disabled={sharing || selectedUserIds.size === 0}>
            {sharing ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Sharing...
              </>
            ) : (
              `Share with ${selectedUserIds.size} user(s)`
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

