import { useState, useEffect, useCallback } from 'react';
import { Table, DatePicker, message } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { dayjs } from '../../utils/dayjs';
import { followUpApi, type FollowUpRecord } from '../../api/health/followUp';
import { PatientSelect } from './components/PatientSelect';
import { useThemeMode } from '../../hooks/useThemeMode';

const RESULT_MAP: Record<string, string> = {
  normal: '正常',
  abnormal: '异常',
  unreachable: '无法联系',
  refused: '拒绝随访',
};

interface QueryParams {
  page: number;
  page_size: number;
  task_id?: string;
  patient_id?: string;
  start_date?: string;
  end_date?: string;
}

export default function FollowUpRecordList() {
  const [records, setRecords] = useState<FollowUpRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState<QueryParams>({ page: 1, page_size: 20 });
  const [selectedPatient, setSelectedPatient] = useState<string | undefined>();

  const isDark = useThemeMode();

  // --- Data fetching ---
  const fetchRecords = useCallback(async (params: QueryParams) => {
    setLoading(true);
    try {
      const result = await followUpApi.listRecords(params);
      setRecords(result.data);
      setTotal(result.total);
    } catch {
      message.error('加载随访记录失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchRecords(query);
  }, [query, fetchRecords]);

  // --- Handlers ---
  const handleTableChange = (pagination: TablePaginationConfig) => {
    setQuery((prev) => ({
      ...prev,
      page: pagination.current ?? 1,
      page_size: pagination.pageSize ?? 20,
    }));
  };

  const handlePatientChange = (value: string | undefined) => {
    setSelectedPatient(value);
    setQuery((prev) => ({
      ...prev,
      patient_id: value || undefined,
      page: 1,
    }));
  };

  const handleDateRangeChange = (
    _dates: [dayjs.Dayjs | null, dayjs.Dayjs | null] | null,
    dateStrings: [string, string],
  ) => {
    setQuery((prev) => ({
      ...prev,
      start_date: dateStrings[0] || undefined,
      end_date: dateStrings[1] || undefined,
      page: 1,
    }));
  };

  // --- Columns ---
  const columns: ColumnsType<FollowUpRecord> = [
    {
      title: '任务ID',
      dataIndex: 'task_id',
      key: 'task_id',
      width: 140,
      render: (id: string) => (
        <span style={{ fontFamily: 'monospace', fontSize: 12 }}>
          {id.slice(0, 8)}
        </span>
      ),
    },
    {
      title: '执行人',
      dataIndex: 'executed_by',
      key: 'executed_by',
      width: 140,
      render: (id: string | undefined) =>
        id ? (
          <span style={{ fontFamily: 'monospace', fontSize: 12 }}>
            {id.slice(0, 8)}
          </span>
        ) : (
          '-'
        ),
    },
    {
      title: '执行日期',
      dataIndex: 'executed_date',
      key: 'executed_date',
      width: 120,
    },
    {
      title: '结果',
      dataIndex: 'result',
      key: 'result',
      width: 100,
      render: (v: string | undefined) =>
        v ? RESULT_MAP[v] || v : '-',
    },
    {
      title: '患者状况',
      dataIndex: 'patient_condition',
      key: 'patient_condition',
      width: 200,
      ellipsis: true,
      render: (v: string | undefined) => v || '-',
    },
    {
      title: '医嘱',
      dataIndex: 'medical_advice',
      key: 'medical_advice',
      width: 200,
      ellipsis: true,
      render: (v: string | undefined) => v || '-',
    },
    {
      title: '下次随访日期',
      dataIndex: 'next_follow_up_date',
      key: 'next_follow_up_date',
      width: 130,
      render: (v: string | undefined) => v || '-',
    },
  ];

  return (
    <div>
      {/* Toolbar */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 12,
          marginBottom: 16,
          padding: 12,
          background: isDark ? '#111827' : '#FFFFFF',
          borderRadius: 10,
          border: `1px solid ${isDark ? '#0f172a' : '#f8fafc'}`,
        }}
      >
        <DatePicker.RangePicker
          onChange={handleDateRangeChange}
          placeholder={['开始日期', '结束日期']}
          style={{ width: 260 }}
        />
        <PatientSelect
          value={selectedPatient}
          onChange={(val) => handlePatientChange(val)}
          placeholder="筛选患者"
        />
        <span
          style={{
            fontSize: 13,
            color: isDark ? '#475569' : '#94a3b8',
            marginLeft: 'auto',
          }}
        >
          共 {total} 条
        </span>
      </div>

      {/* Table */}
      <div
        style={{
          background: isDark ? '#111827' : '#FFFFFF',
          borderRadius: 12,
          border: `1px solid ${isDark ? '#0f172a' : '#f8fafc'}`,
          overflow: 'hidden',
        }}
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={records}
          loading={loading}
          onChange={handleTableChange}
          pagination={{
            current: query.page,
            pageSize: query.page_size,
            total,
            showSizeChanger: true,
            showTotal: (t) => `共 ${t} 条`,
          }}
          scroll={{ x: 1030 }}
        />
      </div>
    </div>
  );
}
