'use client'

import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { formatDateTime } from '@/utils/formatDate'

interface LoginRecord {
    id: string
    connDate: string
    ipInfo: string
    country: string
    countryEng: string
}

export default function LoginHistoryTab() {
    const { t } = useTranslation()
    const [period, setPeriod] = useState<7 | 30 | 90>(7)
    const [page, setPage] = useState(1)
    const [records, setRecords] = useState<LoginRecord[]>([])
    const [total, setTotal] = useState(0)
    const [maxIp, setMaxIp] = useState('')
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetchData()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [period, page])

    const fetchData = async () => {
        setLoading(true)
        try {
            const response = await fetch(`/api/profile/login-history?period=${period}&page=${page}&pageSize=15`)
            const data = await response.json()
            if (data.ok) {
                setRecords(data.records || [])
                setTotal(data.total || 0)
                setMaxIp(data.maxIp || '')
            }
        } catch (error) {
            console.error('Failed to fetch login history:', error)
        } finally {
            setLoading(false)
        }
    }

    const getDateRange = () => {
        const today = new Date()
        const startDate = new Date(today)
        startDate.setDate(today.getDate() - period)
        return {
            start: startDate.toLocaleDateString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '.'),
            end: today.toLocaleDateString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '.'),
        }
    }

    const dateRange = getDateRange()
    const totalPages = Math.ceil(total / 15)
    const periodOptions = [7, 30, 90] as const

    return (
        <div>
            {/* 表格（封鎖使用者風格的卡片 + 標題 + 篩選） */}
            <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.loginHistory.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>
                </div>

                {/* 統計摘要 */}
                <p className="mb-4 text-sm sm:text-base text-gray-700 dark:text-gray-200">
                    {t('profile.loginHistory.summary')
                        .replace('{{period}}', String(period))
                        .replace('{{count}}', String(total))
                        .replace('{{maxIp}}', maxIp || '-')}
                </p>

                {/* 時間篩選 + 日期區間（移入表格容器上方） */}
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4">
                    <ul className="flex items-center justify-center sm:justify-start text-sm">
                        {periodOptions.map((days, index) => {
                            const isFirst = index === 0
                            const isLast = index === periodOptions.length - 1
                            const isActive = period === days
                            return (
                                <li key={days} className="-mr-px">
                                    <button
                                        onClick={() => {
                                            setPeriod(days as 7 | 30 | 90)
                                            setPage(1)
                                        }}
                                        className={`min-w-[93px] h-7 px-[15px] border text-[12px] leading-[25px] text-center transition-colors
                                            ${isFirst ? 'rounded-l-[2px]' : ''}
                                            ${isLast ? 'rounded-r-[2px]' : ''}
                                            ${isActive
                                                ? 'bg-black text-white border-black dark:bg-white dark:text-black dark:border-white'
                                                : 'bg-transparent text-gray-700 border-gray-400 hover:bg-black hover:text-white hover:border-black dark:text-gray-200 dark:border-gray-500 dark:hover:bg-white dark:hover:text-black dark:hover:border-white'}`}
                                    >
                                        {days}
                                        {t('profile.loginHistory.days')}
                                    </button>
                                </li>
                            )
                        })}
                    </ul>
                    <div className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">
                        {dateRange.start} ~ {dateRange.end}
                    </div>
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full border-collapse">
                        <colgroup>
                            <col style={{ width: '40%' }} />
                            <col style={{ width: '30%' }} />
                            <col style={{ width: '30%' }} />
                        </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.loginHistory.table.dateTime')}
                                </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.loginHistory.table.ipAddress')}
                                </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.loginHistory.table.country')}
                                </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={3}
                                    >
                                        {t('common.loading')}
                                    </td>
                                </tr>
                            ) : records.length === 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={3}
                                    >
                                        {t('profile.loginHistory.noRecords')}
                                    </td>
                                </tr>
                            ) : (
                                records.map((record) => (
                                    <tr key={record.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">
                                            {formatDateTime(record.connDate)}
                                        </td>
                                        <td className="py-4 px-4 text-sm text-gray-700 dark:text-gray-300">
                                            {record.ipInfo}
                                        </td>
                                        <td className="py-4 px-4 text-sm">
                                            {record.countryEng && record.countryEng !== 'Korea, Republic of' ? (
                                                <span className="text-red-500">{record.country}</span>
                                            ) : (
                                                <span className="text-gray-700 dark:text-gray-300">
                                                    {record.country || '-'}
                                                </span>
                                            )}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* 分頁 */}
            {!loading && totalPages > 1 && (
                <div className="flex justify-center items-center gap-2 mt-6">
                    {page > 1 && (
                        <button
                            onClick={() => setPage(page - 1)}
                            className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-800"
                        >
                            {t('common.previous')}
                        </button>
                    )}
                    {Array.from({ length: Math.min(10, totalPages) }, (_, i) => {
                        const pageNum = i + 1
                        return (
                            <button
                                key={pageNum}
                                onClick={() => setPage(pageNum)}
                                className={`px-3 py-1 text-sm border rounded ${page === pageNum
                                    ? 'bg-blue-500 text-white border-blue-500'
                                    : 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800'
                                    }`}
                            >
                                {pageNum}
                            </button>
                        )
                    })}
                    {page < totalPages && (
                        <button
                            onClick={() => setPage(page + 1)}
                            className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-800"
                        >
                            {t('common.next')}
                        </button>
                    )}
                </div>
            )}
        </div>
    )
}

