'use client';

import { useState, useCallback, useEffect } from 'react';
import { Modal, toast, Button } from '@/components/common';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import {
  audienceSegmentService,
  AudienceSegment,
  SegmentCondition,
  SegmentConditionGroup,
  SegmentStatus,
  LogicOperator,
  ConditionOperator,
  SEGMENT_STATUS_OPTIONS,
  CONDITION_OPERATOR_OPTIONS,
  SEGMENT_FIELD_OPTIONS,
} from '@/services/audienceSegmentService';
import { userTagService, UserTag } from '@/services/userTagService';
import styles from './AudienceSegmentsTab.module.scss';

/**
 * 人群包管理 Tab
 */
export const AudienceSegmentsTab = () => {
  // 数据状态
  const [segments, setSegments] = useState<AudienceSegment[]>([]);
  const [tags, setTags] = useState<UserTag[]>([]);
  const [loading, setLoading] = useState(true);

  // 弹窗状态
  const [showModal, setShowModal] = useState(false);
  const [editingSegment, setEditingSegment] = useState<AudienceSegment | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    groupsLogic: 'AND' as LogicOperator,
    conditionGroups: [createEmptyGroup()] as SegmentConditionGroup[],
  });

  function createEmptyCondition(): SegmentCondition {
    return { field: 'registrationDays', operator: 'GREATER_THAN', value: '' };
  }

  function createEmptyGroup(): SegmentConditionGroup {
    return { logic: 'AND', conditions: [createEmptyCondition()] };
  }

  // 加载数据
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      const [segmentsResponse, tagsResponse] = await Promise.all([
        audienceSegmentService.getSegments(),
        userTagService.getTags({ isAdvertisable: true }),
      ]);
      setSegments(segmentsResponse.items);
      setTags(tagsResponse.items);
    } catch (err) {
      toast.error((err as Error).message || '加载失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 打开创建弹窗
  const handleCreate = () => {
    setEditingSegment(null);
    setFormData({
      name: '',
      description: '',
      groupsLogic: 'AND',
      conditionGroups: [createEmptyGroup()],
    });
    setShowModal(true);
  };

  // 打开编辑弹窗
  const handleEdit = (segment: AudienceSegment) => {
    setEditingSegment(segment);
    setFormData({
      name: segment.name,
      description: segment.description || '',
      groupsLogic: segment.groupsLogic,
      conditionGroups: segment.conditionGroups.length > 0
        ? segment.conditionGroups
        : [createEmptyGroup()],
    });
    setShowModal(true);
  };

  // 保存
  const handleSave = async () => {
    if (!formData.name.trim()) {
      toast.error('请输入人群包名称');
      return;
    }

    // 过滤空条件
    const validGroups = formData.conditionGroups
      .map(g => ({
        ...g,
        conditions: g.conditions.filter(c => c.field && c.operator),
      }))
      .filter(g => g.conditions.length > 0);

    if (validGroups.length === 0) {
      toast.error('请至少添加一个有效条件');
      return;
    }

    try {
      if (editingSegment) {
        await audienceSegmentService.updateSegment(editingSegment.id, {
          name: formData.name.trim(),
          description: formData.description.trim() || undefined,
          groupsLogic: formData.groupsLogic,
          conditionGroups: validGroups,
        });
        toast.success('人群包已更新');
      } else {
        await audienceSegmentService.createSegment({
          name: formData.name.trim(),
          description: formData.description.trim() || undefined,
          groupsLogic: formData.groupsLogic,
          conditionGroups: validGroups,
        });
        toast.success('人群包已创建');
      }
      setShowModal(false);
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  // 删除
  const handleDelete = async () => {
    if (!deleteConfirm) return;
    try {
      await audienceSegmentService.deleteSegment(deleteConfirm);
      toast.success('人群包已删除');
      setDeleteConfirm(null);
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '删除失败');
    }
  };

  // 刷新
  const handleRefresh = async (id: string) => {
    try {
      await audienceSegmentService.refreshSegment(id);
      toast.success('人群包已刷新');
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '刷新失败');
    }
  };

  // 条件组操作
  const addConditionGroup = () => {
    setFormData({
      ...formData,
      conditionGroups: [...formData.conditionGroups, createEmptyGroup()],
    });
  };

  const removeConditionGroup = (groupIndex: number) => {
    const groups = [...formData.conditionGroups];
    groups.splice(groupIndex, 1);
    setFormData({ ...formData, conditionGroups: groups.length > 0 ? groups : [createEmptyGroup()] });
  };

  const updateConditionGroup = (groupIndex: number, updates: Partial<SegmentConditionGroup>) => {
    const groups = [...formData.conditionGroups];
    groups[groupIndex] = { ...groups[groupIndex], ...updates };
    setFormData({ ...formData, conditionGroups: groups });
  };

  // 条件操作
  const addCondition = (groupIndex: number) => {
    const groups = [...formData.conditionGroups];
    groups[groupIndex].conditions.push(createEmptyCondition());
    setFormData({ ...formData, conditionGroups: groups });
  };

  const removeCondition = (groupIndex: number, condIndex: number) => {
    const groups = [...formData.conditionGroups];
    groups[groupIndex].conditions.splice(condIndex, 1);
    if (groups[groupIndex].conditions.length === 0) {
      groups[groupIndex].conditions.push(createEmptyCondition());
    }
    setFormData({ ...formData, conditionGroups: groups });
  };

  const updateCondition = (groupIndex: number, condIndex: number, updates: Partial<SegmentCondition>) => {
    const groups = [...formData.conditionGroups];
    groups[groupIndex].conditions[condIndex] = { ...groups[groupIndex].conditions[condIndex], ...updates };
    setFormData({ ...formData, conditionGroups: groups });
  };

  // 获取状态显示
  const getStatusLabel = (status: SegmentStatus) => {
    const opt = SEGMENT_STATUS_OPTIONS.find(o => o.value === status);
    return opt?.label || status;
  };

  const getStatusColor = (status: SegmentStatus) => {
    const opt = SEGMENT_STATUS_OPTIONS.find(o => o.value === status);
    return opt?.color || 'gray';
  };

  // 获取字段标签
  const getFieldLabel = (field: string) => {
    const opt = SEGMENT_FIELD_OPTIONS.find(o => o.value === field);
    return opt?.label || field;
  };

  // 获取操作符标签
  const getOperatorLabel = (op: ConditionOperator) => {
    const opt = CONDITION_OPERATOR_OPTIONS.find(o => o.value === op);
    return opt?.label || op;
  };

  if (loading && segments.length === 0) {
    return <div className={styles.loading}>加载中...</div>;
  }

  return (
    <div className={styles.container}>
      {/* 头部 */}
      <div className={styles.header}>
        <h3>人群包管理</h3>
        <Button variant="primary" onClick={handleCreate}>+ 新建人群包</Button>
      </div>

      {/* 列表 */}
      {segments.length === 0 ? (
        <div className={styles.empty}>暂无人群包，点击"新建人群包"创建</div>
      ) : (
        <div className={styles.list}>
          {segments.map(segment => (
            <div key={segment.id} className={styles.card}>
              <div className={styles.cardHeader}>
                <h4>{segment.name}</h4>
                <span className={cn(styles.status, styles[`status--${getStatusColor(segment.status)}`])}>
                  {getStatusLabel(segment.status)}
                </span>
              </div>
              {segment.description && <p className={styles.desc}>{segment.description}</p>}
              <div className={styles.conditions}>
                {segment.conditionGroups.map((group, gi) => (
                  <div key={gi} className={styles.conditionGroup}>
                    {gi > 0 && <span className={styles.groupLogic}>{segment.groupsLogic}</span>}
                    <div className={styles.conditionItems}>
                      {group.conditions.map((cond, ci) => (
                        <span key={ci} className={styles.condition}>
                          {ci > 0 && <em>{group.logic}</em>}
                          {getFieldLabel(cond.field)} {getOperatorLabel(cond.operator)} {String(cond.value || '')}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
              <div className={styles.meta}>
                <span>预估用户: {segment.estimatedUsers?.toLocaleString() || '-'}</span>
                {segment.lastRefreshedAt && (
                  <span>上次刷新: {formatDateTime(segment.lastRefreshedAt)}</span>
                )}
              </div>
              <div className={styles.actions}>
                <button onClick={() => handleRefresh(segment.id)}>刷新</button>
                <button onClick={() => handleEdit(segment)}>编辑</button>
                <button onClick={() => setDeleteConfirm(segment.id)}>删除</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 创建/编辑弹窗 */}
      <Modal
        visible={showModal}
        title={editingSegment ? '编辑人群包' : '新建人群包'}
        onClose={() => setShowModal(false)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setShowModal(false)}>取消</Button>
            <Button variant="primary" onClick={handleSave}>保存</Button>
          </div>
        }
        width={720}
      >
        <div className={styles.form}>
          <div className={styles.formGroup}>
            <label>人群包名称 *</label>
            <input
              type="text"
              value={formData.name}
              onChange={e => setFormData({ ...formData, name: e.target.value })}
              placeholder="如: 高价值用户, 沉睡用户"
            />
          </div>
          <div className={styles.formGroup}>
            <label>描述</label>
            <textarea
              value={formData.description}
              onChange={e => setFormData({ ...formData, description: e.target.value })}
              placeholder="人群包说明"
              rows={2}
            />
          </div>

          {/* 条件组 */}
          <div className={styles.conditionsSection}>
            <div className={styles.conditionsSectionHeader}>
              <label>筛选条件</label>
              <div className={styles.groupsLogic}>
                <span>条件组之间:</span>
                <select
                  value={formData.groupsLogic}
                  onChange={e => setFormData({ ...formData, groupsLogic: e.target.value as LogicOperator })}
                >
                  <option value="AND">全部满足 (AND)</option>
                  <option value="OR">任一满足 (OR)</option>
                </select>
              </div>
            </div>

            {formData.conditionGroups.map((group, gi) => (
              <div key={gi} className={styles.conditionGroupEdit}>
                <div className={styles.groupHeader}>
                  <span>条件组 {gi + 1}</span>
                  <div className={styles.groupControls}>
                    <select
                      value={group.logic}
                      onChange={e => updateConditionGroup(gi, { logic: e.target.value as LogicOperator })}
                    >
                      <option value="AND">全部满足</option>
                      <option value="OR">任一满足</option>
                    </select>
                    {formData.conditionGroups.length > 1 && (
                      <button onClick={() => removeConditionGroup(gi)}>删除组</button>
                    )}
                  </div>
                </div>
                <div className={styles.conditionsList}>
                  {group.conditions.map((cond, ci) => (
                    <div key={ci} className={styles.conditionRow}>
                      <select
                        value={cond.field}
                        onChange={e => updateCondition(gi, ci, { field: e.target.value })}
                      >
                        {SEGMENT_FIELD_OPTIONS.map(opt => (
                          <option key={opt.value} value={opt.value}>{opt.label}</option>
                        ))}
                      </select>
                      <select
                        value={cond.operator}
                        onChange={e => updateCondition(gi, ci, { operator: e.target.value as ConditionOperator })}
                      >
                        {CONDITION_OPERATOR_OPTIONS.map(opt => (
                          <option key={opt.value} value={opt.value}>{opt.label}</option>
                        ))}
                      </select>
                      {cond.field === 'tag' ? (
                        <select
                          value={String(cond.value || '')}
                          onChange={e => updateCondition(gi, ci, { value: e.target.value })}
                        >
                          <option value="">选择标签</option>
                          {tags.map(tag => (
                            <option key={tag.id} value={tag.code}>{tag.name}</option>
                          ))}
                        </select>
                      ) : (
                        <input
                          type="text"
                          value={String(cond.value || '')}
                          onChange={e => updateCondition(gi, ci, { value: e.target.value })}
                          placeholder="值"
                        />
                      )}
                      <button
                        className={styles.removeBtn}
                        onClick={() => removeCondition(gi, ci)}
                      >
                        ×
                      </button>
                    </div>
                  ))}
                  <button className={styles.addCondBtn} onClick={() => addCondition(gi)}>
                    + 添加条件
                  </button>
                </div>
              </div>
            ))}
            <button className={styles.addGroupBtn} onClick={addConditionGroup}>
              + 添加条件组
            </button>
          </div>
        </div>
      </Modal>

      {/* 删除确认弹窗 */}
      <Modal
        visible={!!deleteConfirm}
        title="确认删除"
        onClose={() => setDeleteConfirm(null)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setDeleteConfirm(null)}>取消</Button>
            <Button variant="danger" onClick={handleDelete}>确认删除</Button>
          </div>
        }
        width={400}
      >
        <p>确定要删除这个人群包吗？此操作无法撤销。</p>
      </Modal>
    </div>
  );
};

export default AudienceSegmentsTab;
