import { useState } from 'react';
import { motion } from 'framer-motion';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Eye, Info, X } from 'lucide-react';
import { FormData } from '@/hooks/useCreateRequestForm';
import { useUserSearch } from '@/hooks/useUserSearch';

interface ParticipantsStepProps {
  formData: FormData;
  updateFormData: (field: keyof FormData, value: any) => void;
  onValidationError: (error: { type: string; email: string; message: string }) => void;
  initiatorEmail: string;
}

/**
 * Component: ParticipantsStep
 * 
 * Purpose: Step 4 - Participants & access settings
 * 
 * Features:
 * - Add spectators with @ search
 * - Manage spectator list
 * - Test IDs for testing
 */
export function ParticipantsStep({
  formData,
  updateFormData,
  onValidationError,
  initiatorEmail
}: ParticipantsStepProps) {
  const [emailInput, setEmailInput] = useState('');
  const { searchResults, searchLoading, searchUsersDebounced, clearSearch, ensureUser } = useUserSearch();

  const handleEmailInputChange = (value: string) => {
    setEmailInput(value);
    if (!value || !value.startsWith('@') || value.length < 2) {
      clearSearch();
      return;
    }
    searchUsersDebounced(value, 10);
  };

  const handleAddSpectator = async (user?: any) => {
    if (user) {
      // Add from search results
      if (user.email.toLowerCase() === initiatorEmail.toLowerCase()) {
        onValidationError({
          type: 'self-assign',
          email: user.email,
          message: 'You cannot add yourself as a spectator.'
        });
        return;
      }

      // Check for duplicates in spectators
      const isDuplicateSpectator = formData.spectators.some(
        (s: any) => s.userId === user.userId || s.email?.toLowerCase() === user.email?.toLowerCase()
      );

      // Check for duplicates in approvers
      const isDuplicateApprover = formData.approvers?.some(
        (approver: any) => approver.userId === user.userId || approver.email?.toLowerCase() === user.email?.toLowerCase()
      );

      if (isDuplicateSpectator) {
        onValidationError({
          type: 'error',
          email: user.email,
          message: 'This user is already added as a spectator.'
        });
        return;
      }

      if (isDuplicateApprover) {
        onValidationError({
          type: 'error',
          email: user.email,
          message: 'This user is already added as an approver. A user cannot be both an approver and a spectator.'
        });
        return;
      }

      try {
        const dbUser = await ensureUser(user);
        const spectator = {
          id: dbUser.userId,
          userId: dbUser.userId,
          name: dbUser.displayName || user.email.split('@')[0],
          email: dbUser.email,
          avatar: (dbUser.displayName || dbUser.email).substring(0, 2).toUpperCase(),
          role: 'Spectator',
          department: dbUser.department || '',
          level: 1,
          canClose: false
        };
        const updatedSpectators = [...formData.spectators, spectator];
        updateFormData('spectators', updatedSpectators);
        setEmailInput('');
        clearSearch();
      } catch (err) {
        onValidationError({
          type: 'error',
          email: user.email,
          message: 'Failed to validate user. Please try again.'
        });
      }
    } else if (emailInput && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput)) {
      // Add by email directly (will be validated)
      if (emailInput.toLowerCase() === initiatorEmail.toLowerCase()) {
        onValidationError({
          type: 'self-assign',
          email: emailInput,
          message: 'You cannot add yourself as a spectator.'
        });
        return;
      }

      // Check for duplicates in spectators by email
      const isDuplicateSpectator = formData.spectators.some(
        (s: any) => s.email?.toLowerCase() === emailInput.toLowerCase()
      );

      // Check for duplicates in approvers by email
      const isDuplicateApprover = formData.approvers?.some(
        (approver: any) => approver.email?.toLowerCase() === emailInput.toLowerCase()
      );

      if (isDuplicateSpectator) {
        onValidationError({
          type: 'error',
          email: emailInput,
          message: 'This user is already added as a spectator.'
        });
        return;
      }

      if (isDuplicateApprover) {
        onValidationError({
          type: 'error',
          email: emailInput,
          message: 'This user is already added as an approver. A user cannot be both an approver and a spectator.'
        });
        return;
      }
      // This would trigger validation in parent component
    }
  };

  const removeSpectator = (spectatorId: string) => {
    const updatedSpectators = formData.spectators.filter((s: any) => s.id !== spectatorId);
    updateFormData('spectators', updatedSpectators);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="space-y-6"
      data-testid="participants-step"
    >
      <div className="text-center mb-8" data-testid="participants-header">
        <div className="w-16 h-16 bg-gradient-to-br from-teal-500 to-green-600 rounded-2xl flex items-center justify-center mx-auto mb-4">
          <Eye className="w-8 h-8 text-white" />
        </div>
        <h2 className="text-2xl font-bold text-gray-900 mb-2" data-testid="participants-title">
          Participants & Access
        </h2>
        <p className="text-gray-600" data-testid="participants-description">
          Configure additional participants and visibility settings for your request.
        </p>
      </div>

      <div className="max-w-3xl mx-auto space-y-8" data-testid="participants-content">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Spectators */}
          <Card data-testid="participants-spectators-card">
            <CardHeader>
              <CardTitle className="flex items-center justify-between text-base" data-testid="participants-spectators-title">
                <div className="flex items-center gap-2">
                  <Eye className="w-4 h-4" />
                  Spectators
                </div>
                <Badge variant="outline" className="text-xs" data-testid="participants-spectators-count">
                  {formData.spectators.length}
                </Badge>
              </CardTitle>
              <CardDescription>
                Users who can view and comment but cannot approve
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2" data-testid="participants-spectators-add-section">
                <div className="flex items-center gap-2">
                  <div className="relative w-full">
                    <Input
                      placeholder="Use @ sign to add a user"
                      value={emailInput}
                      onChange={(e) => handleEmailInputChange(e.target.value)}
                      onKeyPress={async (e) => {
                        if (e.key === 'Enter' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput)) {
                          e.preventDefault();
                          await handleAddSpectator();
                        }
                      }}
                      className="text-sm w-full"
                      data-testid="participants-spectators-email-input"
                    />
                    {(searchLoading || searchResults.length > 0) && (
                      <div className="absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg">
                        {searchLoading ? (
                          <div className="p-2 text-xs text-gray-500">Searching...</div>
                        ) : (
                          <ul className="max-h-56 overflow-auto divide-y">
                            {searchResults.map(u => (
                              <li
                                key={u.userId}
                                className="p-2 text-sm cursor-pointer hover:bg-gray-50"
                                onClick={() => handleAddSpectator(u)}
                                data-testid={`participants-spectators-search-result-${u.userId}`}
                              >
                                <div className="font-medium text-gray-900">{u.displayName || u.email}</div>
                                <div className="text-xs text-gray-600">{u.email}</div>
                              </li>
                            ))}
                          </ul>
                        )}
                      </div>
                    )}
                  </div>
                  <Button
                    size="sm"
                    onClick={() => handleAddSpectator()}
                    disabled={!emailInput || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput)}
                    data-testid="participants-spectators-add-button"
                  >
                    Add
                  </Button>
                </div>
                <p className="text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1">
                  <Info className="w-3 h-3 flex-shrink-0" />
                  <span>
                    Use <span className="font-mono bg-blue-100 px-1 rounded">@</span> sign to search users, or type email directly (will be validated against organization directory)
                  </span>
                </p>
              </div>

              <div className="space-y-2 max-h-40 overflow-y-auto" data-testid="participants-spectators-list">
                {formData.spectators.map((spectator) => (
                  <div key={spectator.id} className="flex items-center justify-between p-2 bg-teal-50 rounded-lg" data-testid={`participants-spectator-${spectator.id}`}>
                    <div className="flex items-center gap-2">
                      <Avatar className="h-6 w-6">
                        <AvatarFallback className="bg-teal-600 text-white text-xs">
                          {spectator.avatar}
                        </AvatarFallback>
                      </Avatar>
                      <span className="text-sm font-medium">{spectator.name}</span>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeSpectator(spectator.id)}
                      data-testid={`participants-spectator-${spectator.id}-remove`}
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </motion.div>
  );
}


