import { useState, useEffect } from 'react';
import { apiClient } from '@/services/api/client';
import { parseApiError } from '@/utils/apiErrorHandler';
import { logger } from '@/utils/logger';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Badge } from '@/components/ui/badge';
import {
  Shield,
  Smartphone,
  Monitor,
  Globe,
  Trash2,
  LogOut,
  MapPin,
  Laptop,
  Tablet,
} from 'lucide-react';
import {
  parseUserAgent,
  formatDeviceInfo,
  type DeviceInfo,
} from '../utils/userAgentParser';
import {
  formatLocation,
  isPrivateIP,
  type LocationInfo,
} from '../utils/ipLocation';
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog';

// FE-PAGE-012: Complete Sessions page implementation

interface Session {
  id: string;
  ip_address: string;
  user_agent: string;
  last_activity: string;
  created_at: string;
  is_current: boolean;
  device_info?: DeviceInfo;
  location_info?: LocationInfo | null;
}

interface SessionsResponse {
  sessions: Session[];
  count: number;
}

export function SessionsPage() {
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);
  const [revoking, setRevoking] = useState<string | null>(null);
  const [revokingAll, setRevokingAll] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sessionToRevoke, setSessionToRevoke] = useState<string | null>(null);
  const [showRevokeAllDialog, setShowRevokeAllDialog] = useState(false);

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

  const fetchSessions = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await apiClient.get<SessionsResponse>('/auth/sessions');
      setSessions(response.data.sessions);
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      logger.error('Failed to fetch sessions', { message: apiError.message });
      setError(apiError.message);
    } finally {
      setLoading(false);
    }
  };

  const handleRevokeClick = (sessionId: string) => {
    setSessionToRevoke(sessionId);
  };

  const revokeSession = async () => {
    if (!sessionToRevoke) return;

    try {
      setRevoking(sessionToRevoke);
      setError(null);
      await apiClient.delete(`/auth/sessions/${sessionToRevoke}`);
      await fetchSessions();
      setSessionToRevoke(null);
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      logger.error('Failed to revoke session', {
        message: apiError.message,
        sessionId: sessionToRevoke,
      });
      setError(apiError.message);
    } finally {
      setRevoking(null);
    }
  };

  const handleRevokeAllClick = () => {
    setShowRevokeAllDialog(true);
  };

  const revokeAllOther = async () => {
    try {
      setRevokingAll(true);
      setError(null);
      await apiClient.delete('/auth/sessions');
      await fetchSessions();
      setShowRevokeAllDialog(false);
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      logger.error('Failed to revoke sessions', { message: apiError.message });
      setError(apiError.message);
    } finally {
      setRevokingAll(false);
    }
  };

  const getDeviceIcon = (deviceType: string) => {
    switch (deviceType) {
      case 'mobile':
        return <Smartphone className="h-5 w-5" />;
      case 'tablet':
        return <Tablet className="h-5 w-5" />;
      case 'desktop':
        return <Laptop className="h-5 w-5" />;
      default:
        return <Monitor className="h-5 w-5" />;
    }
  };

  // Parse device info for all sessions
  const sessionsWithDeviceInfo: Session[] = sessions.map((session) => {
    const deviceInfo = parseUserAgent(session.user_agent);
    return {
      ...session,
      device_info: deviceInfo,
      location_info: isPrivateIP(session.ip_address)
        ? { country: 'Local', region: 'Network', city: 'Private IP' }
        : null,
    };
  });

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    }).format(date);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <LoadingSpinner />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* En-tête */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Active Sessions</h1>
        <p className="text-muted-foreground">
          Manage your active sessions and sign out from other devices
        </p>
      </div>

      {/* Message d'erreur */}
      {error && (
        <div className="bg-destructive/10 text-destructive px-4 py-3 rounded-md">
          {error}
        </div>
      )}

      {/* Bouton pour révoquer toutes les autres sessions */}
      <div className="flex justify-end">
        <Button
          onClick={handleRevokeAllClick}
          disabled={revokingAll || sessions.length <= 1}
          variant="destructive"
        >
          {revokingAll ? (
            <>
              <LoadingSpinner className="mr-2 h-4 w-4" />
              Revoking...
            </>
          ) : (
            <>
              <LogOut className="mr-2 h-4 w-4" />
              Revoke All Other Sessions
            </>
          )}
        </Button>
      </div>

      {/* Liste des sessions */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Sessions ({sessions.length})
          </CardTitle>
          <CardDescription>
            These are the devices where you're currently signed in
          </CardDescription>
        </CardHeader>
        <CardContent>
          {sessions.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              No active sessions found.
            </div>
          ) : (
            <div className="space-y-4">
              {sessionsWithDeviceInfo.map((session) => {
                const deviceInfo =
                  session.device_info || parseUserAgent(session.user_agent);
                const locationInfo = session.location_info;

                return (
                  <div
                    key={session.id}
                    className={`flex items-center justify-between p-4 border rounded-lg ${
                      session.is_current
                        ? 'border-primary bg-primary/5'
                        : 'border-border'
                    }`}
                  >
                    <div className="flex items-start gap-4 flex-1">
                      <div className="mt-1">
                        {getDeviceIcon(deviceInfo.deviceType)}
                      </div>
                      <div className="flex-1 space-y-2">
                        <div className="flex items-center gap-2 flex-wrap">
                          <p className="font-medium">
                            {formatDeviceInfo(deviceInfo)}
                          </p>
                          {session.is_current && (
                            <Badge
                              variant="default"
                              className="bg-primary text-primary-foreground"
                            >
                              Current Session
                            </Badge>
                          )}
                          <Badge variant="secondary" className="capitalize">
                            {deviceInfo.deviceType}
                          </Badge>
                        </div>
                        <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                          <div className="flex items-center gap-1">
                            <Globe className="h-4 w-4" />
                            <span>{session.ip_address || 'Unknown IP'}</span>
                          </div>
                          {locationInfo && (
                            <div className="flex items-center gap-1">
                              <MapPin className="h-4 w-4" />
                              <span>{formatLocation(locationInfo)}</span>
                            </div>
                          )}
                          <div>
                            <span className="font-medium">Created:</span>{' '}
                            {formatDate(session.created_at)}
                          </div>
                          {session.last_activity && (
                            <div>
                              <span className="font-medium">
                                Last activity:
                              </span>{' '}
                              {formatDate(session.last_activity)}
                            </div>
                          )}
                        </div>
                        {deviceInfo.browserVersion && (
                          <div className="text-xs text-muted-foreground">
                            {deviceInfo.browser} {deviceInfo.browserVersion}
                            {deviceInfo.osVersion &&
                              ` • ${deviceInfo.os} ${deviceInfo.osVersion}`}
                          </div>
                        )}
                      </div>
                    </div>
                    {!session.is_current && (
                      <Button
                        onClick={() => handleRevokeClick(session.id)}
                        disabled={revoking === session.id}
                        variant="destructive"
                        size="sm"
                      >
                        {revoking === session.id ? (
                          <>
                            <LoadingSpinner className="mr-2 h-4 w-4" />
                            Revoking...
                          </>
                        ) : (
                          <>
                            <Trash2 className="mr-2 h-4 w-4" />
                            Revoke
                          </>
                        )}
                      </Button>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      <ConfirmationDialog
        open={!!sessionToRevoke}
        onClose={() => setSessionToRevoke(null)}
        onConfirm={revokeSession}
        title="Revoke Session"
        description="Are you sure you want to revoke this session? The user will be logged out from this device."
        confirmLabel="Revoke"
        cancelLabel="Cancel"
        variant="destructive"
        isLoading={!!revoking}
      />
      <ConfirmationDialog
        open={showRevokeAllDialog}
        onClose={() => setShowRevokeAllDialog(false)}
        onConfirm={revokeAllOther}
        title="Revoke All Other Sessions"
        description="Are you sure you want to revoke all other sessions? You will remain logged in on this device, but all other devices will be logged out."
        confirmLabel="Revoke All"
        cancelLabel="Cancel"
        variant="destructive"
        isLoading={revokingAll}
      />
    </div>
  );
}

export default SessionsPage;
