import React, { useState } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { UserPlus, Shield, CheckCircle2, Mail, Phone, Loader2 } from 'lucide-react';
import { useTenant } from '../../../../stores/tenant.store';
import { authService } from '../../../../api/services/auth';

interface WizardDataProps extends WizardStepProps {
  data: Record<string, any>;
  onDataChange: (data: Record<string, any>) => void;
}

const MemberDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
  const [memberData, setMemberData] = useState({
    fullName: data.fullName || '',
    email: data.email || '',
    phone: data.phone || '',
    position: data.position || 'baker',
    employmentType: data.employmentType || 'full-time',
  });

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <UserPlus className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">Miembro del Equipo</h3>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Nombre Completo *</label>
          <input
            type="text"
            value={memberData.fullName}
            onChange={(e) => setMemberData({ ...memberData, fullName: e.target.value })}
            placeholder="Ej: Juan García"
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            <Mail className="w-3.5 h-3.5 inline mr-1" />
            Email *
          </label>
          <input
            type="email"
            value={memberData.email}
            onChange={(e) => setMemberData({ ...memberData, email: e.target.value })}
            placeholder="juan@panaderia.com"
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            <Phone className="w-3.5 h-3.5 inline mr-1" />
            Teléfono
          </label>
          <input
            type="tel"
            value={memberData.phone}
            onChange={(e) => setMemberData({ ...memberData, phone: e.target.value })}
            placeholder="+34 123 456 789"
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Posición *</label>
          <select
            value={memberData.position}
            onChange={(e) => setMemberData({ ...memberData, position: e.target.value })}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          >
            <option value="baker">Panadero</option>
            <option value="pastry-chef">Pastelero</option>
            <option value="manager">Gerente</option>
            <option value="sales">Ventas</option>
            <option value="delivery">Repartidor</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Tipo de Empleo</label>
          <select
            value={memberData.employmentType}
            onChange={(e) => setMemberData({ ...memberData, employmentType: e.target.value })}
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
          >
            <option value="full-time">Tiempo Completo</option>
            <option value="part-time">Medio Tiempo</option>
            <option value="contractor">Contratista</option>
          </select>
        </div>
      </div>
      <div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={() => {
            onDataChange({ ...data, ...memberData });
            onNext();
          }}
          disabled={!memberData.fullName || !memberData.email}
          className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          Continuar
        </button>
      </div>
    </div>
  );
};

const PermissionsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const { currentTenant } = useTenant();
  const [permissions, setPermissions] = useState({
    role: data.role || 'staff',
    canManageInventory: data.canManageInventory || false,
    canViewRecipes: data.canViewRecipes || true,
    canCreateOrders: data.canCreateOrders || false,
    canViewFinancial: data.canViewFinancial || false,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSave = async () => {
    if (!currentTenant?.id) {
      setError('No se pudo obtener información del tenant');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      // Generate a temporary password (in production, this should be sent via email)
      const tempPassword = `Temp${Math.random().toString(36).substring(2, 10)}!`;

      // Register the new team member
      const registrationData = {
        email: data.email,
        password: tempPassword,
        full_name: data.fullName,
        phone_number: data.phone || undefined,
        tenant_id: currentTenant.id,
        role: permissions.role,
      };

      await authService.register(registrationData);

      // In a real implementation, you would:
      // 1. Send email with temporary password
      // 2. Store permissions in a separate permissions table
      // 3. Link user to tenant with specific role

      onDataChange({ ...data, ...permissions, tempPassword });
      onComplete();
    } catch (err: any) {
      console.error('Error creating team member:', err);
      setError(err.response?.data?.detail || 'Error al crear el miembro del equipo');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Shield className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">Rol y Permisos</h3>
        <p className="text-sm text-[var(--text-secondary)]">{data.fullName}</p>
      </div>

      {error && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
          {error}
        </div>
      )}

      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-3">Rol del Sistema</label>
        <select
          value={permissions.role}
          onChange={(e) => setPermissions({ ...permissions, role: e.target.value })}
          className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
        >
          <option value="admin">Administrador</option>
          <option value="manager">Gerente</option>
          <option value="staff">Personal</option>
          <option value="view-only">Solo Lectura</option>
        </select>
      </div>
      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-3">Permisos Específicos</label>
        <div className="space-y-2">
          {[
            { key: 'canManageInventory', label: 'Gestionar Inventario' },
            { key: 'canViewRecipes', label: 'Ver Recetas' },
            { key: 'canCreateOrders', label: 'Crear Pedidos' },
            { key: 'canViewFinancial', label: 'Ver Datos Financieros' },
          ].map(({ key, label }) => (
            <label
              key={key}
              className="flex items-center gap-3 p-3 border border-[var(--border-secondary)] rounded-lg cursor-pointer hover:bg-[var(--bg-secondary)]/30"
            >
              <input
                type="checkbox"
                checked={permissions[key as keyof typeof permissions] as boolean}
                onChange={(e) => setPermissions({ ...permissions, [key]: e.target.checked })}
                className="w-4 h-4 text-[var(--color-primary)] rounded focus:ring-[var(--color-primary)]"
              />
              <span className="text-sm text-[var(--text-primary)]">{label}</span>
            </label>
          ))}
        </div>
      </div>
      <div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={handleSave}
          disabled={loading}
          className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Guardando...
            </>
          ) : (
            <>
              <CheckCircle2 className="w-5 h-5" />
              Agregar Miembro
            </>
          )}
        </button>
      </div>
    </div>
  );
};

export const TeamMemberWizardSteps = (data: Record<string, any>, setData: (data: Record<string, any>) => void): WizardStep[] => [
  { id: 'member-details', title: 'Datos Personales', description: 'Nombre, contacto, posición', component: (props) => <MemberDetailsStep {...props} data={data} onDataChange={setData} /> },
  { id: 'member-permissions', title: 'Rol y Permisos', description: 'Accesos al sistema', component: (props) => <PermissionsStep {...props} data={data} onDataChange={setData} /> },
];
