/**
 * Transfer Ownership Modal Component
 *
 * Allows the current tenant owner to transfer ownership to another admin.
 * This is a critical operation with multiple confirmation steps.
 */

import React, { useState } from 'react';
import { Crown, AlertTriangle, Shield, ChevronRight } from 'lucide-react';
import { StatusModal } from '../../ui';
import { TENANT_ROLES } from '../../../types/roles';

export interface TeamMember {
  id: string;
  user_id: string;
  role: string;
  is_active: boolean;
  user_email?: string | null;
  user_full_name?: string | null;
  joined_at?: string | null;
}

interface TransferOwnershipModalProps {
  isOpen: boolean;
  onClose: () => void;
  onTransfer: (newOwnerId: string) => Promise<void>;
  currentOwner: TeamMember | null;
  eligibleMembers: TeamMember[]; // Only admins should be eligible
  tenantName: string;
}

const TransferOwnershipModal: React.FC<TransferOwnershipModalProps> = ({
  isOpen,
  onClose,
  onTransfer,
  currentOwner,
  eligibleMembers,
  tenantName,
}) => {
  const [selectedMemberId, setSelectedMemberId] = useState<string>('');
  const [confirmationStep, setConfirmationStep] = useState<1 | 2>(1);
  const [confirmationText, setConfirmationText] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const selectedMember = eligibleMembers.find(m => m.user_id === selectedMemberId);
  const requiredConfirmationText = 'TRANSFERIR PROPIEDAD';

  const handleReset = () => {
    setSelectedMemberId('');
    setConfirmationStep(1);
    setConfirmationText('');
    setError(null);
    setIsProcessing(false);
  };

  const handleClose = () => {
    handleReset();
    onClose();
  };

  const handleNextStep = () => {
    if (!selectedMember) {
      setError('Por favor selecciona un miembro');
      return;
    }
    setError(null);
    setConfirmationStep(2);
  };

  const handleTransfer = async () => {
    if (confirmationText !== requiredConfirmationText) {
      setError(`Por favor escribe "${requiredConfirmationText}" para confirmar`);
      return;
    }

    if (!selectedMember) {
      setError('No se ha seleccionado ningún miembro');
      return;
    }

    try {
      setIsProcessing(true);
      setError(null);
      await onTransfer(selectedMember.user_id);
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al transferir la propiedad');
      setIsProcessing(false);
    }
  };

  return (
    <StatusModal
      isOpen={isOpen}
      onClose={handleClose}
      title="Transferir Propiedad"
      subtitle={`Organización: ${tenantName}`}
      size="lg"
      preventClose={isProcessing}
    >
      <div className="space-y-6">
        {/* Warning Banner */}
        <div className="bg-color-warning bg-opacity-10 border border-color-warning rounded-lg p-4">
          <div className="flex items-start gap-3">
            <AlertTriangle className="w-5 h-5 text-color-warning flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <h4 className="font-semibold text-text-primary mb-1">
                Acción Irreversible
              </h4>
              <p className="text-sm text-text-secondary">
                Transferir la propiedad es permanente. El nuevo propietario tendrá control total
                de la organización y podrá cambiar todos los permisos, incluyendo los tuyos.
              </p>
            </div>
          </div>
        </div>

        {/* Step 1: Select New Owner */}
        {confirmationStep === 1 && (
          <div className="space-y-4">
            <div>
              <h3 className="text-lg font-semibold text-text-primary mb-2">
                Paso 1: Selecciona el Nuevo Propietario
              </h3>
              <p className="text-sm text-text-secondary mb-4">
                Solo puedes transferir la propiedad a un administrador actual de la organización.
              </p>
            </div>

            {/* Current Owner Info */}
            <div className="bg-bg-tertiary rounded-lg p-4">
              <div className="flex items-center gap-3 mb-2">
                <Crown className="w-5 h-5 text-color-primary" />
                <span className="text-sm font-medium text-text-secondary">
                  Propietario Actual
                </span>
              </div>
              <div className="ml-8">
                <p className="font-medium text-text-primary">
                  {currentOwner?.user_full_name || currentOwner?.user_email || 'Usuario actual'}
                </p>
                <p className="text-sm text-text-secondary">
                  {currentOwner?.user_email}
                </p>
              </div>
            </div>

            {/* Eligible Members Selection */}
            <div>
              <label className="block text-sm font-medium text-text-primary mb-3">
                Selecciona el nuevo propietario:
              </label>
              {eligibleMembers.length === 0 ? (
                <div className="bg-bg-tertiary rounded-lg p-4 text-center">
                  <Shield className="w-12 h-12 text-text-tertiary mx-auto mb-2" />
                  <p className="text-sm text-text-secondary">
                    No hay administradores disponibles para la transferencia.
                  </p>
                  <p className="text-xs text-text-tertiary mt-1">
                    Primero promociona a un miembro a administrador.
                  </p>
                </div>
              ) : (
                <div className="space-y-2">
                  {eligibleMembers.map((member) => (
                    <button
                      key={member.user_id}
                      onClick={() => {
                        setSelectedMemberId(member.user_id);
                        setError(null);
                      }}
                      className={`
                        w-full text-left p-4 rounded-lg border-2 transition-all
                        ${selectedMemberId === member.user_id
                          ? 'border-color-primary bg-color-primary bg-opacity-5'
                          : 'border-border-primary hover:border-border-hover bg-bg-secondary'
                        }
                      `}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3 flex-1">
                          <div className={`
                            w-10 h-10 rounded-full flex items-center justify-center
                            ${selectedMemberId === member.user_id
                              ? 'bg-color-primary text-text-inverse'
                              : 'bg-bg-tertiary text-text-secondary'
                            }
                          `}>
                            <Shield className="w-5 h-5" />
                          </div>
                          <div className="flex-1">
                            <p className="font-medium text-text-primary">
                              {member.user_full_name || member.user_email}
                            </p>
                            <p className="text-sm text-text-secondary">
                              {member.user_email}
                            </p>
                            <p className="text-xs text-text-tertiary mt-1">
                              Rol actual: Administrador
                            </p>
                          </div>
                        </div>
                        {selectedMemberId === member.user_id && (
                          <div className="w-6 h-6 rounded-full bg-color-primary flex items-center justify-center">
                            <svg className="w-4 h-4 text-text-inverse" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                            </svg>
                          </div>
                        )}
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>

            {error && (
              <div className="bg-color-error bg-opacity-10 border border-color-error rounded-lg p-3">
                <p className="text-sm text-color-error">{error}</p>
              </div>
            )}

            {/* Actions */}
            <div className="flex justify-end gap-3 pt-4 border-t border-border-primary">
              <button
                onClick={handleClose}
                className="btn btn-outline"
                disabled={isProcessing}
              >
                Cancelar
              </button>
              <button
                onClick={handleNextStep}
                disabled={!selectedMember || eligibleMembers.length === 0 || isProcessing}
                className="btn btn-primary flex items-center gap-2"
              >
                Continuar
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}

        {/* Step 2: Confirmation */}
        {confirmationStep === 2 && selectedMember && (
          <div className="space-y-4">
            <div>
              <h3 className="text-lg font-semibold text-text-primary mb-2">
                Paso 2: Confirma la Transferencia
              </h3>
              <p className="text-sm text-text-secondary mb-4">
                Por favor revisa cuidadosamente antes de confirmar.
              </p>
            </div>

            {/* Transfer Summary */}
            <div className="bg-bg-tertiary rounded-lg p-4 space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Crown className="w-5 h-5 text-text-secondary" />
                  <div>
                    <p className="text-xs text-text-tertiary">De</p>
                    <p className="font-medium text-text-primary">
                      {currentOwner?.user_full_name || currentOwner?.user_email}
                    </p>
                  </div>
                </div>
                <ChevronRight className="w-5 h-5 text-text-tertiary" />
                <div className="flex items-center gap-3">
                  <Crown className="w-5 h-5 text-color-primary" />
                  <div>
                    <p className="text-xs text-text-tertiary">A</p>
                    <p className="font-medium text-text-primary">
                      {selectedMember.user_full_name || selectedMember.user_email}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* Consequences List */}
            <div className="bg-color-warning bg-opacity-5 rounded-lg p-4">
              <h4 className="font-semibold text-text-primary mb-3">
                Qué sucederá:
              </h4>
              <ul className="space-y-2 text-sm text-text-secondary">
                <li className="flex items-start gap-2">
                  <span className="text-color-warning mt-0.5">•</span>
                  <span>
                    <strong>{selectedMember.user_full_name || selectedMember.user_email}</strong> será
                    el nuevo propietario con control total
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-color-warning mt-0.5">•</span>
                  <span>Tu rol cambiará a <strong>Administrador</strong></span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-color-warning mt-0.5">•</span>
                  <span>El nuevo propietario podrá modificar tu rol o remover tu acceso</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-color-warning mt-0.5">•</span>
                  <span>Esta acción <strong>no se puede deshacer</strong></span>
                </li>
              </ul>
            </div>

            {/* Confirmation Input */}
            <div>
              <label className="block text-sm font-medium text-text-primary mb-2">
                Escribe <code className="bg-bg-tertiary px-2 py-1 rounded text-color-error font-mono text-xs">
                  {requiredConfirmationText}
                </code> para confirmar:
              </label>
              <input
                type="text"
                value={confirmationText}
                onChange={(e) => {
                  setConfirmationText(e.target.value);
                  setError(null);
                }}
                placeholder={requiredConfirmationText}
                className="input w-full font-mono"
                disabled={isProcessing}
                autoComplete="off"
              />
            </div>

            {error && (
              <div className="bg-color-error bg-opacity-10 border border-color-error rounded-lg p-3">
                <p className="text-sm text-color-error">{error}</p>
              </div>
            )}

            {/* Actions */}
            <div className="flex justify-end gap-3 pt-4 border-t border-border-primary">
              <button
                onClick={() => {
                  setConfirmationStep(1);
                  setConfirmationText('');
                  setError(null);
                }}
                className="btn btn-outline"
                disabled={isProcessing}
              >
                Atrás
              </button>
              <button
                onClick={handleTransfer}
                disabled={confirmationText !== requiredConfirmationText || isProcessing}
                className="btn btn-error flex items-center gap-2"
              >
                {isProcessing ? (
                  <>
                    <div className="spinner spinner-sm"></div>
                    Transfiriendo...
                  </>
                ) : (
                  <>
                    <Crown className="w-4 h-4" />
                    Transferir Propiedad
                  </>
                )}
              </button>
            </div>
          </div>
        )}
      </div>
    </StatusModal>
  );
};

export default TransferOwnershipModal;
