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

import {
  carePlanApi,
  type CarePlan,
  type CreateCarePlanReq,
  type UpdateCarePlanReq,
  PLAN_TYPE_OPTIONS,
  PLAN_STATUS_OPTIONS,
  PLAN_STATUS_COLOR,
} 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]),
);

interface FilterValues {
  plan_type?: string;
  status?: string;
}

export default function CarePlanList() {
  const { hasPermission } = usePermission('health.care-plan.manage');
  const navigate = useNavigate();

  const [data, setData] = useState<CarePlan[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState<FilterValues>({});

  const [modalOpen, setModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<CarePlan | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm();

  const pageSize = 20;

  const fetchData = useCallback(async (p: number, f: FilterValues) => {
    setLoading(true);
    try {
      const resp = await carePlanApi.list({
        page: p,
        page_size: pageSize,
        plan_type: f.plan_type || undefined,
        status: f.status || undefined,
      });
      setData(resp.data);
      setTotal(resp.total);
      setPage(p);
    } catch {
      message.error('加载护理计划失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData(1, filters);
  }, [fetchData, filters]);

  const handleFilterChange = (key: string, value: string | undefined) => {
    setFilters((prev) => ({ ...prev, [key]: value }));
  };

  const handleResetFilters = () => {
    setFilters({});
  };

  const handleCreate = () => {
    setEditRecord(null);
    form.resetFields();
    setModalOpen(true);
  };

  const handleEdit = (record: CarePlan) => {
    setEditRecord(record);
    form.setFieldsValue({
      title: record.title,
      plan_type: record.plan_type,
      start_date: record.start_date ? dayjs(record.start_date) : undefined,
      end_date: record.end_date ? dayjs(record.end_date) : undefined,
      notes: record.notes,
    });
    setModalOpen(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const req: CreateCarePlanReq | (UpdateCarePlanReq & { version: number }) = {
        title: values.title,
        plan_type: values.plan_type,
        start_date: values.start_date?.format('YYYY-MM-DD'),
        end_date: values.end_date?.format('YYYY-MM-DD'),
        notes: values.notes,
        ...(editRecord ? { version: editRecord.version } : { patient_id: values.patient_id }),
      };

      setSubmitting(true);
      if (editRecord) {
        await carePlanApi.update(editRecord.id, req as UpdateCarePlanReq & { version: number });
        message.success('护理计划已更新');
      } else {
        await carePlanApi.create(req as CreateCarePlanReq);
        message.success('护理计划已创建');
      }
      setModalOpen(false);
      fetchData(page, filters);
    } catch {
      // form validation
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (record: CarePlan) => {
    try {
      await carePlanApi.delete(record.id, record.version);
      message.success('护理计划已删除');
      fetchData(page, filters);
    } catch {
      message.error('删除失败');
    }
  };

  const columns: ColumnsType<CarePlan> = useMemo(() => [
    {
      title: '计划名称',
      dataIndex: 'title',
      width: 200,
      render: (title: string, record) => (
        <a onClick={() => navigate(`/health/care-plans/${record.id}`)}>{title}</a>
      ),
    },
    {
      title: '类型',
      dataIndex: 'plan_type',
      width: 120,
      render: (v: string) => PLAN_TYPE_LABEL[v] ?? v,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (v: string) => (
        <Tag color={PLAN_STATUS_COLOR[v] ?? 'default'}>{PLAN_STATUS_LABEL[v] ?? v}</Tag>
      ),
    },
    {
      title: '开始日期',
      dataIndex: 'start_date',
      width: 120,
      render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD') : '-',
    },
    {
      title: '结束日期',
      dataIndex: 'end_date',
      width: 120,
      render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD') : '-',
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      width: 170,
      render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定删除此计划？" onConfirm={() => handleDelete(record)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [navigate, page, filters]);

  if (!hasPermission) {
    return <Result status="403" title="权限不足" subTitle="您没有管理护理计划的权限" />;
  }

  return (
    <PageContainer
      title="护理计划"
      actions={<Button type="primary" onClick={handleCreate}>新建计划</Button>}
    >
      <Space style={{ marginBottom: 16 }} wrap>
        <Select
          allowClear
          placeholder="计划类型"
          options={PLAN_TYPE_OPTIONS}
          value={filters.plan_type}
          onChange={(v) => handleFilterChange('plan_type', v)}
          style={{ width: 140 }}
        />
        <Select
          allowClear
          placeholder="状态"
          options={PLAN_STATUS_OPTIONS}
          value={filters.status}
          onChange={(v) => handleFilterChange('status', v)}
          style={{ width: 120 }}
        />
        <Button onClick={handleResetFilters}>重置</Button>
      </Space>

      <Table<CarePlan>
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{
          current: page,
          pageSize,
          total,
          showTotal: (t) => `共 ${t} 条`,
          onChange: (p) => fetchData(p, filters),
        }}
      />

      <Modal
        title={editRecord ? '编辑护理计划' : '新建护理计划'}
        open={modalOpen}
        onOk={handleSubmit}
        onCancel={() => setModalOpen(false)}
        confirmLoading={submitting}
        width={560}
      >
        <Form form={form} layout="vertical">
          {!editRecord && (
            <Form.Item name="patient_id" label="患者 ID" rules={[{ required: true, message: '请输入患者 ID' }]}>
              <Input placeholder="输入患者 UUID" />
            </Form.Item>
          )}
          <Form.Item name="title" label="计划名称" rules={[{ required: true, message: '请输入计划名称' }]}>
            <Input placeholder="如：血管通路护理计划" />
          </Form.Item>
          <Form.Item name="plan_type" label="计划类型" rules={[{ required: true, message: '请选择类型' }]}>
            <Select options={PLAN_TYPE_OPTIONS} placeholder="选择类型" />
          </Form.Item>
          <Space style={{ width: '100%' }} size="middle">
            <Form.Item name="start_date" label="开始日期">
              <DatePicker style={{ width: 220 }} />
            </Form.Item>
            <Form.Item name="end_date" label="结束日期">
              <DatePicker style={{ width: 220 }} />
            </Form.Item>
          </Space>
          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={3} placeholder="计划备注" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
