import { useI18n } from '@/hooks/useI18n';
import { api } from '@/services/api';
import { auth } from '@/services/auth';
import { useCallback, useEffect, useState } from 'react';
import './index.css';

export default function History() {
  const { t } = useI18n();
  const [records, setRecords] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);

  const [loginRedirecting, setLoginRedirecting] = useState(false);

  const checkLoginStatus = useCallback(async () => {
    try {
      const loginStatus = await auth.checkLogin();
      setIsLoggedIn(loginStatus);
      return loginStatus;
    } catch (error) {
      console.error('Failed to check login status:', error);
      setIsLoggedIn(false);
      return false;
    }
  }, []);

  const loadRecords = useCallback(async () => {
    try {
      const logs = await api.getMineLogs();
      setRecords(logs || []);
    } catch (error) {
      console.error('Failed to load records:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    const initPage = async () => {
      const loginStatus = await checkLoginStatus();
      if (loginStatus) {
        await loadRecords();
      } else {
        setLoading(false);
      }
    };

    initPage();
  }, []);

  const handleLogin = useCallback(async () => {
    try {
      setLoginRedirecting(true);
      await auth.login('/history');
    } catch (error) {
      console.error('Login failed:', error);
    }
  }, []);

  if (loginRedirecting) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <div>Redirecting to login...</div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="loading-state">
        <span className="loading-text">{t('common.loading')}</span>
      </div>
    );
  }

  return (
    <div className="history">
      {/* Settings area */}
      <div className="history-list">
        <div className="history-grid">
          {isLoggedIn === false ? (
            <div className="login-required-state">
              <img className="login-icon-image" src="/assets/icons/user.png" alt="login" />
              <div className="login-content">
                <h3 className="login-title">{t('history.notLoggedIn')}</h3>
                <p className="login-description">{t('history.loginToViewHistory')}</p>
                <button className="login-button" onClick={handleLogin}>
                  {t('history.loginButton')}
                </button>
              </div>
            </div>
          ) : records.length === 0 ? (
            <div className="empty-state">
              <img className="empty-icon-image" src="/assets/icons/cloud.png" alt="empty" />
              <span className="empty-text">{t('history.noRecords')}</span>
            </div>
          ) : (
            records.map(record => {
              // const progress = calculateProgress(record); // Temporarily unused
              const isGenerating = record.status === 'processing';
              return (
                <a key={record.id} className="history-item" href={`/result?taskId=${record.paymentId}`}>
                  <div className="item-thumbnail">
                    {record.status === 'completed' && record.outputResult ? (
                      <img className="thumbnail-image" src={record.inputImages?.[0] || ''} alt="thumbnail" />
                    ) : (
                      <div className={`thumbnail-placeholder ${record.status}`}>
                        <img className="thumbnail-image" src={record.inputImages?.[0] || ''} alt="thumbnail" />
                        {/* Scanning effect for generating state */}
                        {isGenerating && (
                          <div className="thumbnail-overlay">
                            <div className="thumbnail-progress-overlay" />
                            <div className="thumbnail-scan-light" />
                            {/* Loading spinner */}
                            <div className="thumbnail-loader" />
                          </div>
                        )}
                      </div>
                    )}
                  </div>

                  <div className="item-content">
                    <div className="item-header">
                      <span className="item-title">{record.templateName}</span>
                    </div>
                    <div className="item-info">
                      <span className="item-time">{formatTime(record.createdAt)}</span>
                    </div>
                  </div>
                </a>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
