'use client'

import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { parseOS, parseBrowser } from '@/utils/parseUserAgent'
import { formatDateTime } from '@/utils/formatDate'
import { useToast } from '@/contexts/ToastContext'

interface Device {
    id: string
    deviceType: string
    deviceName: string
    userAgent: string
    lastLoginDate: string
    currentSession: boolean
}

export default function LoginDevicesTab() {
    const { t } = useTranslation()
    const { showToast } = useToast()
    const [devices, setDevices] = useState<Device[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetchDevices()
    }, [])

    const fetchDevices = async () => {
        setLoading(true)
        try {
            const response = await fetch('/api/profile/login-devices')
            const data = await response.json()
            if (data.ok) {
                setDevices(data.devices || [])
            }
        } catch (error) {
            console.error('Failed to fetch login devices:', error)
        } finally {
            setLoading(false)
        }
    }

    const handleDisconnect = async (deviceId: string) => {
        if (!window.confirm(t('profile.loginDevices.confirmDisconnect'))) return

        try {
            const response = await fetch('/api/profile/login-devices', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ deviceId }),
            })
            const data = await response.json()
            if (data.ok) {
                fetchDevices()
                showToast(t('profile.loginDevices.disconnectSuccess'), 'success')
            } else {
                showToast(data.message || t('common.error'), 'error')
            }
        } catch (error) {
            console.error('Failed to disconnect device:', error)
            showToast(t('common.error'), 'error')
        }
    }

    const handleDisconnectAll = async () => {
        if (!window.confirm(t('profile.loginDevices.confirmDisconnectAll'))) return

        try {
            const response = await fetch('/api/profile/login-devices', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ all: true }),
            })
            const data = await response.json()
            if (data.ok) {
                fetchDevices()
                showToast(t('profile.loginDevices.disconnectAllSuccess'), 'success')
            } else {
                showToast(data.message || t('common.error'), 'error')
            }
        } catch (error) {
            console.error('Failed to disconnect all devices:', error)
            showToast(t('common.error'), 'error')
        }
    }

    const total = devices.length

    return (
        <div>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-6 leading-relaxed">
                {t('profile.loginDevices.description')}
            </p>

            <div className="bg-white dark:bg-[#0c0d0e] rounded-2xl border border-gray-200 dark:border-gray-700 p-4 md:p-6">
                <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2">
                        <h3 className="text-lg font-semibold">{t('profile.loginDevices.listTitle')}</h3>
                        <span className="text-sm text-gray-600 dark:text-gray-400">
                            (<em className="not-italic text-gray-900 dark:text-white">{total}</em>)
                        </span>
                    </div>
                    {total > 0 && (
                        <button
                            onClick={handleDisconnectAll}
                            className="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                        >
                            {t('profile.loginDevices.disconnectAll')}
                        </button>
                    )}
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full border-collapse">
                        <colgroup>
                            <col style={{ width: '35%' }} />
                            <col style={{ width: '35%' }} />
                            <col style={{ width: '20%' }} />
                            <col style={{ width: '10%' }} />
                        </colgroup>
                        <thead>
                            <tr className="bg-gray-50 dark:bg-gray-900">
                                <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-left text-sm font-medium text-gray-700 dark:text-gray-200 px-4">
                                    {t('profile.loginDevices.table.os')}
                                </th>
                                <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-left text-sm font-medium text-gray-700 dark:text-gray-200 px-4">
                                    {t('profile.loginDevices.table.type')}
                                </th>
                                <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-left text-sm font-medium text-gray-700 dark:text-gray-200 px-4">
                                    {t('profile.loginDevices.table.lastLogin')}
                                </th>
                                <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-left text-sm font-medium text-gray-700 dark:text-gray-200 px-4">
                                    {t('profile.loginDevices.table.manage')}
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {loading ? (
                                <tr>
                                    <td
                                        className="py-24 border-b border-gray-100 dark:border-gray-800 text-center text-sm text-gray-600 dark:text-gray-400"
                                        colSpan={4}
                                    >
                                        {t('common.loading')}
                                    </td>
                                </tr>
                            ) : total === 0 ? (
                                <tr>
                                    <td
                                        className="py-24 border-b border-gray-100 dark:border-gray-800 text-center text-sm text-gray-600 dark:text-gray-400"
                                        colSpan={4}
                                    >
                                        {t('profile.loginDevices.noDevices')}
                                    </td>
                                </tr>
                            ) : (
                                devices.map((device) => {
                                    const os = parseOS(device.userAgent)
                                    const browser = parseBrowser(device.userAgent)
                                    return (
                                        <tr key={device.id} className="border-b border-gray-100 dark:border-gray-800">
                                            <td className="py-4 px-4 text-sm text-gray-700 dark:text-gray-300">
                                                {os}
                                            </td>
                                            <td className="py-4 px-4 text-sm text-gray-700 dark:text-gray-300">
                                                {browser}
                                            </td>
                                            <td className="py-4 px-4 text-sm text-gray-700 dark:text-gray-300">
                                                {formatDateTime(device.lastLoginDate)}
                                            </td>
                                            <td className="py-4 px-4 text-sm">
                                                {device.currentSession ? (
                                                    <span className="text-blue-500">{t('profile.loginDevices.currentDevice')}</span>
                                                ) : (
                                                    <button
                                                        onClick={() => handleDisconnect(device.id)}
                                                        className="px-3 py-1 text-sm border border-[#d5d7dc] dark:border-gray-700 rounded-lg text-gray-900 dark:text-white hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] transition-colors"
                                                    >
                                                        {t('profile.loginDevices.disconnect')}
                                                    </button>
                                                )}
                                            </td>
                                        </tr>
                                    )
                                })
                            )}
                        </tbody>
                    </table>
                </div>

                <dl className="mt-6 text-sm">
                    <dt className="font-medium text-gray-900 dark:text-white mb-2">
                        {t('profile.loginDevices.notice.title')}
                    </dt>
                    <dd>
                        <ul className="list-disc list-inside text-gray-600 dark:text-gray-400 space-y-1">
                            <li>{t('profile.loginDevices.notice.item1')}</li>
                            <li>{t('profile.loginDevices.notice.item2')}</li>
                            <li>{t('profile.loginDevices.notice.item3')}</li>
                        </ul>
                    </dd>
                </dl>
            </div>
        </div>
    )
}

