import { Box, Typography, Alert, CircularProgress } from "@mui/material";
import { useParams } from 'react-router-dom';
import { useAgentDetail } from '@/hooks/agent-hooks';
import { useState } from 'react';
import AgentTopbar from '@/pages/agent/components/AgentTopbar';
import AgentCanvas from '@/pages/agent/canvas';
import VersionListDialog from '@/pages/agent/components/VersionListDialog';
import EditAgentDialog from '@/pages/agent/components/EditAgentDialog';
import dayjs from "dayjs";
import { useTranslation } from "react-i18next";

function AgentDetailPage() {
  const { id } = useParams();
  const { agent, graph, loading, error, refresh } = useAgentDetail(id);
  const [canvasApi, setCanvasApi] = useState<{ fitView: () => void } | null>(null);
  const [lastAutoSavedAt, setLastAutoSavedAt] = useState<Date | null>(null);
  const [versionOpen, setVersionOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);

  const { t } = useTranslation();

  const subtitle = (() => {
    const ts = agent?.update_time ?? agent?.create_time;
    if (!ts) return undefined;
    const d = new Date(ts);
    const dStr = dayjs(d).format('YYYY-MM-DD HH:mm:ss');
    return t('agent.lastAutoSavedAt', { date: dStr });
  })();

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <AgentTopbar
        title={agent?.title}
        id={id}
        onRefresh={refresh}
        subtitle={lastAutoSavedAt ? t('agent.lastAutoSavedAt', { date: dayjs(lastAutoSavedAt).format('YYYY-MM-DD HH:mm:ss') }) : subtitle}
        onOpenVersions={() => setVersionOpen(true)}
        onOpenSettings={() => setEditOpen(true)}
      />

      <Box sx={{ flex: 1, position: 'relative' }}>
        {loading && (
          <Box sx={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <CircularProgress />
          </Box>
        )}
        {error && (
          <Box sx={{ p: 2 }}>
            <Alert severity="error">{error}</Alert>
          </Box>
        )}
        <AgentCanvas agent={agent} graph={graph} onReady={(api) => setCanvasApi(api)} onAutoSaved={(date) => setLastAutoSavedAt(date)} />
        <VersionListDialog open={versionOpen} canvasId={id} onClose={() => setVersionOpen(false)} />
        <EditAgentDialog
          open={editOpen}
          agent={agent as any}
          onClose={() => setEditOpen(false)}
          onSaved={() => { setEditOpen(false); refresh(); }}
        />
      </Box>
    </Box>
  );
}

export default AgentDetailPage;