import React, { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Smartphone, Monitor, Clock } from 'lucide-react';
import { useToast } from '../../../context/ToastContext';
import { sessionService, Session } from '../../../services/sessionService';
import { logger } from '@/utils/logger';

export const SessionManagement: React.FC = () => {
  const { addToast } = useToast();
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadSessions();
  }, []);

  const loadSessions = async () => {
    try {
      setLoading(true);
      const res = await sessionService.getSessions();
      setSessions(res.sessions);
    } catch (error) {
      logger.error('Error loading sessions', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
    } finally {
      setLoading(false);
    }
  };

  const handleRevoke = async (id: string) => {
    try {
      await sessionService.revokeSession(id);
      setSessions((prev) => prev.filter((s) => s.id !== id));
      addToast('Session revoked successfully', 'success');
    } catch (error) {
      addToast('Failed to revoke session', 'error');
    }
  };

  const handleRevokeAll = async () => {
    try {
      await sessionService.logoutAll();
      // Ideally reload or clear all except current, but for safety re-fetch
      loadSessions();
      addToast('All other sessions have been logged out', 'success');
    } catch (error) {
      addToast('Failed to log out all devices', 'error');
    }
  };

  if (loading)
    return (
      <div className="text-center p-4 text-gray-500">Loading sessions...</div>
    );

  return (
    <Card variant="default">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h3 className="text-xl font-bold text-white">Active Sessions</h3>
          <p className="text-sm text-gray-400">
            Manage devices logged into your account.
          </p>
        </div>
        <Button
          variant="ghost"
          className="text-kodo-red hover:bg-kodo-red/10 border-kodo-red/30"
          onClick={handleRevokeAll}
        >
          Log Out All Other Devices
        </Button>
      </div>

      <div className="space-y-4">
        {sessions.map((session) => {
          // Simple heuristics for icon since backend might not provide device type explicitly yet
          const isMobile = session.user_agent.toLowerCase().includes('mobile');
          return (
            <div
              key={session.id}
              className="flex flex-col md:flex-row md:items-center justify-between p-4 bg-kodo-ink rounded-xl border border-kodo-steel hover:border-kodo-cyan/30 transition-colors"
            >
              <div className="flex items-start gap-4">
                <div
                  className={`p-3 rounded-full ${session.is_current ? 'bg-kodo-cyan/10 text-kodo-cyan' : 'bg-kodo-slate text-gray-400'}`}
                >
                  {isMobile ? (
                    <Smartphone className="w-6 h-6" />
                  ) : (
                    <Monitor className="w-6 h-6" />
                  )}
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <h4 className="font-bold text-white text-sm">
                      {session.ip_address}
                    </h4>
                    {session.is_current && (
                      <span className="bg-kodo-lime/10 text-kodo-lime text-[10px] px-2 py-0.5 rounded border border-kodo-lime/30 font-bold">
                        CURRENT DEVICE
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-gray-400 mt-1 truncate max-w-xs">
                    {session.user_agent}
                  </p>
                  <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                    <span className="flex items-center gap-1">
                      <Clock className="w-3 h-3" /> Active:{' '}
                      {new Date(session.last_activity).toLocaleString()}
                    </span>
                  </div>
                </div>
              </div>

              {!session.is_current && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="mt-4 md:mt-0 text-gray-400 hover:text-white border border-kodo-steel hover:bg-white/5"
                  onClick={() => handleRevoke(session.id)}
                >
                  Revoke Access
                </Button>
              )}
            </div>
          );
        })}
        {sessions.length === 0 && (
          <p className="text-gray-500 text-sm">No active sessions found.</p>
        )}
      </div>
    </Card>
  );
};
