import React, { useState } from 'react';
import { App, Button, DatePicker, Form, Input, Modal, Select, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import api from '../../api';
import { message } from '../../ui/app-message';
import { useApiMutation } from '../../hooks/useApiMutation';
import { usePermission } from '../../hooks/usePermission';
import PermissionButton from '../PermissionButton';
import { EditableArchiveCell } from './EditableArchiveCell';
import { RECORD_TYPE_OPTIONS } from './shared';
import type { LearningRecord, TabProps } from './shared';

const LEARNING_FIELDS = {
  recordDate: 'recordDate',
  recordType: 'recordType',
  content: 'content',
  followUpMethod: 'followUpMethod',
  nextStep: 'nextStep',
} as const;

export const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
  data,
  studentId,
}) => {
  const { modal } = App.useApp();
  const { hasPermission } = usePermission();
  const canPurgeArchive = hasPermission('archive:purge');
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [saving, setSaving] = useState(false);

  const addLearningMutation = useApiMutation(
    async (payload: Record<string, unknown>) =>
      api.post(`/archive/${studentId}/learning-records`, payload),
    { invalidate: [['archive', studentId]] },
  );
  const saveLearningCellMutation = useApiMutation(
    async ({ id, field, value }: { id: number; field: string; value: unknown }) =>
      api.put(`/archive/learning-records/${id}`, { [field]: value }),
    { invalidate: [['archive', studentId]] },
  );
  const purgeLearningMutation = useApiMutation(
    async (id: number) => api.delete(`/archive/learning-records/${id}/permanent`),
    { invalidate: [['archive', studentId]] },
  );

  const handleAdd = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);
      await addLearningMutation.mutateAsync({
        ...values,
        recordDate: values.recordDate?.format('YYYY-MM-DD'),
      });
      message.success('学情记录已添加');
      setModalOpen(false);
      form.resetFields();
    } catch {
      // 错误提示由 useApiMutation 统一处理
    } finally {
      setSaving(false);
    }
  };

  const saveCell = async (record: LearningRecord, field: string, value: unknown) => {
    try {
      await saveLearningCellMutation.mutateAsync({ id: record.id, field, value });
      message.success('学情记录已保存');
    } catch {
      // 错误提示由 useApiMutation 统一处理
    }
  };

  const handlePurge = (record: LearningRecord) => {
    modal.confirm({
      title: `永久删除学情记录（${record.recordType || `记录${record.id}`}）？`,
      content: '删除后不可恢复，学习记录将被物理删除。确定继续？',
      okText: '永久删除',
      okButtonProps: { danger: true },
      cancelText: '取消',
      onOk: async () => {
        try {
          await purgeLearningMutation.mutateAsync(record.id);
          message.success('已永久删除（不可恢复）');
        } catch {
          // 错误提示由 useApiMutation 统一处理
        }
      },
    });
  };

  const columns: ColumnsType<LearningRecord> = [
    {
      title: '记录日期',
      dataIndex: 'recordDate',
      render: (v: string, r) => (
        <EditableArchiveCell value={v} field={LEARNING_FIELDS.recordDate} record={r} editor="date" onSave={saveCell}>
          {v}
        </EditableArchiveCell>
          ),
    },
    {
      title: '记录类型',
      dataIndex: 'recordType',
      render: (v: string, r) => (
        <EditableArchiveCell value={v} field={LEARNING_FIELDS.recordType} record={r} editor="select"           options={RECORD_TYPE_OPTIONS} onSave={saveCell}>
          {RECORD_TYPE_OPTIONS.find((o) => o.value === v)?.label || v}
        </EditableArchiveCell>
          ),
    },
    {
      title: '内容',
      dataIndex: 'content',
      ellipsis: true,
      render: (v: string, r) => (
        <EditableArchiveCell value={v} field={LEARNING_FIELDS.content} record={r} editor="textarea" onSave={saveCell}>
          {v}
        </EditableArchiveCell>
          ),
    },
    {
      title: '跟进方式',
      dataIndex: 'followUpMethod',
      render: (v: string, r) => (
        <EditableArchiveCell value={v} field={LEARNING_FIELDS.followUpMethod} record={r} onSave={saveCell}>
          {v || '-'}
        </EditableArchiveCell>
          ),
    },
    {
      title: '下一步计划',
      dataIndex: 'nextStep',
      render: (v: string, r) => (
        <EditableArchiveCell value={v} field={LEARNING_FIELDS.nextStep} record={r} editor="textarea" onSave={saveCell}>
          {v || '-'}
        </EditableArchiveCell>
          ),
    },
    {
      title: '操作',
      render: (_: unknown, r: LearningRecord) =>
        r.status === 'archived' && canPurgeArchive ? (
          <Button size="small" danger type="link" onClick={() => handlePurge(r)}>
            删除
          </Button>
        ) : null,
    },
  ];

  return (
    <div>
      <PermissionButton
        permission="student:edit"
        icon={<PlusOutlined />}
        type="primary"
        onClick={() => {
          form.resetFields();
          setModalOpen(true);
        }}
        style={{ marginBottom: 16 }}
      >
        添加学情记录
      </PermissionButton>
      <Table<LearningRecord>
        columns={columns}
        dataSource={data}
        rowKey="id"
        rowClassName={(record) => (record.status === 'archived' ? 'archived-row' : '')}
        pagination={{
          defaultPageSize: 15,
          showSizeChanger: true,
          pageSizeOptions: [15, 30, 50],
        }}
      />
      <Modal
        title="添加学情记录"
        open={modalOpen && hasPermission('student:edit')}
        onOk={hasPermission('student:edit') ? handleAdd : undefined}
        onCancel={() => setModalOpen(false)}
        confirmLoading={saving}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="recordDate"
            label="记录日期"
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="recordType"
            label="记录类型"
            rules={[{ required: true, message: '请选择记录类型' }]}
          >
            <Select options={RECORD_TYPE_OPTIONS} placeholder="请选择" />
          </Form.Item>
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <Input.TextArea rows={4} placeholder="请记录学情内容" />
          </Form.Item>
          <Form.Item name="followUpMethod" label="跟进方式">
            <Input placeholder="如：电话、微信、面谈" />
          </Form.Item>
          <Form.Item name="nextStep" label="下一步计划">
            <Input placeholder="后续跟进计划" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
