import { useCallback, useState, useMemo } from 'react';
import { Table, Tag, Button, Modal, Form, Select, DatePicker, Input, message, Popconfirm, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { dayjs } from '../../../utils/dayjs';
import type { Dayjs } from 'dayjs';
import { healthDataApi } from '../../../api/health/healthData';
import type { HealthRecord } from '../../../api/health/healthData';
import { AuthButton } from '../../../components/AuthButton';
import { usePaginatedData } from '../../../hooks/usePaginatedData';

interface Props {
  patientId: string;
}

const RECORD_TYPE_OPTIONS = [
  { value: 'checkup', label: '体检' },
  { value: 'outpatient', label: '门诊' },
  { value: 'inpatient', label: '住院' },
];

const RECORD_TYPE_MAP: Record<string, string> = {
  checkup: '体检',
  outpatient: '门诊',
  inpatient: '住院',
};

export function HealthRecordsTab({ patientId }: Props) {
  const [modalOpen, setModalOpen] = useState(false);
  const [editingRecord, setEditingRecord] = useState<HealthRecord | null>(null);
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);

  const fetcher = useCallback(
    async (page: number, pageSize: number) => {
      return healthDataApi.listHealthRecords(patientId, { page, page_size: pageSize });
    },
    [patientId],
  );

  const { data, total, page, loading, refresh } = usePaginatedData<HealthRecord>(fetcher, 10);

  const isEditing = editingRecord !== null;
  const modalTitle = isEditing ? '编辑健康记录' : '添加健康记录';

  const openCreateModal = () => {
    setEditingRecord(null);
    form.resetFields();
    setModalOpen(true);
  };

  const openEditModal = (record: HealthRecord) => {
    setEditingRecord(record);
    form.setFieldsValue({
      record_type: record.record_type,
      record_date: dayjs(record.record_date),
      overall_assessment: record.overall_assessment,
    });
    setModalOpen(true);
  };

  const handleSubmit = async (values: {
    record_type: 'checkup' | 'outpatient' | 'inpatient';
    record_date: Dayjs;
    overall_assessment?: string;
  }) => {
    setSubmitting(true);
    try {
      if (isEditing && editingRecord) {
        await healthDataApi.updateHealthRecord(patientId, editingRecord.id, {
          record_type: values.record_type,
          record_date: values.record_date.format('YYYY-MM-DD'),
          overall_assessment: values.overall_assessment,
          version: editingRecord.version,
        });
        message.success('健康记录更新成功');
      } else {
        await healthDataApi.createHealthRecord(patientId, {
          record_type: values.record_type,
          record_date: values.record_date.format('YYYY-MM-DD'),
          overall_assessment: values.overall_assessment,
        });
        message.success('健康记录添加成功');
      }
      setModalOpen(false);
      form.resetFields();
      setEditingRecord(null);
      refresh();
    } catch {
      message.error(isEditing ? '更新失败' : '添加失败');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (record: HealthRecord) => {
    try {
      await healthDataApi.deleteHealthRecord(patientId, record.id);
      message.success('健康记录删除成功');
      refresh();
    } catch {
      message.error('删除失败');
    }
  };

  const columns = useMemo(() => [
    { title: '记录类型', dataIndex: 'record_type', key: 'record_type', width: 120, render: (v: string) => <Tag>{RECORD_TYPE_MAP[v] || v}</Tag> },
    { title: '记录日期', dataIndex: 'record_date', key: 'record_date', width: 120 },
    { title: '内容', dataIndex: 'overall_assessment', key: 'overall_assessment', ellipsis: true },
    { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 170, render: (v: string) => new Date(v).toLocaleString('zh-CN') },
    {
      title: '操作',
      key: 'action',
      width: 140,
      render: (_: unknown, record: HealthRecord) => (
        <Space size="small">
          <AuthButton code="health.health-data.manage">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => openEditModal(record)}
            >
              编辑
            </Button>
          </AuthButton>
          <AuthButton code="health.health-data.manage">
            <Popconfirm
              title="确认删除"
              description="确定要删除这条健康记录吗？"
              onConfirm={() => handleDelete(record)}
              okText="删除"
              cancelText="取消"
            >
              <Button type="link" size="small" danger icon={<DeleteOutlined />}>
                删除
              </Button>
            </Popconfirm>
          </AuthButton>
        </Space>
      ),
    },
  ], [openEditModal, handleDelete]);

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end' }}>
        <Button icon={<PlusOutlined />} onClick={openCreateModal}>
          添加记录
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        size="small"
        pagination={{
          current: page, total, pageSize: 10,
          onChange: (p) => refresh(p),
          showTotal: (t) => `共 ${t} 条`,
          style: { margin: 0 },
        }}
      />
      <Modal
        title={modalTitle}
        open={modalOpen}
        onCancel={() => { setModalOpen(false); setEditingRecord(null); }}
        onOk={() => form.submit()}
        confirmLoading={submitting}
        destroyOnHidden
        width={520}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item name="record_type" label="记录类型" rules={[{ required: true, message: '请选择类型' }]}>
            <Select placeholder="请选择记录类型" options={RECORD_TYPE_OPTIONS} />
          </Form.Item>
          <Form.Item name="record_date" label="记录日期" rules={[{ required: true, message: '请选择日期' }]}>
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="overall_assessment" label="内容">
            <Input.TextArea rows={4} placeholder="健康记录详细内容" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
