'use client';

import { useEffect, useState } from 'react';
import { Box, Card, Stack, Text, Title } from '@tidbcloud/uikit';
import { fetchWithAuth } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';
import { EvidencePreviewPane } from './DiagnosisEvidencePanel';

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

interface DiagnosisEvidenceFilePanelProps {
  workspaceId: string;
  filePath: string;
}

async function fetchFileData(workspaceId: string, path: string): Promise<any> {
  const res = await fetchWithAuth(
    `${API}/api/workspace/${encodeURIComponent(workspaceId)}/file?path=${encodeURIComponent(path)}`
  );
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const ct = (res.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase();
  if (ct === 'application/json' || path.endsWith('.json')) {
    const text = await res.text();
    try {
      return JSON.parse(text);
    } catch {
      return text;
    }
  }
  return res.text();
}

export default function DiagnosisEvidenceFilePanel({ workspaceId, filePath }: DiagnosisEvidenceFilePanelProps) {
  const { t } = useTranslation();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!workspaceId || !filePath) return;
    setLoading(true);
    setError(null);
    fetchFileData(workspaceId, filePath)
      .then(setData)
      .catch(err => setError(String(err)))
      .finally(() => setLoading(false));
  }, [workspaceId, filePath]);

  return (
    <Box style={{ height: '100%' }}>
      <Stack gap="sm" p="md" style={{ minHeight: '100%' }}>
        <Card withBorder p="md">
          <Stack gap="xs">
            <Title order={5}>{t('studio.evidence')}</Title>
            <Text size="xs" c="carbon.6" style={{ fontFamily: 'monospace' }}>
              {filePath}
            </Text>
          </Stack>
        </Card>

        {loading ? (
          <Text size="sm" c="carbon.6">Loading evidence file…</Text>
        ) : error ? (
          <Text size="sm" c="red">{error}</Text>
        ) : (
          <EvidencePreviewPane filePath={filePath} data={data} />
        )}
      </Stack>
    </Box>
  );
}
