/**
 * ClaimApproverSelectionStep Component
 * Step 2: Manual approver selection for all 8 steps in dealer claim workflow
 * Similar to ApprovalWorkflowStep but fixed to 8 steps with predefined step names
 */

import { motion } from 'framer-motion';
import { useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Users, Shield, CheckCircle, Info, Clock, User } from 'lucide-react';
import { useMultiUserSearch } from '@/hooks/useUserSearch';
import { ensureUserExists } from '@/services/userApi';
import { toast } from 'sonner';

// Fixed 8-step workflow for dealer claims
const CLAIM_STEPS = [
  { level: 1, name: 'Dealer Proposal Submission', description: 'Dealer submits proposal documents', defaultTat: 72, isAuto: false, approverType: 'dealer' },
  { level: 2, name: 'Requestor Evaluation', description: 'Initiator evaluates dealer proposal', defaultTat: 48, isAuto: false, approverType: 'initiator' },
  { level: 3, name: 'Department Lead Approval', description: 'Department lead approves and blocks IO budget', defaultTat: 72, isAuto: false, approverType: 'manual' },
  { level: 4, name: 'Activity Creation', description: 'System auto-processes activity creation', defaultTat: 1, isAuto: true, approverType: 'system' },
  { level: 5, name: 'Dealer Completion Documents', description: 'Dealer submits completion documents', defaultTat: 120, isAuto: false, approverType: 'dealer' },
  { level: 6, name: 'Requestor Claim Approval', description: 'Initiator approves completion', defaultTat: 48, isAuto: false, approverType: 'initiator' },
  { level: 7, name: 'E-Invoice Generation', description: 'System generates e-invoice via DMS', defaultTat: 1, isAuto: true, approverType: 'system' },
  { level: 8, name: 'Credit Note Confirmation', description: 'System/Finance processes credit note confirmation', defaultTat: 48, isAuto: true, approverType: 'system' },
];

interface ClaimApprover {
  email: string;
  name?: string;
  userId?: string;
  level: number;
  tat?: number | string;
  tatType?: 'hours' | 'days';
}

interface ClaimApproverSelectionStepProps {
  formData: {
    dealerEmail?: string;
    dealerName?: string;
    approvers?: ClaimApprover[];
  };
  updateFormData: (field: string, value: any) => void;
  onValidationError?: (error: { type: string; email: string; message: string }) => void;
  currentUserEmail?: string;
  currentUserId?: string;
  currentUserName?: string;
  onValidate?: (isValid: boolean) => void;
}

export function ClaimApproverSelectionStep({
  formData,
  updateFormData,
  onValidationError,
  currentUserEmail = '',
  currentUserId = '',
  currentUserName = '',
  onValidate,
}: ClaimApproverSelectionStepProps) {
  const { userSearchResults, userSearchLoading, searchUsersForIndex, clearSearchForIndex } = useMultiUserSearch();

  // Validation function to check for missing approvers
  const validateApprovers = (): { isValid: boolean; missingSteps: string[] } => {
    const approvers = formData.approvers || [];
    const missingSteps: string[] = [];

    CLAIM_STEPS.forEach((step) => {
      // Skip auto steps (system steps) and pre-filled steps (dealer, initiator)
      // Step 8 is now a system step, so it should be skipped from validation
      if (step.isAuto || step.approverType === 'dealer' || step.approverType === 'initiator') {
        return;
      }

      // For manual steps (3 and 8), check if approver is assigned, verified, and has TAT
      const approver = approvers.find((a: ClaimApprover) => a.level === step.level);
      
      if (!approver || !approver.email || !approver.userId || !approver.tat) {
        missingSteps.push(`Step ${step.level}: ${step.name}`);
      }
    });

    return {
      isValid: missingSteps.length === 0,
      missingSteps,
    };
  };

  // Expose validation to parent component
  useEffect(() => {
    if (onValidate) {
      const validation = validateApprovers();
      onValidate(validation.isValid);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formData.approvers]);

  // Initialize approvers array for all 8 steps
  useEffect(() => {
    const currentApprovers = formData.approvers || [];
    const newApprovers: ClaimApprover[] = [];

    CLAIM_STEPS.forEach((step) => {
      const existingApprover = currentApprovers.find((a: ClaimApprover) => a.level === step.level);
      
      if (step.isAuto) {
        // System steps - no approver needed
        // Step 8 is System/Finance, use finance email
        const systemEmail = step.level === 8 ? 'finance@royalenfield.com' : 'system@royalenfield.com';
        const systemName = step.level === 8 ? 'System/Finance' : 'System';
        newApprovers.push({
          email: systemEmail,
          name: systemName,
          level: step.level,
          tat: step.defaultTat,
          tatType: 'hours',
        });
      } else if (step.approverType === 'dealer') {
        // Dealer steps - use dealer email
        newApprovers.push({
          email: formData.dealerEmail || '',
          name: formData.dealerName || '',
          level: step.level,
          tat: step.defaultTat,
          tatType: 'hours',
        });
      } else if (step.approverType === 'initiator') {
        // Initiator steps - use current user
        newApprovers.push({
          email: currentUserEmail || '',
          name: currentUserName || currentUserEmail || 'User',
          userId: currentUserId,
          level: step.level,
          tat: step.defaultTat,
          tatType: 'hours',
        });
      } else {
        // Manual steps - use existing or create empty
        newApprovers.push(existingApprover || {
          email: '',
          name: '',
          level: step.level,
          tat: step.defaultTat,
          tatType: 'hours',
        });
      }
    });

    // Only update if approvers array is empty or structure changed
    if (currentApprovers.length === 0 || currentApprovers.length !== newApprovers.length) {
      updateFormData('approvers', newApprovers);
    }
  }, [formData.dealerEmail, formData.dealerName, currentUserEmail, currentUserId, currentUserName]);

  const handleApproverEmailChange = (level: number, value: string) => {
    const approvers = [...(formData.approvers || [])];
    const index = approvers.findIndex((a: ClaimApprover) => a.level === level);
    
    if (index === -1) {
      // Create new approver entry
      const step = CLAIM_STEPS.find(s => s.level === level);
      approvers.push({
        email: value,
        name: '',
        level: level,
        tat: step?.defaultTat || 48,
        tatType: 'hours',
      });
    } else {
      // Update existing approver
      const existingApprover = approvers[index];
      if (existingApprover) {
        const previousEmail = existingApprover.email;
        approvers[index] = {
          ...existingApprover,
          email: value,
          // Clear name and userId if email changed
          name: value !== previousEmail ? '' : existingApprover.name,
          userId: value !== previousEmail ? undefined : existingApprover.userId,
        };
      }
    }

    updateFormData('approvers', approvers);

    if (!value || !value.startsWith('@') || value.length < 2) {
      clearSearchForIndex(level - 1);
      return;
    }
    searchUsersForIndex(level - 1, value, 10);
  };

  const handleUserSelect = async (level: number, selectedUser: any) => {
    try {
      // Check if user is trying to select themselves for non-initiator steps
      const step = CLAIM_STEPS.find(s => s.level === level);
      if (step && !step.isAuto && step.approverType !== 'initiator' && selectedUser.email?.toLowerCase() === currentUserEmail?.toLowerCase()) {
        toast.error(`You cannot assign yourself as ${step.name} approver.`);
        if (onValidationError) {
          onValidationError({
            type: 'self-assign',
            email: selectedUser.email,
            message: `You cannot assign yourself as ${step.name} approver.`
          });
        }
        return;
      }

      // Check for duplicates across other steps
      const approvers = formData.approvers || [];
      const isDuplicate = approvers.some(
        (a: ClaimApprover) => 
          a.level !== level && 
          (a.userId === selectedUser.userId || a.email?.toLowerCase() === selectedUser.email?.toLowerCase())
      );

      if (isDuplicate) {
        toast.error('This user is already assigned to another step.');
        if (onValidationError) {
          onValidationError({
            type: 'error',
            email: selectedUser.email,
            message: 'This user is already assigned to another step.'
          });
        }
        return;
      }

      // Ensure user exists in database (create from Okta if needed)
      const dbUser = await ensureUserExists({
        userId: selectedUser.userId,
        email: selectedUser.email,
        displayName: selectedUser.displayName,
        firstName: selectedUser.firstName,
        lastName: selectedUser.lastName,
        department: selectedUser.department,
        phone: selectedUser.phone,
        mobilePhone: selectedUser.mobilePhone,
        designation: selectedUser.designation,
        jobTitle: selectedUser.jobTitle,
        manager: selectedUser.manager,
        employeeId: selectedUser.employeeId,
        employeeNumber: selectedUser.employeeNumber,
        secondEmail: selectedUser.secondEmail,
        location: selectedUser.location
      });

      // Update approver in array
      const updatedApprovers = [...(formData.approvers || [])];
      const approverIndex = updatedApprovers.findIndex((a: ClaimApprover) => a.level === level);
      
      if (approverIndex === -1) {
        const step = CLAIM_STEPS.find(s => s.level === level);
        updatedApprovers.push({
          email: selectedUser.email,
          name: selectedUser.displayName || [selectedUser.firstName, selectedUser.lastName].filter(Boolean).join(' '),
          userId: dbUser.userId,
          level: level,
          tat: step?.defaultTat || 48,
          tatType: 'hours' as const,
        });
      } else {
        const existingApprover = updatedApprovers[approverIndex];
        if (existingApprover) {
          updatedApprovers[approverIndex] = {
            ...existingApprover,
            email: selectedUser.email,
            name: selectedUser.displayName || [selectedUser.firstName, selectedUser.lastName].filter(Boolean).join(' '),
            userId: dbUser.userId,
          };
        }
      }

      updateFormData('approvers', updatedApprovers);
      clearSearchForIndex(level - 1);
      toast.success(`Approver for ${CLAIM_STEPS.find(s => s.level === level)?.name} selected successfully.`);
    } catch (err) {
      console.error('Failed to ensure user exists:', err);
      toast.error('Failed to validate user. Please try again.');
      if (onValidationError) {
        onValidationError({
          type: 'error',
          email: selectedUser.email,
          message: 'Failed to validate user. Please try again.'
        });
      }
    }
  };

  const handleTatChange = (level: number, tat: number | string) => {
    const approvers = [...(formData.approvers || [])];
    const index = approvers.findIndex((a: ClaimApprover) => a.level === level);
    
    if (index !== -1) {
      const existingApprover = approvers[index];
      if (existingApprover) {
        approvers[index] = {
          ...existingApprover,
          tat: tat,
        };
        updateFormData('approvers', approvers);
      }
    }
  };

  const handleTatTypeChange = (level: number, tatType: 'hours' | 'days') => {
    const approvers = [...(formData.approvers || [])];
    const index = approvers.findIndex((a: ClaimApprover) => a.level === level);
    
    if (index !== -1) {
      const existingApprover = approvers[index];
      if (existingApprover) {
        approvers[index] = {
          ...existingApprover,
          tatType: tatType,
          tat: '', // Clear TAT when changing type
        };
        updateFormData('approvers', approvers);
      }
    }
  };

  const approvers = formData.approvers || [];

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="space-y-6"
    >
      <div className="text-center mb-8">
        <div className="w-16 h-16 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4">
          <Users className="w-8 h-8 text-white" />
        </div>
        <h2 className="text-2xl font-bold text-gray-900 mb-2">Approver Selection</h2>
        <p className="text-gray-600">
          Assign approvers for all 8 workflow steps with TAT (Turn Around Time)
        </p>
      </div>

      <div className="max-w-4xl mx-auto space-y-6">
        {/* Info Card */}
        <Card className="border-2 border-blue-200 bg-blue-50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-blue-900">
              <Info className="w-5 h-5" />
              Workflow Steps Information
            </CardTitle>
            <CardDescription className="text-blue-700">
              Some steps are pre-filled (Dealer, Initiator, System). You need to assign approvers for Step 3 only. Step 8 is handled by System/Finance.
            </CardDescription>
          </CardHeader>
        </Card>

        {/* Approval Hierarchy */}
        <Card className="border-2">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Shield className="w-5 h-5" />
              Approval Hierarchy (8 Steps)
            </CardTitle>
            <CardDescription>
              Define approvers and TAT for each step. Steps 1, 2, 4, 5, 6, 7, 8 are pre-filled. Only Step 3 requires manual assignment.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-2 pt-4">
            {/* Initiator Card */}
            <div className="p-3 rounded-lg border-2 border-blue-200 bg-blue-50">
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center flex-shrink-0">
                  <User className="w-4 h-4 text-white" />
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-blue-900 text-sm">Request Initiator</span>
                    <Badge variant="secondary" className="text-xs">YOU</Badge>
                  </div>
                  <p className="text-xs text-blue-700">Creates and submits the request</p>
                </div>
              </div>
            </div>

            {/* Dynamic Approver Cards - Filter out system steps (auto-processed) */}
            {CLAIM_STEPS.filter((step) => !step.isAuto).map((step, index, filteredSteps) => {
              const approver = approvers.find((a: ClaimApprover) => a.level === step.level) || {
                email: '',
                name: '',
                level: step.level,
                tat: step.defaultTat,
                tatType: 'hours' as const,
              };

              const isLast = index === filteredSteps.length - 1;
              const isPreFilled = step.isAuto || step.approverType === 'dealer' || step.approverType === 'initiator';
              const isEditable = !step.isAuto;

              return (
                <div key={step.level} className="space-y-1">
                  <div className="flex justify-center">
                    <div className="w-px h-3 bg-gray-300"></div>
                  </div>
                  
                  <div className={`p-3 rounded-lg border-2 transition-all ${
                    approver.email && approver.userId
                      ? 'border-green-200 bg-green-50' 
                      : isPreFilled
                      ? 'border-blue-200 bg-blue-50'
                      : 'border-gray-200 bg-gray-50'
                  }`}>
                    <div className="flex items-start gap-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                        approver.email && approver.userId
                          ? 'bg-green-600' 
                          : isPreFilled
                          ? 'bg-blue-600'
                          : 'bg-gray-400'
                      }`}>
                        <span className="text-white font-semibold text-sm">{step.level}</span>
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                          <span className="font-semibold text-gray-900 text-sm">
                            {step.name}
                          </span>
                          {isLast && (
                            <Badge variant="destructive" className="text-xs">FINAL</Badge>
                          )}
                          {isPreFilled && (
                            <Badge variant="outline" className="text-xs">PRE-FILLED</Badge>
                          )}
                        </div>
                        <p className="text-xs text-gray-600 mb-2">{step.description}</p>
                        
                        {isEditable && (
                          <div className="space-y-2">
                            <div>
                              <div className="flex items-center justify-between mb-1">
                                <Label htmlFor={`approver-${step.level}`} className="text-xs font-medium">
                                  Email Address {!isPreFilled && '*'}
                                </Label>
                                {approver.email && approver.userId && (
                                  <Badge variant="outline" className="text-xs bg-green-50 text-green-700 border-green-300">
                                    <CheckCircle className="w-3 h-3 mr-1" />
                                    Verified
                                  </Badge>
                                )}
                              </div>
                              <div className="relative">
                                <Input
                                  id={`approver-${step.level}`}
                                  type="text"
                                  placeholder={isPreFilled ? approver.email : "@approver@royalenfield.com"}
                                  value={approver.email || ''}
                                  onChange={(e) => {
                                    const newValue = e.target.value;
                                    if (!isPreFilled) {
                                      handleApproverEmailChange(step.level, newValue);
                                    }
                                  }}
                                  disabled={isPreFilled || step.isAuto}
                                  className="h-9 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full text-sm"
                                />
                                {/* Search suggestions dropdown */}
                                {!isPreFilled && !step.isAuto && (userSearchLoading[step.level - 1] || (userSearchResults[step.level - 1]?.length || 0) > 0) && (
                                  <div className="absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg">
                                    {userSearchLoading[step.level - 1] ? (
                                      <div className="p-2 text-xs text-gray-500">Searching...</div>
                                    ) : (
                                      <ul className="max-h-56 overflow-auto divide-y">
                                        {userSearchResults[step.level - 1]?.map((u) => (
                                          <li
                                            key={u.userId}
                                            className="p-2 text-sm cursor-pointer hover:bg-gray-50"
                                            onClick={() => handleUserSelect(step.level, u)}
                                          >
                                            <div className="font-medium text-gray-900">{u.displayName || u.email}</div>
                                            <div className="text-xs text-gray-600">{u.email}</div>
                                            {u.department && (
                                              <div className="text-xs text-gray-500">{u.department}</div>
                                            )}
                                          </li>
                                        ))}
                                      </ul>
                                    )}
                                  </div>
                                )}
                              </div>
                              {approver.name && (
                                <p className="text-xs text-green-600 mt-1">
                                  Selected: <span className="font-semibold">{approver.name}</span>
                                </p>
                              )}
                            </div>

                            <div>
                              <Label htmlFor={`tat-${step.level}`} className="text-xs font-medium">
                                TAT (Turn Around Time) *
                              </Label>
                              <div className="flex items-center gap-2 mt-1">
                                <Input
                                  id={`tat-${step.level}`}
                                  type="number"
                                  placeholder={approver.tatType === 'days' ? '7' : '24'}
                                  min="1"
                                  max={approver.tatType === 'days' ? '30' : '720'}
                                  value={approver.tat || ''}
                                  onChange={(e) => handleTatChange(step.level, parseInt(e.target.value) || '')}
                                  disabled={step.isAuto}
                                  className="h-9 border-2 border-gray-300 focus:border-blue-500 flex-1 text-sm"
                                />
                                <Select
                                  value={approver.tatType || 'hours'}
                                  onValueChange={(value) => handleTatTypeChange(step.level, value as 'hours' | 'days')}
                                  disabled={step.isAuto}
                                >
                                  <SelectTrigger className="w-20 h-9 border-2 border-gray-300 text-sm">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="hours">Hours</SelectItem>
                                    <SelectItem value="days">Days</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </CardContent>
        </Card>

        {/* TAT Summary */}
        <Card className="border-2">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Clock className="w-5 h-5" />
              TAT Summary
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {approvers.map((approver: ClaimApprover) => {
                const step = CLAIM_STEPS.find(s => s.level === approver.level);
                if (!step || step.isAuto) return null;
                
                const tat = Number(approver.tat || 0);
                const tatType = approver.tatType || 'hours';
                const hours = tatType === 'days' ? tat * 24 : tat;
                if (!tat) return null;
                
                return (
                  <div key={approver.level} className="flex items-center justify-between p-2 bg-gray-50 rounded">
                    <span className="text-sm font-medium">Step {approver.level}: {step.name}</span>
                    <span className="text-sm text-gray-600">{hours} hours</span>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      </div>
    </motion.div>
  );
}

