import React, { useState, useMemo } from 'react';
import { Plus, Users, Shield, UserPlus } from 'lucide-react';
import { AddModal } from '../../ui/AddModal/AddModal';
import { TENANT_ROLES } from '../../../types/roles';
import { statusColors } from '../../../styles/colors';

interface AddTeamMemberModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddMember?: (userData: { userId?: string; role: string; createUser?: boolean; email?: string; fullName?: string; password?: string; phone?: string }) => Promise<void>;
  availableUsers: Array<{ id: string; full_name: string; email: string }>;
}

/**
 * AddTeamMemberModal - Modal for adding a new member to the team
 * Supports both adding existing users and creating new users (pilot phase)
 */
export const AddTeamMemberModal: React.FC<AddTeamMemberModalProps> = ({
  isOpen,
  onClose,
  onAddMember,
  availableUsers
}) => {
  const [loading, setLoading] = useState(false);
  const [createNewUser, setCreateNewUser] = useState(false);

  const handleSave = async (formData: Record<string, any>) => {
    const isCreatingNewUser = formData.createNewUser === true || formData.createNewUser === 'true';

    // Validation based on mode
    if (isCreatingNewUser) {
      // Creating new user - validate required fields
      if (!formData.email || !formData.fullName || !formData.password) {
        throw new Error('Por favor completa todos los campos requeridos: email, nombre completo y contraseña');
      }

      if (formData.password !== formData.confirmPassword) {
        throw new Error('Las contraseñas no coinciden');
      }

      if (formData.password.length < 8) {
        throw new Error('La contraseña debe tener al menos 8 caracteres');
      }
    } else {
      // Adding existing user - validate userId
      if (!formData.userId) {
        throw new Error('Por favor selecciona un usuario');
      }
    }

    if (!formData.role) {
      throw new Error('Por favor selecciona un rol');
    }

    setLoading(true);
    try {
      if (onAddMember) {
        await onAddMember({
          userId: isCreatingNewUser ? undefined : formData.userId,
          role: formData.role,
          createUser: isCreatingNewUser,
          email: isCreatingNewUser ? formData.email : undefined,
          fullName: isCreatingNewUser ? formData.fullName : undefined,
          password: isCreatingNewUser ? formData.password : undefined,
          phone: isCreatingNewUser ? formData.phone : undefined,
        });
      }
    } catch (error) {
      console.error('Error adding team member:', error);
      throw error; // Let AddModal handle error display
    } finally {
      setLoading(false);
    }
  };

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: 'Nuevo Miembro',
    icon: Plus,
    isCritical: false,
    isHighlight: true
  };

  const roleOptions = [
    { label: 'Miembro - Acceso estándar', value: TENANT_ROLES.MEMBER },
    { label: 'Administrador - Gestión de equipo', value: TENANT_ROLES.ADMIN },
    { label: 'Observador - Solo lectura', value: TENANT_ROLES.VIEWER }
  ];

  const userOptions = availableUsers.length > 0
    ? availableUsers.map(user => ({
        label: `${user.full_name} (${user.email})`,
        value: user.id
      }))
    : [];

  // Use useMemo to recalculate sections when createNewUser changes
  const sections = useMemo(() => {
    const userFields = [];

    // Add mode toggle
    userFields.push({
      label: 'Modo de Adición',
      name: 'createNewUser',
      type: 'select' as const,
      required: true,
      options: [
        { label: 'Agregar Usuario Existente', value: 'false' },
        { label: 'Crear Nuevo Usuario', value: 'true' }
      ],
      defaultValue: 'false',
      helpText: 'Selecciona si quieres agregar un usuario existente o crear uno nuevo'
    });

    // Conditional fields based on create mode
    if (createNewUser) {
      // Fields for creating new user
      userFields.push(
        {
          label: 'Email',
          name: 'email',
          type: 'email' as const,
          required: true,
          placeholder: 'usuario@ejemplo.com',
          helpText: 'Email del nuevo usuario (se usará para iniciar sesión)',
          validation: (value: string | number) => {
            const email = String(value);
            if (!email || !email.includes('@')) {
              return 'Por favor ingresa un email válido';
            }
            return null;
          }
        },
        {
          label: 'Nombre Completo',
          name: 'fullName',
          type: 'text' as const,
          required: true,
          placeholder: 'Juan Pérez',
          helpText: 'Nombre completo del nuevo usuario'
        },
        {
          label: 'Contraseña',
          name: 'password',
          type: 'password' as const,
          required: true,
          placeholder: '••••••••',
          helpText: 'Contraseña inicial (mínimo 8 caracteres)',
          validation: (value: string | number) => {
            const pwd = String(value);
            if (pwd && pwd.length < 8) {
              return 'La contraseña debe tener al menos 8 caracteres';
            }
            return null;
          }
        },
        {
          label: 'Confirmar Contraseña',
          name: 'confirmPassword',
          type: 'password' as const,
          required: true,
          placeholder: '••••••••',
          helpText: 'Repite la contraseña'
        },
        {
          label: 'Teléfono (opcional)',
          name: 'phone',
          type: 'tel' as const,
          placeholder: '+34 600 000 000',
          helpText: 'Número de teléfono del usuario'
        }
      );
    } else {
      // Field for selecting existing user
      if (userOptions.length > 0) {
        userFields.push({
          label: 'Usuario',
          name: 'userId',
          type: 'select' as const,
          required: true,
          options: userOptions,
          placeholder: 'Seleccionar usuario...',
          helpText: 'Selecciona el usuario que quieres agregar al equipo'
        });
      } else {
        userFields.push({
          label: 'No hay usuarios disponibles',
          name: 'noUsers',
          type: 'text' as const,
          disabled: true,
          defaultValue: 'No hay usuarios disponibles para agregar. Crea un nuevo usuario.',
          helpText: 'Cambia el modo a "Crear Nuevo Usuario" para agregar miembros'
        });
      }
    }

    // Add role field (common to both modes)
    userFields.push({
      label: 'Rol en el Equipo',
      name: 'role',
      type: 'select' as const,
      required: true,
      options: roleOptions,
      defaultValue: TENANT_ROLES.MEMBER,
      helpText: 'Selecciona el nivel de acceso para este usuario'
    });

    return [
      {
        title: createNewUser ? 'Crear Nuevo Usuario' : 'Seleccionar Usuario',
        icon: createNewUser ? UserPlus : Users,
        fields: userFields
      }
    ];
  }, [createNewUser, userOptions, roleOptions]);

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title="Agregar Miembro al Equipo"
      subtitle="Agregar un nuevo miembro al equipo de la panadería"
      statusIndicator={statusConfig}
      sections={sections}
      size="lg"
      loading={loading}
      onSave={handleSave}
      onFieldChange={(fieldName, value) => {
        // Handle the mode toggle field change
        if (fieldName === 'createNewUser') {
          setCreateNewUser(value === 'true');
        }
      }}
    />
  );
};

export default AddTeamMemberModal;