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 {
  shiftApi,
  type Shift,
  type CreateShiftReq,
  type UpdateShiftReq,
  PERIOD_OPTIONS,
  SHIFT_STATUS_OPTIONS,
  PERIOD_LABEL,
  SHIFT_STATUS_LABEL,
  SHIFT_STATUS_COLOR,
} from '../../api/health/shifts';
import { PageContainer } from '../../components/PageContainer';
import { usePermission } from '../../hooks/usePermission';

interface FilterValues {
  shift_date?: string;
  period?: string;
  status?: string;
}

export default function ShiftList() {
  const { hasPermission } = usePermission('health.shifts.manage');
  const navigate = useNavigate();

  const [data, setData] = useState<Shift[]>([]);
  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<Shift | 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 shiftApi.list({
        page: p,
        page_size: pageSize,
        shift_date: f.shift_date || undefined,
        period: f.period || 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: Shift) => {
    setEditRecord(record);
    form.setFieldsValue({
      shift_date: record.shift_date ? dayjs(record.shift_date) : undefined,
      period: record.period,
      nurse_id: record.nurse_id,
      notes: record.notes,
    });
    setModalOpen(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const req = {
        shift_date: values.shift_date?.format('YYYY-MM-DD'),
        period: values.period,
        nurse_id: values.nurse_id || undefined,
        notes: values.notes,
        ...(editRecord ? { version: editRecord.version } : {}),
      };

      setSubmitting(true);
      if (editRecord) {
        await shiftApi.update(editRecord.id, req as UpdateShiftReq & { version: number });
        message.success('班次已更新');
      } else {
        await shiftApi.create(req as CreateShiftReq);
        message.success('班次已创建');
      }
      setModalOpen(false);
      fetchData(page, filters);
    } catch {
      // validation
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (record: Shift) => {
    try {
      await shiftApi.delete(record.id, record.version);
      message.success('班次已删除');
      fetchData(page, filters);
    } catch {
      message.error('删除失败');
    }
  };

  const columns: ColumnsType<Shift> = useMemo(() => [
    {
      title: '日期',
      dataIndex: 'shift_date',
      width: 120,
      render: (v: string) => dayjs(v).format('YYYY-MM-DD'),
    },
    {
      title: '班次',
      dataIndex: 'period',
      width: 100,
      render: (v: string) => <Tag>{PERIOD_LABEL[v] ?? v}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (v: string) => (
        <Tag color={SHIFT_STATUS_COLOR[v] ?? 'default'}>{SHIFT_STATUS_LABEL[v] ?? v}</Tag>
      ),
    },
    {
      title: '患者数',
      dataIndex: 'patient_count',
      width: 80,
      render: (v: number) => v ?? 0,
    },
    {
      title: '危重',
      dataIndex: 'critical_count',
      width: 70,
      render: (v: number) => v ? <Tag color="red">{v}</Tag> : 0,
    },
    {
      title: '需关注',
      dataIndex: 'attention_count',
      width: 70,
      render: (v: number) => v ? <Tag color="orange">{v}</Tag> : 0,
    },
    {
      title: '备注',
      dataIndex: 'notes',
      width: 160,
      ellipsis: true,
      render: (v: string) => v ?? '-',
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      width: 170,
      render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button size="small" type="link" onClick={() => navigate(`/health/shifts/${record.id}`)}>详情</Button>
          <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>
        <DatePicker
          placeholder="选择日期"
          value={filters.shift_date ? dayjs(filters.shift_date) : undefined}
          onChange={(_, ds) => handleFilterChange('shift_date', ds as string || undefined)}
          style={{ width: 150 }}
        />
        <Select
          allowClear
          placeholder="班次"
          options={PERIOD_OPTIONS}
          value={filters.period}
          onChange={(v) => handleFilterChange('period', v)}
          style={{ width: 120 }}
        />
        <Select
          allowClear
          placeholder="状态"
          options={SHIFT_STATUS_OPTIONS}
          value={filters.status}
          onChange={(v) => handleFilterChange('status', v)}
          style={{ width: 120 }}
        />
        <Button onClick={handleResetFilters}>重置</Button>
      </Space>

      <Table<Shift>
        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={480}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="shift_date" label="日期" rules={[{ required: true, message: '请选择日期' }]}>
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="period" label="班次" rules={[{ required: true, message: '请选择班次' }]}>
            <Select options={PERIOD_OPTIONS} placeholder="选择班次" />
          </Form.Item>
          <Form.Item name="nurse_id" label="责任护士 ID">
            <Input placeholder="护士 UUID（可选）" />
          </Form.Item>
          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={2} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
