import { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Select,
  Tag,
  Space,
  Modal,
  Tabs,
  Typography,
  Statistic,
  Row,
  Col,
  Form,
  Input,
  InputNumber,
} from 'antd';
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useAuthStore } from '../../../auth/application';
import {
  usePendingExperiences,
  useExperienceStatistics,
  useApproveExperience,
  useRejectExperience,
  useCreateExperience,
  useRunEvolution,
} from '../../application';
import type { Experience } from '../../infrastructure';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

const EXPERIENCE_TYPES = [
  { value: 'COMMON_QUESTION', label: '常见问题' },
  { value: 'ANSWER_TEMPLATE', label: '回答模板' },
  { value: 'CLARIFICATION', label: '澄清方式' },
  { value: 'USER_PATTERN', label: '用户模式' },
  { value: 'CONVERSION_TRIGGER', label: '转化触发' },
  { value: 'KNOWLEDGE_GAP', label: '知识缺口' },
  { value: 'CONVERSATION_SKILL', label: '对话技巧' },
  { value: 'OBJECTION_HANDLING', label: '异议处理' },
];

export function ExperiencePage() {
  const [activeTab, setActiveTab] = useState('pending');
  const [typeFilter, setTypeFilter] = useState<string>();
  const [selectedExperience, setSelectedExperience] = useState<Experience | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [createForm] = Form.useForm();
  const admin = useAuthStore((state) => state.admin);

  const { data: pendingData, isLoading: pendingLoading } = usePendingExperiences(
    typeFilter,
    activeTab === 'pending'
  );
  const { data: stats } = useExperienceStatistics();
  const approveMutation = useApproveExperience();
  const rejectMutation = useRejectExperience();
  const createMutation = useCreateExperience();
  const runEvolutionMutation = useRunEvolution();

  const handleView = (exp: Experience) => {
    setSelectedExperience(exp);
    setIsModalOpen(true);
  };

  const handleApprove = (id: string) => {
    if (admin?.id) {
      approveMutation.mutate({ id, adminId: admin.id });
    }
  };

  const handleReject = (id: string) => {
    if (admin?.id) {
      rejectMutation.mutate({ id, adminId: admin.id });
    }
  };

  const handleCreate = async () => {
    try {
      const values = await createForm.validateFields();
      createMutation.mutate(values, {
        onSuccess: () => {
          setIsCreateModalOpen(false);
          createForm.resetFields();
        },
      });
    } catch {
      // validation error — form will show inline errors
    }
  };

  const getTypeLabel = (type: string) => {
    return EXPERIENCE_TYPES.find((t) => t.value === type)?.label || type;
  };

  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; label: string }> = {
      PENDING: { color: 'orange', label: '待审核' },
      APPROVED: { color: 'green', label: '已通过' },
      REJECTED: { color: 'red', label: '已拒绝' },
      DEPRECATED: { color: 'default', label: '已弃用' },
    };
    const s = statusMap[status] || { color: 'default', label: status };
    return <Tag color={s.color}>{s.label}</Tag>;
  };

  const columns = [
    {
      title: '类型',
      dataIndex: 'experienceType',
      key: 'experienceType',
      render: (type: string) => <Tag>{getTypeLabel(type)}</Tag>,
    },
    {
      title: '场景',
      dataIndex: 'scenario',
      key: 'scenario',
      ellipsis: true,
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (text: string) => (
        <Text ellipsis style={{ maxWidth: 200 }}>
          {text}
        </Text>
      ),
    },
    {
      title: '置信度',
      dataIndex: 'confidence',
      key: 'confidence',
      render: (confidence: number) => (
        <span
          className={
            confidence >= 70
              ? 'text-green-600'
              : confidence >= 40
              ? 'text-yellow-600'
              : 'text-red-600'
          }
        >
          {confidence}%
        </span>
      ),
    },
    {
      title: '来源对话',
      dataIndex: 'sourceConversationIds',
      key: 'sources',
      render: (ids: string[]) => <span>{ids?.length || 0}个</span>,
    },
    {
      title: '状态',
      dataIndex: 'verificationStatus',
      key: 'status',
      render: getStatusTag,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: Experience) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          />
          {record.verificationStatus === 'PENDING' && (
            <>
              <Button
                type="text"
                icon={<CheckOutlined />}
                className="text-green-600"
                onClick={() => handleApprove(record.id)}
                loading={approveMutation.isPending}
              />
              <Button
                type="text"
                icon={<CloseOutlined />}
                danger
                onClick={() => handleReject(record.id)}
                loading={rejectMutation.isPending}
              />
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <Title level={4} className="mb-0">系统经验管理</Title>
        <Space>
          <Button
            icon={<PlusOutlined />}
            onClick={() => setIsCreateModalOpen(true)}
          >
            新建经验
          </Button>
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={() => runEvolutionMutation.mutate({})}
            loading={runEvolutionMutation.isPending}
          >
            运行进化任务
          </Button>
        </Space>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={12} sm={6}>
          <Card>
            <Statistic title="总经验" value={stats?.total || 0} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="待审核"
              value={stats?.byStatus?.PENDING || 0}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="已通过"
              value={stats?.byStatus?.APPROVED || 0}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="已拒绝"
              value={stats?.byStatus?.REJECTED || 0}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            { key: 'pending', label: '待审核' },
            { key: 'approved', label: '已通过' },
            { key: 'rejected', label: '已拒绝' },
          ]}
        />

        <div className="mb-4">
          <Select
            placeholder="筛选类型"
            allowClear
            style={{ width: 180 }}
            value={typeFilter}
            onChange={setTypeFilter}
            options={EXPERIENCE_TYPES}
          />
        </div>

        <Table
          columns={columns}
          dataSource={pendingData?.items || []}
          rowKey="id"
          loading={pendingLoading}
          pagination={{
            total: pendingData?.total || 0,
            pageSize: 20,
          }}
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="经验详情"
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
          setSelectedExperience(null);
        }}
        footer={
          selectedExperience?.verificationStatus === 'PENDING'
            ? [
                <Button
                  key="reject"
                  danger
                  onClick={() => {
                    handleReject(selectedExperience.id);
                    setIsModalOpen(false);
                  }}
                >
                  拒绝
                </Button>,
                <Button
                  key="approve"
                  type="primary"
                  onClick={() => {
                    handleApprove(selectedExperience.id);
                    setIsModalOpen(false);
                  }}
                >
                  批准
                </Button>,
              ]
            : null
        }
        width={600}
      >
        {selectedExperience && (
          <div>
            <div className="mb-4">
              <Tag>{getTypeLabel(selectedExperience.experienceType)}</Tag>
              {getStatusTag(selectedExperience.verificationStatus)}
              {selectedExperience.isActive && <Tag color="blue">激活中</Tag>}
            </div>

            <div className="mb-4">
              <Text type="secondary">场景</Text>
              <Paragraph>{selectedExperience.scenario}</Paragraph>
            </div>

            <div className="mb-4">
              <Text type="secondary">内容</Text>
              <Paragraph>{selectedExperience.content}</Paragraph>
            </div>

            <Row gutter={16}>
              <Col span={8}>
                <Statistic
                  title="置信度"
                  value={selectedExperience.confidence}
                  suffix="%"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="使用次数"
                  value={selectedExperience.usageCount}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="来源对话"
                  value={selectedExperience.sourceConversationIds?.length || 0}
                />
              </Col>
            </Row>

            {selectedExperience.relatedCategory && (
              <div className="mt-4">
                <Text type="secondary">相关类别: </Text>
                <Tag color="blue">{selectedExperience.relatedCategory}</Tag>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* 新建经验弹窗 */}
      <Modal
        title="新建经验"
        open={isCreateModalOpen}
        onCancel={() => {
          setIsCreateModalOpen(false);
          createForm.resetFields();
        }}
        onOk={handleCreate}
        okText="创建"
        cancelText="取消"
        confirmLoading={createMutation.isPending}
        width={600}
      >
        <Form form={createForm} layout="vertical">
          <Form.Item
            name="experienceType"
            label="经验类型"
            rules={[{ required: true, message: '请选择经验类型' }]}
          >
            <Select placeholder="选择类型" options={EXPERIENCE_TYPES} />
          </Form.Item>

          <Form.Item
            name="scenario"
            label="适用场景"
            rules={[{ required: true, message: '请描述适用场景' }]}
          >
            <Input placeholder="例如：用户咨询QMAS签证费用时" />
          </Form.Item>

          <Form.Item
            name="content"
            label="经验内容"
            rules={[{ required: true, message: '请填写经验内容' }]}
          >
            <TextArea
              rows={4}
              placeholder="例如：回答费用问题时应引用官方数据并标注更新日期，避免给出过期信息"
            />
          </Form.Item>

          <Form.Item name="relatedCategory" label="相关移民类别">
            <Select
              placeholder="可选"
              allowClear
              options={[
                { value: 'QMAS', label: '优才计划 (QMAS)' },
                { value: 'GEP', label: '一般就业政策 (GEP)' },
                { value: 'IANG', label: '非本地毕业生 (IANG)' },
                { value: 'TTPS', label: '科技人才 (TTPS)' },
                { value: 'CIES', label: '资本投资者 (CIES)' },
                { value: 'TECHTAS', label: '人才清单 (TechTAS)' },
              ]}
            />
          </Form.Item>

          <Form.Item
            name="confidence"
            label="置信度"
            initialValue={80}
          >
            <InputNumber min={0} max={100} addonAfter="%" style={{ width: '100%' }} />
          </Form.Item>

          <Text type="secondary">
            管理员手动创建的经验将自动激活，无需额外审核。
          </Text>
        </Form>
      </Modal>
    </div>
  );
}
