import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import type { ApiKey } from '../../types/apikey';
import { getMyKeys, revokeKey } from '../../services/apiKeyService';
import Badge from '../../components/ui/Badge';
import type { BadgeVariant } from '../../components/ui/Badge';
import Button from '../../components/ui/Button';

const STATUS_VARIANT: Record<string, BadgeVariant> = {
  ACTIVE: 'success',
  PENDING: 'warning',
  REVOKED: 'danger',
  EXPIRED: 'default',
  INACTIVE: 'danger',
};

const formatDateTime = (dateStr: string | null): string => {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString('ko-KR');
};

const MyKeysPage = () => {
  const navigate = useNavigate();
  const [keys, setKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [rawKeyModal, setRawKeyModal] = useState<{ keyName: string; rawKey: string } | null>(null);
  const [copied, setCopied] = useState(false);

  const fetchKeys = async () => {
    try {
      setLoading(true);
      const res = await getMyKeys();
      if (res.success && res.data) {
        setKeys(res.data);
      } else {
        setError(res.message || 'API Key 목록을 불러오는데 실패했습니다.');
      }
    } catch {
      setError('API Key 목록을 불러오는데 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

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

  const handleRevoke = async (key: ApiKey) => {
    if (!window.confirm(`'${key.keyName}' 키를 폐기하시겠습니까? 이 작업은 되돌릴 수 없습니다.`)) return;

    try {
      const res = await revokeKey(key.apiKeyId);
      if (res.success) {
        await fetchKeys();
      } else {
        setError(res.message || '키 폐기에 실패했습니다.');
      }
    } catch {
      setError('키 폐기에 실패했습니다.');
    }
  };

  const handleCopyRawKey = async () => {
    if (!rawKeyModal) return;
    await navigator.clipboard.writeText(rawKeyModal.rawKey);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  if (loading) {
    return <div className="max-w-7xl mx-auto text-center py-10 text-[var(--color-text-secondary)]">로딩 중...</div>;
  }

  return (
    <div className="max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-[var(--color-text-primary)]">My API Keys</h1>
        <div className="flex gap-2">
          <Button onClick={() => navigate('/apikeys/request')}>
            API Key 신청
          </Button>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>
      )}

      <div className="overflow-x-auto bg-[var(--color-bg-surface)] rounded-lg shadow">
        <table className="w-full divide-y divide-[var(--color-border)] text-sm">
          <thead className="bg-[var(--color-bg-base)]">
            <tr>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Key Name</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Prefix</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Status</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Expires At</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Last Used At</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Created At</th>
              <th className="px-4 py-3 text-left font-medium text-[var(--color-text-secondary)]">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--color-border)]">
            {keys.map((key) => (
              <tr key={key.apiKeyId} className="hover:bg-[var(--color-bg-base)]">
                <td className="px-4 py-3 text-[var(--color-text-primary)]">{key.keyName}</td>
                <td className="px-4 py-3 font-mono text-[var(--color-text-secondary)]">{key.apiKeyPrefix}</td>
                <td className="px-4 py-3">
                  <Badge variant={STATUS_VARIANT[key.status] ?? 'default'}>
                    {key.status}
                  </Badge>
                </td>
                <td className="px-4 py-3 text-[var(--color-text-secondary)]">{formatDateTime(key.expiresAt)}</td>
                <td className="px-4 py-3 text-[var(--color-text-secondary)]">{formatDateTime(key.lastUsedAt)}</td>
                <td className="px-4 py-3 text-[var(--color-text-secondary)]">{formatDateTime(key.createdAt)}</td>
                <td className="px-4 py-3">
                  {key.status === 'ACTIVE' && (
                    <Button
                      onClick={() => handleRevoke(key)}
                      variant="danger"
                      size="sm"
                    >
                      폐기
                    </Button>
                  )}
                </td>
              </tr>
            ))}
            {keys.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-8 text-center text-[var(--color-text-tertiary)]">
                  등록된 API Key가 없습니다.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {rawKeyModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-[var(--color-bg-surface)] rounded-lg shadow-xl w-full max-w-lg mx-4">
            <div className="px-6 py-4 border-b border-[var(--color-border)]">
              <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">API Key 생성 완료</h2>
            </div>
            <div className="px-6 py-4 space-y-4">
              <div className="p-3 bg-yellow-50 border border-yellow-200 text-yellow-800 rounded-lg text-sm">
                이 키는 다시 표시되지 않습니다. 안전한 곳에 보관하세요.
              </div>
              <div>
                <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">Key Name</label>
                <p className="text-[var(--color-text-primary)]">{rawKeyModal.keyName}</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-[var(--color-text-primary)] mb-1">API Key</label>
                <div className="flex items-center gap-2">
                  <code className="flex-1 bg-[var(--color-bg-base)] px-3 py-2 rounded-lg text-sm font-mono break-all text-[var(--color-text-primary)]">
                    {rawKeyModal.rawKey}
                  </code>
                  <Button
                    onClick={handleCopyRawKey}
                    variant="primary"
                    size="sm"
                    className="shrink-0"
                  >
                    {copied ? '복사됨!' : '복사'}
                  </Button>
                </div>
              </div>
            </div>
            <div className="px-6 py-4 border-t border-[var(--color-border)] flex justify-end">
              <button
                onClick={() => {
                  setRawKeyModal(null);
                  setCopied(false);
                }}
                className="bg-gray-200 hover:bg-gray-300 dark:bg-gray-600 dark:hover:bg-gray-500 text-gray-700 dark:text-gray-200 px-4 py-2 rounded-lg text-sm font-medium"
              >
                닫기
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MyKeysPage;
