import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { useToast } from '@/hooks/use-toast';
import { Monitor, Smartphone, Tablet, Trash2 } from 'lucide-react';
import { format } from 'date-fns';

interface UserSession {
  id: string;
  device_info: any;
  last_activity: string;
  created_at: string;
  expires_at: string;
  session_token: string;
}

export function SessionsTab() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [sessions, setSessions] = useState<UserSession[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchSessions = async () => {
    if (!user) return;
    
    const { data, error } = await supabase
      .from('user_sessions')
      .select('*')
      .eq('user_id', user.id)
      .order('last_activity', { ascending: false });
    
    if (error) {
      console.error('Error fetching sessions:', error);
    } else {
      setSessions(data || []);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchSessions();
  }, [user]);

  const revokeSession = async (sessionId: string) => {
    const { error } = await supabase
      .from('user_sessions')
      .delete()
      .eq('id', sessionId);
    
    if (error) {
      toast({
        title: 'Error',
        description: 'Failed to revoke session',
        variant: 'destructive'
      });
    } else {
      toast({
        title: 'Success',
        description: 'Session revoked successfully'
      });
      fetchSessions();
    }
  };

  const getDeviceIcon = (deviceInfo: any) => {
    const ua = deviceInfo?.userAgent?.toLowerCase() || '';
    if (ua.includes('mobile')) return <Smartphone className="w-4 h-4" />;
    if (ua.includes('tablet')) return <Tablet className="w-4 h-4" />;
    return <Monitor className="w-4 h-4" />;
  };

  if (loading) {
    return <div className="text-muted-foreground">Loading sessions...</div>;
  }

  return (
    <div className="space-y-4">
      <div>
        <h3 className="text-lg font-semibold">Active Sessions</h3>
        <p className="text-sm text-muted-foreground">
          Manage your active login sessions across devices
        </p>
      </div>

      {sessions.map((session) => (
        <Card key={session.id} className="p-4">
          <div className="flex items-start justify-between">
            <div className="flex gap-3">
              {getDeviceIcon(session.device_info)}
              <div>
                <div className="font-medium">
                  {session.device_info?.browser || 'Unknown Browser'}
                </div>
                <div className="text-sm text-muted-foreground">
                  Last active: {format(new Date(session.last_activity), 'PPpp')}
                </div>
                <div className="text-sm text-muted-foreground">
                  Expires: {format(new Date(session.expires_at), 'PPpp')}
                </div>
              </div>
            </div>
            <Button
              variant="destructive"
              size="sm"
              onClick={() => revokeSession(session.id)}
            >
              <Trash2 className="w-4 h-4 mr-2" />
              Revoke
            </Button>
          </div>
        </Card>
      ))}

      {sessions.length === 0 && (
        <Card className="p-8 text-center text-muted-foreground">
          No active sessions found
        </Card>
      )}
    </div>
  );
}
