import React, { useCallback } from 'react';
import { useParams, useNavigate } from 'react-router';
import { Card, Button, Space } from 'antd';
import { ArrowLeftOutlined, EyeOutlined } from '@ant-design/icons';
import StudentProfileContent from '../../components/StudentProfileContent';
import PermissionButton from '../../components/PermissionButton';
import api from '../../api';

const StudentProfilePage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  if (!id) return null;

  const studentId = Number(id);

  const handlePreviewReport = useCallback(async () => {
    try {
      const { html } = await api.get<{ html: string }>(`/archive/${studentId}/report-html`);
      const w = window.open('', '_blank');
      if (w) {
        w.document.write(html);
        w.document.close();
      }
    } catch (err) {
      console.error('Failed to load report HTML:', err);
    }
  }, [studentId]);

  return (
    <Card
      title={
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/students')} />
          <span>学生档案</span>
        </Space>
      }
      extra={
        <PermissionButton
          permission="student:view"
          type="primary"
          icon={<EyeOutlined />}
          onClick={handlePreviewReport}
        >
          预览报告
        </PermissionButton>
      }
    >
      <StudentProfileContent studentId={studentId} />
    </Card>
  );
};

export default StudentProfilePage;
