import { useEffect, useState, useCallback } from 'react';
import { Loader2, RefreshCw, LogIn } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@shared/components/ui/card';
import { Badge } from '@shared/components/ui/badge';
import { Button } from '@shared/components/ui/button';
import { PageContainer, PageHeader } from '@shared/components/layout';
import { fetchLoginHistory, fetchLoginStats, type LoginHistory, type LoginStats } from '@/services/adminApi';
import { formatDateTime, formatDate } from '@shared/utils/dateFormat';
import { getLoginResultIntent, getLoginResultLabel } from '@shared/constants/loginResultStatuses';
import { useSettingsStore } from '@stores/settingsStore';
import { useTranslation } from 'react-i18next';

/**
 * 로그인 이력 조회 + 메트릭 카드.
 * 권한: admin:login-history (READ)
 */
export function LoginHistoryView() {
  const { t: tc } = useTranslation('common');
  const lang = useSettingsStore((s) => s.language);
  const [items, setItems] = useState<LoginHistory[]>([]);
  const [stats, setStats] = useState<LoginStats | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true); setError('');
    try {
      const [logs, st] = await Promise.all([fetchLoginHistory(0, 100), fetchLoginStats()]);
      setItems(logs.content);
      setStats(st);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'unknown');
    } finally {
      setLoading(false);
    }
  }, []);

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

  return (
    <PageContainer size="lg">
      <PageHeader
        icon={LogIn}
        iconColor="text-green-400"
        title="로그인 이력"
        description="성공/실패 로그인 시도 기록 (5회 실패 시 자동 잠금)"
        actions={
          <Button variant="primary" size="sm" onClick={load} icon={<RefreshCw className="w-3.5 h-3.5" />}>
            새로고침
          </Button>
        }
      />

      {/* 통계 카드 */}
      {stats && (
        <div className="grid grid-cols-5 gap-3">
          <MetricCard label="전체 시도" value={stats.total} color="text-heading" />
          <MetricCard label="성공 (24h)" value={stats.success24h} color="text-green-400" />
          <MetricCard label="실패 (24h)" value={stats.failed24h} color="text-orange-400" />
          <MetricCard label="잠금 (24h)" value={stats.locked24h} color="text-red-400" />
          <MetricCard label="성공률 (24h)" value={stats.successRate} color="text-cyan-400" suffix="%" />
        </div>
      )}

      {/* 사용자별 + 일자별 추세 */}
      {stats && (stats.byUser.length > 0 || stats.daily7d.length > 0) && (
        <div className="grid grid-cols-2 gap-3">
          {stats.byUser.length > 0 && (
            <Card>
              <CardHeader className="px-4 pt-3 pb-2"><CardTitle className="text-xs text-label">사용자별 성공 로그인 (7일)</CardTitle></CardHeader>
              <CardContent className="px-4 pb-4 space-y-1">
                {stats.byUser.map((u) => (
                  <div key={u.user_acnt} className="flex items-center justify-between text-[11px]">
                    <span className="text-cyan-400 font-mono">{u.user_acnt}</span>
                    <span className="text-heading font-bold">{u.count}회</span>
                  </div>
                ))}
              </CardContent>
            </Card>
          )}
          {stats.daily7d.length > 0 && (
            <Card>
              <CardHeader className="px-4 pt-3 pb-2"><CardTitle className="text-xs text-label">일별 추세 (7일)</CardTitle></CardHeader>
              <CardContent className="px-4 pb-4 space-y-1">
                {stats.daily7d.map((d) => (
                  <div key={d.day} className="flex items-center justify-between text-[11px]">
                    <span className="text-muted-foreground font-mono">{formatDate(d.day)}</span>
                    <div className="flex gap-3">
                      <span className="text-green-400">성공 {d.success}</span>
                      <span className="text-orange-400">실패 {d.failed}</span>
                      <span className="text-red-400">잠금 {d.locked}</span>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
          )}
        </div>
      )}

      {error && <div className="text-xs text-red-400">에러: {error}</div>}

      {loading && <div className="flex items-center justify-center py-12 text-muted-foreground"><Loader2 className="w-5 h-5 animate-spin" /></div>}

      {!loading && (
        <Card>
          <CardContent className="p-0 overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="bg-surface-overlay text-hint">
                <tr>
                  <th className="px-3 py-2 text-left">SN</th>
                  <th className="px-3 py-2 text-left">시각</th>
                  <th className="px-3 py-2 text-left">계정</th>
                  <th className="px-3 py-2 text-left">결과</th>
                  <th className="px-3 py-2 text-left">실패 사유</th>
                  <th className="px-3 py-2 text-left">인증 방식</th>
                  <th className="px-3 py-2 text-left">IP</th>
                </tr>
              </thead>
              <tbody>
                {items.length === 0 && <tr><td colSpan={7} className="px-3 py-8 text-center text-hint">로그인 이력이 없습니다.</td></tr>}
                {items.map((it) => (
                  <tr key={it.histSn} className="border-t border-border hover:bg-surface-overlay/50">
                    <td className="px-3 py-2 text-hint font-mono">{it.histSn}</td>
                    <td className="px-3 py-2 text-muted-foreground text-[10px]">{formatDateTime(it.loginDtm)}</td>
                    <td className="px-3 py-2 text-cyan-400">{it.userAcnt}</td>
                    <td className="px-3 py-2">
                      <Badge intent={getLoginResultIntent(it.result)} size="sm">{getLoginResultLabel(it.result, tc, lang)}</Badge>
                    </td>
                    <td className="px-3 py-2 text-red-400 text-[10px]">{it.failReason || '-'}</td>
                    <td className="px-3 py-2 text-muted-foreground">{it.authProvider || '-'}</td>
                    <td className="px-3 py-2 text-muted-foreground text-[10px]">{it.loginIp || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CardContent>
        </Card>
      )}
    </PageContainer>
  );
}

function MetricCard({ label, value, color, suffix }: { label: string; value: number; color: string; suffix?: string }) {
  return (
    <Card>
      <CardContent className="p-4">
        <div className="text-[10px] text-hint">{label}</div>
        <div className={`text-2xl font-bold ${color} mt-1`}>{value.toLocaleString()}{suffix && <span className="text-sm ml-1">{suffix}</span>}</div>
      </CardContent>
    </Card>
  );
}
