import React, { useRef, useState } from 'react';
import { useAccess } from '@umijs/max';
import { Button, message, Modal, Tag } from 'antd';
import { ActionType, ProColumns, ProTable, ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, FormOutlined, ApartmentOutlined } from '@ant-design/icons';
import {
  getJobFairList,
  addJobFair,
  updateJobFair,
  deleteJobFair,
} from '@/services/jobportal/indoorJobFair';
import type { JobFairItem, JobFairForm } from '@/services/jobportal/indoorJobFair';
import FairBoothModal from './FairBoothModal';

interface Props {
  fairId: number;
  fairInfo: JobFairItem;
  onFairUpdate: () => void;
}

const FairManageTab: React.FC<Props> = ({ fairInfo }) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [modalOpen, setModalOpen] = useState(false);
  const [editingFair, setEditingFair] = useState<JobFairItem | null>(null);
  const [boothModalOpen, setBoothModalOpen] = useState(false);
  const [boothFair, setBoothFair] = useState<JobFairItem | null>(null);

  const statusMap: Record<string, { text: string; color: string }> = {
    pending: { text: '筹备中', color: 'default' },
    ongoing: { text: '进行中', color: 'green' },
    finished: { text: '已结束', color: 'red' },
  };

  const columns: ProColumns<JobFairItem>[] = [
    { title: '招聘会名称', dataIndex: 'fairName', ellipsis: true },
    { title: '场地名称', dataIndex: 'venueName', ellipsis: true, hideInSearch: true },
    { title: '开始日期', dataIndex: 'startDate', hideInSearch: true },
    { title: '结束日期', dataIndex: 'endDate', hideInSearch: true },
    { title: '使用展位数', dataIndex: 'boothUseCount', hideInSearch: true },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => {
        const s = statusMap[record.status] || { text: record.status, color: 'default' };
        return <Tag color={s.color}>{s.text}</Tag>;
      },
    },
    { title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button key="booth" type="link" size="small" icon={<ApartmentOutlined />}
          onClick={() => { setBoothFair(record); setBoothModalOpen(true); }}
        >展位管理</Button>,
        <Button key="edit" type="link" size="small" icon={<FormOutlined />}
          hidden={!access.hasPerms('cms:indoorJobFair:edit')}
          onClick={() => { setEditingFair(record); setModalOpen(true); }}
        >编辑</Button>,
        <Button key="delete" type="link" size="small" danger icon={<DeleteOutlined />}
          hidden={!access.hasPerms('cms:indoorJobFair:remove')}
          onClick={() => {
            Modal.confirm({
              title: '确认删除',
              content: `确定删除招聘会「${record.fairName}」吗？`,
              onOk: async () => {
                const res = await deleteJobFair(record.id);
                if (res.code === 200) { message.success('删除成功'); actionRef.current?.reload(); }
                else { message.error(res.msg); }
              },
            });
          }}
        >删除</Button>,
      ],
    },
  ];

  const venueOptions = [
    { label: '石河子大学体育馆', value: 1 },
    { label: '第八师人力资源市场', value: 2 },
    { label: '阿拉尔市人才交流中心', value: 3 },
    { label: '图木舒克市职业介绍所', value: 4 },
  ];

  const venueNameMap: Record<number, string> = {
    1: '石河子大学体育馆',
    2: '第八师人力资源市场',
    3: '阿拉尔市人才交流中心',
    4: '图木舒克市职业介绍所',
  };

  return (
    <div>
      <ProTable
        headerTitle="招聘会列表"
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        scroll={{ x: 'max-content' }}
        search={{ labelWidth: 100 }}
        request={async (params) => {
          const res = await getJobFairList({
            current: params.current,
            pageSize: params.pageSize,
            fairName: params.fairName,
            startDate: params.startDate,
            endDate: params.endDate,
          } as any);
          return { data: res.rows, total: res.total, success: true };
        }}
        toolBarRender={() => [
          <Button key="add" type="primary" icon={<PlusOutlined />}
            hidden={!access.hasPerms('cms:indoorJobFair:add')}
            onClick={() => { setEditingFair(null); setModalOpen(true); }}
          >新增招聘会</Button>,
        ]}
      />

      <ModalForm
        title={editingFair ? '编辑招聘会' : '新增招聘会'}
        open={modalOpen}
        width={500}
        modalProps={{ destroyOnClose: true, onCancel: () => setModalOpen(false) }}
        onFinish={async (values) => {
          const submitValues = {
            ...values,
            venueName: venueNameMap[values.venueId as number] || '',
          };
          const res = editingFair
            ? await updateJobFair({ id: editingFair.id, ...submitValues } as JobFairForm)
            : await addJobFair(submitValues as JobFairForm);
          if (res.code === 200) { message.success(res.msg); setModalOpen(false); actionRef.current?.reload(); return true; }
          message.error(res.msg); return false;
        }}
        initialValues={editingFair}
      >
        <ProFormText name="fairName" label="招聘会名称" rules={[{ required: true, message: '请输入招聘会名称' }]} />
        <ProFormSelect name="venueId" label="选择场地" rules={[{ required: true, message: '请选择场地' }]}
          options={venueOptions} />
        <ProFormText name="startDate" label="开始日期" rules={[{ required: true, message: '请输入开始日期' }]} />
        <ProFormText name="endDate" label="结束日期" rules={[{ required: true, message: '请输入结束日期' }]} />
      </ModalForm>

      <FairBoothModal
        fair={boothFair}
        open={boothModalOpen}
        onClose={() => setBoothModalOpen(false)}
      />
    </div>
  );
};

export default FairManageTab;
