'use client';

import { useEffect, useRef, useState } from 'react';
import { fetchWithAuth } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

async function triggerLocalDownload(url: string, filename: string) {
  const res = await fetchWithAuth(url);
  if (!res.ok) throw new Error(`Download failed: ${res.status}`);
  const blob = await res.blob();
  const blobUrl = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = blobUrl;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(blobUrl);
}

const API = process.env.NEXT_PUBLIC_API_URL ?? '';

interface ExportTask {
  task_id: string;
  workspace_id: string;
  workspace_name: string;
  status: 'processing' | 'completed' | 'error';
  download_url: string | null;
  s3_key: string | null;
  error: string | null;
  created_at: string;
}

export default function ExportsSection() {
  const { t, locale } = useTranslation();
  const [exports, setExports] = useState<ExportTask[]>([]);
  const [loading, setLoading] = useState(true);
  const [downloadingId, setDownloadingId] = useState<string | null>(null);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const formatDate = (iso: string) => {
    const tag = locale === 'zh' ? 'zh-CN' : locale === 'ja' ? 'ja-JP' : 'en-US';
    return new Date(iso).toLocaleString(tag, {
      month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
    });
  };

  const statusStyle: Record<string, { color: string; bg: string; label: string }> = {
    processing: { color: '#b45309', bg: '#fef9c3', label: t('exports.statusProcessing') },
    completed:  { color: '#166534', bg: '#dcfce7', label: t('exports.statusReady') },
    error:      { color: '#991b1b', bg: '#fee2e2', label: t('exports.statusFailed') },
  };

  const loadExports = async () => {
    const res = await fetchWithAuth(`${API}/api/exports`);
    if (!res.ok) return;
    const data = await res.json();
    setExports(data.exports ?? []);
    setLoading(false);
  };

  useEffect(() => {
    loadExports();
    // Poll while any task is still processing
    intervalRef.current = setInterval(async () => {
      const res = await fetchWithAuth(`${API}/api/exports`);
      if (!res.ok) return;
      const data = await res.json();
      const tasks: ExportTask[] = data.exports ?? [];
      setExports(tasks);
      if (!tasks.some(t => t.status === 'processing')) {
        clearInterval(intervalRef.current!);
      }
    }, 3000);
    return () => { if (intervalRef.current) clearInterval(intervalRef.current); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <div style={{ marginBottom: '20px' }}>
        <div style={{ fontSize: '16px', fontWeight: 600, color: '#1a1a2e', marginBottom: '4px' }}>
          {t('exports.title')}
        </div>
        <div style={{ fontSize: '13px', color: '#6b7280' }}>
          {t('exports.description')}
        </div>
      </div>

      {loading ? (
        <div style={{ color: '#9ca3af', fontSize: '13px', padding: '24px 0', textAlign: 'center' }}>
          {t('common.loading')}
        </div>
      ) : exports.length === 0 ? (
        <div style={{
          border: '1px dashed #e5e7eb',
          borderRadius: '10px',
          padding: '32px',
          textAlign: 'center',
          color: '#9ca3af',
          fontSize: '13px',
        }}>
          {t('exports.empty')}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
          {exports.map(task => {
            const s = statusStyle[task.status] ?? statusStyle.error;
            return (
              <div
                key={task.task_id}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '12px',
                  padding: '10px 14px',
                  border: '1px solid #f0f0f0',
                  borderRadius: '8px',
                  background: '#fafafa',
                }}
              >
                {/* Workspace name */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: '13px', fontWeight: 500, color: '#1a1a2e', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {task.workspace_name}
                  </div>
                  <div style={{ fontSize: '11px', color: '#9ca3af', marginTop: '2px' }}>
                    {formatDate(task.created_at)}
                  </div>
                </div>

                {/* Status badge */}
                <span style={{
                  fontSize: '11px',
                  fontWeight: 600,
                  padding: '2px 8px',
                  borderRadius: '10px',
                  background: s.bg,
                  color: s.color,
                  flexShrink: 0,
                }}>
                  {task.status === 'processing' && (
                    <span style={{ marginRight: '4px', display: 'inline-block', animation: 'spin 1s linear infinite' }}>⟳</span>
                  )}
                  {s.label}
                </span>

                {/* Error tooltip */}
                {task.status === 'error' && task.error && (
                  <span
                    title={task.error}
                    style={{ fontSize: '12px', color: '#ef4444', cursor: 'help', flexShrink: 0 }}
                  >
                    ⓘ
                  </span>
                )}

                {/* Download button */}
                {task.status === 'completed' && task.download_url && (() => {
                  const isLocal = task.download_url.startsWith('/api/');
                  const downloadStyle = {
                    fontSize: '12px',
                    fontWeight: 600,
                    color: '#4a6cf7',
                    textDecoration: 'none',
                    padding: '4px 10px',
                    border: '1px solid #c7d2fe',
                    borderRadius: '6px',
                    background: '#eef2ff',
                    flexShrink: 0,
                    cursor: 'pointer',
                  } as const;
                  if (isLocal) {
                    const filename = task.workspace_name.replace(/[^a-zA-Z0-9_-]/g, '_') + '.zip';
                    return (
                      <button
                        disabled={downloadingId === task.task_id}
                        style={{ ...downloadStyle, opacity: downloadingId === task.task_id ? 0.6 : 1 }}
                        onClick={async () => {
                          setDownloadingId(task.task_id);
                          try {
                            await triggerLocalDownload(`${API}${task.download_url}`, filename);
                          } finally {
                            setDownloadingId(null);
                          }
                        }}
                      >
                        {downloadingId === task.task_id ? '…' : t('exports.download')}
                      </button>
                    );
                  }
                  return (
                    <a
                      href={task.download_url}
                      target="_blank"
                      rel="noreferrer"
                      style={downloadStyle}
                    >
                      {t('exports.download')}
                    </a>
                  );
                })()}
              </div>
            );
          })}
        </div>
      )}

      <style>{`
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}
