'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { api, apiPaths } from '@/lib/api';
import { useAuthGuard } from '@/lib/useAuthGuard';
import { useI18n } from '@/lib/i18n/context';

type SessionLog = {
  id: number;
  ip_address: string | null;
  device_info: string | null;
  platform: string | null;
  browser?: string;
  os_label?: string;
  device_label?: string;
  logged_in_at: string | null;
  logged_in_human?: string | null;
};

export default function SessionsPage() {
  const { t, locale, isRtl } = useI18n();
  const { checked, authenticated } = useAuthGuard();
  const [sessions, setSessions] = useState<SessionLog[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!authenticated) return;
    api.get<SessionLog[]>(apiPaths.user.sessionLogs).then((res) => {
      if (res.key === 'success' && res.data) {
        setSessions(res.data as SessionLog[]);
      }
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [authenticated]);

  if (!checked) return null;

  const getPlatformIcon = (platform: string | null | undefined, osLabel?: string) => {
    const p = (platform || osLabel || '').toLowerCase();
    if (p.includes('ios') || p.includes('iphone')) return 'ri-apple-line';
    if (p.includes('android')) return 'ri-android-line';
    if (p.includes('windows')) return 'ri-windows-line';
    return 'ri-computer-line';
  };

  const titleFor = (s: SessionLog) =>
    s.device_label?.trim() ||
    s.os_label?.trim() ||
    s.platform?.trim() ||
    s.browser?.trim() ||
    t('sessionsPage.deviceFallback');

  const dateLocale = locale === 'en' ? 'en-US' : 'ar-SA';

  return (
    <div dir={isRtl ? 'rtl' : 'ltr'} className="flex flex-col flex-1 bg-gradient-to-br from-blue-50 via-white to-gray-50">
      <main className="max-w-2xl mx-auto px-6 py-8 flex-1 w-full">
        <div className="flex items-center gap-4 mb-6">
          <Link
            href="/profile"
            className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
            aria-label={t('profilePage.title')}
          >
            <i className={`${isRtl ? 'ri-arrow-right-line' : 'ri-arrow-left-line'} text-xl text-gray-700`}></i>
          </Link>
          <h1 className="text-xl font-bold text-gray-900">{t('sessionsPage.title')}</h1>
        </div>
        <p className="text-gray-600 mb-6">سجل عمليات تسجيل الدخول لحسابك (الجهاز، المتصفح، عنوان IP)</p>

        {loading ? (
          <div className="flex justify-center py-12">
            <div className="w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : sessions.length === 0 ? (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
            <i className="ri-history-line text-5xl text-gray-300 mb-4 block"></i>
            <p className="text-gray-500">لا يوجد سجل جلسات</p>
          </div>
        ) : (
          <div className="space-y-3">
            {sessions.map((session) => (
              <div key={session.id} className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-start gap-4">
                <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center flex-shrink-0">
                  <i className={`${getPlatformIcon(session.platform, session.os_label)} text-2xl text-blue-600`}></i>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2 mb-1 flex-wrap">
                    <span className="font-semibold text-gray-900">{titleFor(session)}</span>
                    <span className="text-sm text-gray-500 whitespace-nowrap">
                      {session.logged_in_at
                        ? new Date(session.logged_in_at).toLocaleDateString(dateLocale, {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                          })
                        : ''}
                    </span>
                  </div>
                  {session.browser && session.os_label && (
                    <p className="text-sm text-gray-600">
                      <span className="font-medium">{session.browser}</span>
                      {session.os_label ? ` · ${session.os_label}` : ''}
                    </p>
                  )}
                  {session.device_info && (
                    <p className="text-xs text-gray-500 break-all mt-1" title={session.device_info}>
                      {session.device_info.length > 120 ? `${session.device_info.slice(0, 120)}…` : session.device_info}
                    </p>
                  )}
                  {session.logged_in_human && (
                    <p className="text-xs text-gray-400 mt-1">{session.logged_in_human}</p>
                  )}
                  {session.ip_address && (
                    <p className="text-xs text-gray-500 mt-2 font-mono flex items-center gap-1" dir="ltr">
                      <i className="ri-map-pin-line text-base"></i>
                      {session.ip_address}
                    </p>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}
