/**
 * DeviceCard Component
 * Displays a single session/device with revocation capability
 */

import { useState } from 'react';
import type { ActiveSession } from '../../../services/auth.service';
import { authService } from '../../../services/auth.service';

// ============================================================================
// Device Icons
// ============================================================================

const DesktopIcon = ({ className = 'w-6 h-6' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
      d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
  </svg>
);

const MobileIcon = ({ className = 'w-6 h-6' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
      d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
  </svg>
);

const TabletIcon = ({ className = 'w-6 h-6' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
      d="M12 18h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
  </svg>
);

const UnknownDeviceIcon = ({ className = 'w-6 h-6' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
      d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" />
  </svg>
);

// ============================================================================
// Types
// ============================================================================

interface DeviceCardProps {
  session: ActiveSession;
  isRevoking: boolean;
  onRevoke: (sessionId: string) => Promise<void>;
}

// ============================================================================
// Component
// ============================================================================

export function DeviceCard({ session, isRevoking, onRevoke }: DeviceCardProps) {
  const [showConfirm, setShowConfirm] = useState(false);
  const parsedInfo = authService.parseUserAgent(session.userAgent);
  const relativeTime = authService.formatRelativeTime(session.lastActiveAt);

  // Use backend-provided device info if available, otherwise use parsed info
  const deviceInfo = {
    type: (session.deviceType as 'desktop' | 'mobile' | 'tablet' | 'unknown') || parsedInfo.type,
    os: session.os || parsedInfo.os,
    browser: session.browser || parsedInfo.browser,
  };

  // Format location from backend data
  const location = session.city && session.countryCode
    ? `${session.city}, ${session.countryCode}`
    : session.countryCode || null;

  // Get device icon based on type
  const DeviceIcon = {
    desktop: DesktopIcon,
    mobile: MobileIcon,
    tablet: TabletIcon,
    unknown: UnknownDeviceIcon,
  }[deviceInfo.type];

  const handleRevoke = async () => {
    try {
      await onRevoke(session.id);
      setShowConfirm(false);
    } catch {
      // Error is handled in parent
    }
  };

  return (
    <div className={`
      relative p-4 rounded-lg border transition-all
      ${session.isCurrent
        ? 'bg-emerald-500/10 border-emerald-500/30 dark:bg-emerald-500/5'
        : 'bg-slate-800/50 border-slate-700 hover:border-slate-600'
      }
    `}>
      <div className="flex items-start gap-4">
        {/* Device Icon */}
        <div className={`
          flex-shrink-0 p-2.5 rounded-lg
          ${session.isCurrent
            ? 'bg-emerald-500/20 text-emerald-400'
            : 'bg-slate-700 text-slate-400'
          }
        `}>
          <DeviceIcon className="w-6 h-6" />
        </div>

        {/* Device Info */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <h4 className="font-medium text-white truncate">
              {deviceInfo.browser} on {deviceInfo.os}
            </h4>
            {session.isCurrent && (
              <span className="flex-shrink-0 px-2 py-0.5 text-xs font-medium rounded-full bg-emerald-500/20 text-emerald-400">
                Current
              </span>
            )}
          </div>

          <div className="mt-1 text-sm text-slate-400 space-y-1">
            <p className="flex items-center gap-2">
              <span className="inline-flex items-center gap-1">
                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                {location ? `${location} (${session.ipAddress || 'Unknown IP'})` : session.ipAddress || 'Unknown IP'}
              </span>
            </p>
            <p className="flex items-center gap-2">
              <span className="inline-flex items-center gap-1">
                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                    d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Last active: {relativeTime}
              </span>
            </p>
          </div>
        </div>

        {/* Revoke Button */}
        <div className="flex-shrink-0">
          {showConfirm ? (
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={handleRevoke}
                disabled={isRevoking}
                className="px-3 py-1.5 text-xs font-medium text-white bg-red-600 rounded hover:bg-red-700 disabled:opacity-50 transition-colors"
              >
                {isRevoking ? (
                  <span className="flex items-center gap-1">
                    <svg className="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                    Revoking...
                  </span>
                ) : (
                  'Confirm'
                )}
              </button>
              <button
                type="button"
                onClick={() => setShowConfirm(false)}
                disabled={isRevoking}
                className="px-3 py-1.5 text-xs font-medium text-slate-300 bg-slate-700 rounded hover:bg-slate-600 disabled:opacity-50 transition-colors"
              >
                Cancel
              </button>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => setShowConfirm(true)}
              className={`
                px-3 py-1.5 text-xs font-medium rounded transition-colors
                ${session.isCurrent
                  ? 'text-slate-300 bg-slate-700 hover:bg-slate-600'
                  : 'text-red-400 bg-red-500/10 hover:bg-red-500/20'
                }
              `}
            >
              {session.isCurrent ? 'Log Out' : 'Revoke'}
            </button>
          )}
        </div>
      </div>

      {/* Session created timestamp (subtle) */}
      <div className="mt-3 pt-3 border-t border-slate-700/50">
        <p className="text-xs text-slate-500">
          Session started: {new Date(session.createdAt).toLocaleString()}
        </p>
      </div>
    </div>
  );
}

export default DeviceCard;
