import { useEffect, useState, useCallback, useMemo } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Tag,
  Card,
  Checkbox,
  message,
  Typography,
} from 'antd';
import { TagsOutlined, AppstoreOutlined } from '@ant-design/icons';
import { patientApi, type TagItem } from '../../api/health/patients';
import type { PatientListItem } from '../../api/health/patients';
import { GENDER_LABEL, STATUS_TAG_CONFIG } from '../../constants/health';
import { useThemeMode } from '../../hooks/useThemeMode';
import { AuthButton } from '../../components/AuthButton';

export default function PatientTagManage() {
  const [patients, setPatients] = useState<PatientListItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [tagModalOpen, setTagModalOpen] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<PatientListItem | null>(null);
  const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);
  const [allTags, setAllTags] = useState<TagItem[]>([]);
  const [saving, setSaving] = useState(false);
  const isDark = useThemeMode();

  const fetchPatients = useCallback(
    async (p = page) => {
      setLoading(true);
      try {
        const result = await patientApi.list({ page: p, page_size: 20 });
        setPatients(result.data);
        setTotal(result.total);
      } catch {
        message.error('加载患者列表失败');
      } finally {
        setLoading(false);
      }
    },
    [page],
  );

  const fetchTags = useCallback(async () => {
    try {
      const tags = await patientApi.listTags();
      setAllTags(tags);
    } catch {
      // 标签列表加载失败不阻塞页面
    }
  }, []);

  useEffect(() => {
    fetchPatients();
    fetchTags();
  }, [fetchPatients, fetchTags]);

  const openTagModal = (record: PatientListItem) => {
    setSelectedPatient(record);
    const existingTags = (record as PatientListItem & { tag_ids?: string[] }).tag_ids || [];
    setSelectedTagIds(existingTags);
    setTagModalOpen(true);
  };

  const handleSaveTags = async () => {
    if (!selectedPatient) return;
    setSaving(true);
    try {
      await patientApi.manageTags(selectedPatient.id, selectedTagIds);
      message.success('标签更新成功');
      setTagModalOpen(false);
      fetchPatients();
    } catch {
      message.error('标签更新失败');
    } finally {
      setSaving(false);
    }
  };

  const toggleTag = (tagId: string) => {
    setSelectedTagIds((prev) =>
      prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId],
    );
  };

  const columns = useMemo(() => [
    {
      title: '患者姓名',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div
            style={{
              width: 32,
              height: 32,
              borderRadius: 8,
              background: 'linear-gradient(135deg, #0ea5e9, #38bdf8)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#fff',
              fontSize: 13,
              fontWeight: 600,
            }}
          >
            {(name?.[0] || 'P').toUpperCase()}
          </div>
          <span style={{ fontWeight: 500 }}>{name}</span>
        </div>
      ),
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
      render: (v?: string) => {
        if (!v) return '-';
        return GENDER_LABEL[v] || v;
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      render: (_: unknown, record: PatientListItem) => {
        const tagIds = (record as PatientListItem & { tag_ids?: string[] }).tag_ids;
        if (!tagIds || tagIds.length === 0) {
          return <span style={{ color: isDark ? '#475569' : '#CBD5E1' }}>暂无标签</span>;
        }
        return (
          <Space size={4} wrap>
            {tagIds.map((t) => {
              const tagDef = allTags.find((at) => at.id === t);
              return (
                <Tag
                  key={t}
                  color={tagDef?.color || undefined}
                  style={tagDef?.color ? undefined : {
                    background: isDark ? '#0f172a' : '#f0f9ff',
                    border: `1px solid ${isDark ? '#1e3a5f' : '#bae6fd'}`,
                    color: isDark ? '#7dd3fc' : '#0369a1',
                  }}
                >
                  {tagDef?.name || t.slice(0, 8)}
                </Tag>
              );
            })}
          </Space>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const cfg = STATUS_TAG_CONFIG[status] || { color: 'default', label: status };
        return <Tag color={cfg.color}>{cfg.label}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_: unknown, record: PatientListItem) => (
        <AuthButton code="health.patient.manage">
          <Button
            size="small"
            type="link"
            icon={<TagsOutlined />}
            onClick={() => openTagModal(record)}
          >
            管理标签
          </Button>
        </AuthButton>
      ),
    },
  ], [isDark, allTags, openTagModal]);

  return (
    <div>
      <Card
        style={{
          marginBottom: 16,
          borderRadius: 12,
          background: isDark ? '#111827' : '#FFFFFF',
          border: `1px solid ${isDark ? '#0f172a' : '#f8fafc'}`,
        }}
      >
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <AppstoreOutlined style={{ fontSize: 20, color: '#0ea5e9', marginTop: 2 }} />
          <div>
            <Typography.Text strong style={{ fontSize: 14 }}>
              标签管理说明
            </Typography.Text>
            <Typography.Paragraph type="secondary" style={{ margin: '4px 0 0', fontSize: 13 }}>
              为患者分配分类标签，便于快速筛选和管理。勾选需要关联的标签后保存即可。
            </Typography.Paragraph>
          </div>
        </div>
      </Card>

      <div className="erp-page-header">
        <div>
          <h4>标签管理</h4>
          <div className="erp-page-subtitle">为患者分配和管理分类标签</div>
        </div>
      </div>

      <div
        style={{
          background: isDark ? '#111827' : '#FFFFFF',
          borderRadius: 12,
          border: `1px solid ${isDark ? '#0f172a' : '#f8fafc'}`,
          overflow: 'hidden',
        }}
      >
        <Table
          columns={columns}
          dataSource={patients}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            total,
            pageSize: 20,
            onChange: (p) => {
              setPage(p);
              fetchPatients(p);
            },
            showTotal: (t) => `共 ${t} 条记录`,
            style: { padding: '12px 16px', margin: 0 },
          }}
        />
      </div>

      <Modal
        title={`管理标签 - ${selectedPatient?.name || ''}`}
        open={tagModalOpen}
        onCancel={() => setTagModalOpen(false)}
        onOk={handleSaveTags}
        confirmLoading={saving}
        okText="保存"
        width={440}
      >
        <div style={{ marginTop: 16 }}>
          {allTags.length === 0 ? (
            <Typography.Text type="secondary">暂无可用标签</Typography.Text>
          ) : (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {allTags.map((tag) => (
                <Checkbox
                  key={tag.id}
                  checked={selectedTagIds.includes(tag.id)}
                  onChange={() => toggleTag(tag.id)}
                >
                  <Tag color={tag.color || undefined}>{tag.name}</Tag>
                </Checkbox>
              ))}
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
}
