import { useState, useCallback, useEffect } from 'react';
import {
  Button, DatePicker, Descriptions, Form, Input, InputNumber, message,
  Modal, Popconfirm, Result, Select, Space, Spin, Table, Tabs, Tag,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useParams, useNavigate } from 'react-router-dom';

import {
  carePlanApi,
  type CarePlan,
  type CarePlanItem,
  type CarePlanOutcome,
  type CreateCarePlanItemReq,
  type CreateCarePlanOutcomeReq,
  PLAN_TYPE_OPTIONS,
  PLAN_STATUS_OPTIONS,
  PLAN_STATUS_COLOR,
  ITEM_TYPE_OPTIONS,
} from '../../api/health/carePlans';
import { PageContainer } from '../../components/PageContainer';
import { usePermission } from '../../hooks/usePermission';

const PLAN_TYPE_LABEL: Record<string, string> = Object.fromEntries(PLAN_TYPE_OPTIONS.map((o) => [o.value, o.label]));
const PLAN_STATUS_LABEL: Record<string, string> = Object.fromEntries(PLAN_STATUS_OPTIONS.map((o) => [o.value, o.label]));
const ITEM_TYPE_LABEL: Record<string, string> = Object.fromEntries(ITEM_TYPE_OPTIONS.map((o) => [o.value, o.label]));

export default function CarePlanDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { hasPermission } = usePermission('health.care-plan.manage');

  const [plan, setPlan] = useState<CarePlan | null>(null);
  const [loading, setLoading] = useState(true);

  // Items
  const [items, setItems] = useState<CarePlanItem[]>([]);
  const [itemsLoading, setItemsLoading] = useState(false);
  const [itemModalOpen, setItemModalOpen] = useState(false);
  const [editItem, setEditItem] = useState<CarePlanItem | null>(null);
  const [itemForm] = Form.useForm();

  // Outcomes
  const [outcomes, setOutcomes] = useState<CarePlanOutcome[]>([]);
  const [outcomesLoading, setOutcomesLoading] = useState(false);
  const [outcomeModalOpen, setOutcomeModalOpen] = useState(false);
  const [editOutcome, setEditOutcome] = useState<CarePlanOutcome | null>(null);
  const [outcomeForm] = Form.useForm();

  const planId = id!;

  const fetchPlan = useCallback(async () => {
    setLoading(true);
    try {
      const data = await carePlanApi.get(planId);
      setPlan(data);
    } catch {
      message.error('加载计划详情失败');
    } finally {
      setLoading(false);
    }
  }, [planId]);

  const fetchItems = useCallback(async () => {
    setItemsLoading(true);
    try {
      const resp = await carePlanApi.listItems(planId, { page: 1, page_size: 100 });
      setItems(resp.data);
    } catch {
      message.error('加载干预项目失败');
    } finally {
      setItemsLoading(false);
    }
  }, [planId]);

  const fetchOutcomes = useCallback(async () => {
    setOutcomesLoading(true);
    try {
      const resp = await carePlanApi.listOutcomes(planId, { page: 1, page_size: 100 });
      setOutcomes(resp.data);
    } catch {
      message.error('加载预后测量失败');
    } finally {
      setOutcomesLoading(false);
    }
  }, [planId]);

  useEffect(() => {
    fetchPlan();
    fetchItems();
    fetchOutcomes();
  }, [fetchPlan, fetchItems, fetchOutcomes]);

  // --- Item CRUD ---

  const handleCreateItem = () => {
    setEditItem(null);
    itemForm.resetFields();
    setItemModalOpen(true);
  };

  const handleEditItem = (record: CarePlanItem) => {
    setEditItem(record);
    itemForm.setFieldsValue({
      item_type: record.item_type,
      title: record.title,
      description: record.description,
      schedule: record.schedule,
      sort_order: record.sort_order,
    });
    setItemModalOpen(true);
  };

  const handleSubmitItem = async () => {
    try {
      const values = await itemForm.validateFields();
      if (editItem) {
        await carePlanApi.updateItem(planId, editItem.id, { ...values, version: editItem.version });
        message.success('干预项目已更新');
      } else {
        await carePlanApi.createItem(planId, values as CreateCarePlanItemReq);
        message.success('干预项目已创建');
      }
      setItemModalOpen(false);
      fetchItems();
    } catch {
      // validation
    }
  };

  const handleDeleteItem = async (record: CarePlanItem) => {
    try {
      await carePlanApi.deleteItem(planId, record.id, record.version);
      message.success('干预项目已删除');
      fetchItems();
    } catch {
      message.error('删除失败');
    }
  };

  // --- Outcome CRUD ---

  const handleCreateOutcome = () => {
    setEditOutcome(null);
    outcomeForm.resetFields();
    setOutcomeModalOpen(true);
  };

  const handleEditOutcome = (record: CarePlanOutcome) => {
    setEditOutcome(record);
    outcomeForm.setFieldsValue({
      metric: record.metric,
      baseline_value: record.baseline_value,
      target_value: record.target_value,
      current_value: record.current_value,
      measured_at: record.measured_at ? dayjs(record.measured_at) : undefined,
      notes: record.notes,
    });
    setOutcomeModalOpen(true);
  };

  const handleSubmitOutcome = async () => {
    try {
      const values = await outcomeForm.validateFields();
      const req = {
        ...values,
        measured_at: values.measured_at?.format('YYYY-MM-DD'),
      };
      if (editOutcome) {
        await carePlanApi.updateOutcome(planId, editOutcome.id, { ...req, version: editOutcome.version });
        message.success('预后测量已更新');
      } else {
        await carePlanApi.createOutcome(planId, req as CreateCarePlanOutcomeReq);
        message.success('预后测量已创建');
      }
      setOutcomeModalOpen(false);
      fetchOutcomes();
    } catch {
      // validation
    }
  };

  const handleDeleteOutcome = async (record: CarePlanOutcome) => {
    try {
      await carePlanApi.deleteOutcome(planId, record.id, record.version);
      message.success('预后测量已删除');
      fetchOutcomes();
    } catch {
      message.error('删除失败');
    }
  };

  // --- Columns ---

  const itemColumns: ColumnsType<CarePlanItem> = [
    { title: '类型', dataIndex: 'item_type', width: 120, render: (v: string) => ITEM_TYPE_LABEL[v] ?? v },
    { title: '标题', dataIndex: 'title', width: 200 },
    { title: '状态', dataIndex: 'status', width: 100, render: (v: string) => <Tag color={v === 'active' ? 'green' : 'default'}>{v}</Tag> },
    { title: '排期', dataIndex: 'schedule', width: 140, render: (v: string) => v ?? '-' },
    { title: '排序', dataIndex: 'sort_order', width: 70 },
    {
      title: '操作', width: 140, render: (_, record) => hasPermission ? (
        <Space>
          <Button size="small" onClick={() => handleEditItem(record)}>编辑</Button>
          <Popconfirm title="确定删除？" onConfirm={() => handleDeleteItem(record)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ) : null,
    },
  ];

  const outcomeColumns: ColumnsType<CarePlanOutcome> = [
    { title: '指标', dataIndex: 'metric', width: 140 },
    { title: '基线值', dataIndex: 'baseline_value', width: 100 },
    { title: '目标值', dataIndex: 'target_value', width: 100 },
    { title: '当前值', dataIndex: 'current_value', width: 100, render: (v: string) => v ?? '-' },
    { title: '测量日期', dataIndex: 'measured_at', width: 120, render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD') : '-' },
    {
      title: '操作', width: 140, render: (_, record) => hasPermission ? (
        <Space>
          <Button size="small" onClick={() => handleEditOutcome(record)}>编辑</Button>
          <Popconfirm title="确定删除？" onConfirm={() => handleDeleteOutcome(record)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ) : null,
    },
  ];

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
  if (!plan) return <Result status="404" title="计划不存在" />;
  if (!hasPermission) return <Result status="403" title="权限不足" />;

  return (
    <PageContainer
      title={plan.title}
      onBack={() => navigate('/health/care-plans')}
    >
      <Descriptions bordered size="small" column={3} style={{ marginBottom: 24 }}>
        <Descriptions.Item label="类型">{PLAN_TYPE_LABEL[plan.plan_type] ?? plan.plan_type}</Descriptions.Item>
        <Descriptions.Item label="状态">
          <Tag color={PLAN_STATUS_COLOR[plan.status] ?? 'default'}>{PLAN_STATUS_LABEL[plan.status] ?? plan.status}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="患者 ID">{plan.patient_id}</Descriptions.Item>
        <Descriptions.Item label="开始日期">{plan.start_date ?? '-'}</Descriptions.Item>
        <Descriptions.Item label="结束日期">{plan.end_date ?? '-'}</Descriptions.Item>
        <Descriptions.Item label="更新时间">{dayjs(plan.updated_at).format('YYYY-MM-DD HH:mm')}</Descriptions.Item>
        {plan.notes && <Descriptions.Item label="备注" span={3}>{plan.notes}</Descriptions.Item>}
      </Descriptions>

      <Tabs
        defaultActiveKey="items"
        items={[
          {
            key: 'items',
            label: `干预项目 (${items.length})`,
            children: (
              <>
                {hasPermission && (
                  <Button type="primary" size="small" style={{ marginBottom: 12 }} onClick={handleCreateItem}>
                    添加干预项目
                  </Button>
                )}
                <Table<CarePlanItem>
                  rowKey="id"
                  columns={itemColumns}
                  dataSource={items}
                  loading={itemsLoading}
                  pagination={false}
                  size="small"
                />
              </>
            ),
          },
          {
            key: 'outcomes',
            label: `预后测量 (${outcomes.length})`,
            children: (
              <>
                {hasPermission && (
                  <Button type="primary" size="small" style={{ marginBottom: 12 }} onClick={handleCreateOutcome}>
                    添加测量指标
                  </Button>
                )}
                <Table<CarePlanOutcome>
                  rowKey="id"
                  columns={outcomeColumns}
                  dataSource={outcomes}
                  loading={outcomesLoading}
                  pagination={false}
                  size="small"
                />
              </>
            ),
          },
        ]}
      />

      {/* Item Modal */}
      <Modal
        title={editItem ? '编辑干预项目' : '添加干预项目'}
        open={itemModalOpen}
        onOk={handleSubmitItem}
        onCancel={() => setItemModalOpen(false)}
        width={520}
      >
        <Form form={itemForm} layout="vertical">
          <Form.Item name="item_type" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
            <Select options={ITEM_TYPE_OPTIONS} placeholder="选择类型" />
          </Form.Item>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
            <Input placeholder="如：血压监测" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea rows={2} />
          </Form.Item>
          <Form.Item name="schedule" label="排期">
            <Input placeholder="如：每日、每周一" />
          </Form.Item>
          <Form.Item name="sort_order" label="排序">
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>

      {/* Outcome Modal */}
      <Modal
        title={editOutcome ? '编辑预后测量' : '添加测量指标'}
        open={outcomeModalOpen}
        onOk={handleSubmitOutcome}
        onCancel={() => setOutcomeModalOpen(false)}
        width={520}
      >
        <Form form={outcomeForm} layout="vertical">
          <Form.Item name="metric" label="指标名称" rules={[{ required: true, message: '请输入指标' }]}>
            <Input placeholder="如：收缩压、血磷" />
          </Form.Item>
          <Space style={{ width: '100%' }} size="middle">
            <Form.Item name="baseline_value" label="基线值" rules={[{ required: true }]}>
              <Input style={{ width: 200 }} placeholder="如：150" />
            </Form.Item>
            <Form.Item name="target_value" label="目标值" rules={[{ required: true }]}>
              <Input style={{ width: 200 }} placeholder="如：130" />
            </Form.Item>
          </Space>
          <Form.Item name="current_value" label="当前值">
            <Input placeholder="最新测量结果" />
          </Form.Item>
          <Form.Item name="measured_at" label="测量日期">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={2} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
