import { useRef, useState } from 'react';
import { Tag, message } from 'antd';
import {
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProTable,
  type ActionType,
  type ProColumns,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import PermissionButton from '@/components/common/PermissionButton';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import {
  periodCloseApi,
  PeriodCloseResp,
  PeriodCloseCreateReq,
} from '@/api/period-close';

// ── 상수 ─────────────────────────────────────────────────────────────────
const MENU_CODE = 'PERIOD_CLOSE';

// YYYYMM 유효성 검사
function isValidYYYYMM(v: string): boolean {
  if (!/^\d{6}$/.test(v)) return false;
  const year = parseInt(v.slice(0, 4), 10);
  const month = parseInt(v.slice(4, 6), 10);
  return year >= 2000 && year <= 2099 && month >= 1 && month <= 12;
}

// ── 마감상태 Tag 렌더러 ───────────────────────────────────────────────────
function CloseStatusTag({ status }: { status: 'CLOSED' | 'REOPENED' | string }) {
  if (status === 'CLOSED') {
    return (
      <Tag
        style={{
          color: '#E24B4A',
          background: '#FCEBEB',
          border: '1px solid #F4C8C8',
          margin: 0,
          padding: '0 8px',
          height: 22,
          lineHeight: '20px',
          fontSize: 12,
          fontWeight: 500,
          borderRadius: 4,
        }}
      >
        마감
      </Tag>
    );
  }
  if (status === 'REOPENED') {
    return (
      <Tag
        style={{
          color: '#BA7517',
          background: '#FAEEDA',
          border: '1px solid #F1D9A8',
          margin: 0,
          padding: '0 8px',
          height: 22,
          lineHeight: '20px',
          fontSize: 12,
          fontWeight: 500,
          borderRadius: 4,
        }}
      >
        재오픈
      </Tag>
    );
  }
  return <Tag>{status}</Tag>;
}

// ── 컴포넌트 ──────────────────────────────────────────────────────────────
export default function PeriodClose() {
  const actionRef = useRef<ActionType>();

  // 마감 등록 모달
  const [closeModal, setCloseModal] = useState(false);
  // 재오픈 모달
  const [reopenModal, setReopenModal] = useState<{
    open: boolean;
    record?: PeriodCloseResp;
  }>({ open: false });

  const { data: statusCodes = [] } = useCommonCodes('PERIOD_CLOSE_STATUS');

  // ── 마감 저장 ──────────────────────────────────────────────────────────
  const onClose = async (values: Record<string, unknown>) => {
    const req: PeriodCloseCreateReq = {
      closeMonth: values.closeMonth as string,
      note: values.note as string | undefined,
    };
    await periodCloseApi.close(req);
    message.success('마감 처리 완료');
    setCloseModal(false);
    actionRef.current?.reload();
    return true;
  };

  // ── 재오픈 저장 ────────────────────────────────────────────────────────
  const onReopen = async (values: Record<string, unknown>) => {
    if (!reopenModal.record) return false;
    await periodCloseApi.reopen(reopenModal.record.closeId, {
      reopenReason: values.reopenReason as string,
    });
    message.success('재오픈 처리 완료');
    setReopenModal({ open: false });
    actionRef.current?.reload();
    return true;
  };

  // ── 날짜 포맷 ──────────────────────────────────────────────────────────
  const fmtDt = (v?: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-');

  // ── 컬럼 ───────────────────────────────────────────────────────────────
  const columns: ProColumns<PeriodCloseResp>[] = [
    {
      title: '정산월',
      dataIndex: 'closeMonth',
      width: 90,
      align: 'center',
      // API 검색 파라미터명: settleMonth
      fieldProps: { placeholder: '예: 202501', maxLength: 6 },
    },
    {
      title: '마감상태',
      dataIndex: 'closeStatus',
      width: 100,
      valueType: 'select',
      valueEnum: Object.fromEntries(
        statusCodes.map((c) => [c.code, { text: c.codeName }]),
      ),
      render: (_, r) => <CloseStatusTag status={r.closeStatus} />,
    },
    {
      title: '마감일시',
      dataIndex: 'closedAt',
      width: 150,
      search: false,
      render: (_, r) => fmtDt(r.closedAt),
    },
    {
      title: '마감자',
      dataIndex: 'closedByName',
      width: 100,
      search: false,
      render: (_, r) => r.closedByName ?? '-',
    },
    {
      title: '재오픈일시',
      dataIndex: 'reopenAt',
      width: 150,
      search: false,
      render: (_, r) => fmtDt(r.reopenAt),
    },
    {
      title: '재오픈자',
      dataIndex: 'reopenByName',
      width: 100,
      search: false,
      render: (_, r) => r.reopenByName ?? '-',
    },
    {
      title: '비고',
      dataIndex: 'note',
      width: 200,
      ellipsis: true,
      search: false,
      render: (_, r) => r.note ?? '-',
    },
    {
      title: '액션',
      valueType: 'option',
      width: 100,
      fixed: 'right',
      render: (_, r) =>
        r.closeStatus === 'CLOSED' ? (
          <PermissionButton
            menuCode={MENU_CODE}
            permCode="UPDATE"
            size="small"
            type="link"
            onClick={() => setReopenModal({ open: true, record: r })}
          >
            재오픈
          </PermissionButton>
        ) : null,
    },
  ];

  // ── 렌더링 ─────────────────────────────────────────────────────────────
  return (
    <PageContainer title="정산 마감 관리" description="정산월 마감 처리 및 재오픈 관리">
      <ProTable<PeriodCloseResp>
        actionRef={actionRef}
        rowKey="closeId"
        columns={columns}
        scroll={{ x: 1000 }}
        request={async (params) => {
          const { current, pageSize, closeMonth, closeStatus } =
            params as { current?: number; pageSize?: number; closeMonth?: string; closeStatus?: string };
          const res = await periodCloseApi.list({
            settleMonth: closeMonth,   // API 파라미터명: settleMonth
            closeStatus,
            pageNum: current,
            pageSize,
          });
          return { data: res.list, total: res.total, success: true };
        }}
        pagination={{
          pageSize: 30,
          showSizeChanger: true,
          pageSizeOptions: ['20', '50', '100'],
          showTotal: (total) => `총 ${total.toLocaleString()}건`,
        }}
        search={{
          labelWidth: 'auto',
          searchText: '검색',
          resetText: '초기화',
          collapsed: false,
          collapseRender: false,
        }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton
            key="close"
            menuCode={MENU_CODE}
            permCode="CREATE"
            type="primary"
            onClick={() => setCloseModal(true)}
          >
            + 마감 처리
          </PermissionButton>,
        ]}
        dateFormatter="string"
      />

      {/* ── 마감 등록 모달 ─────────────────────────────────────────────── */}
      <ModalForm
        title="마감 처리"
        open={closeModal}
        onOpenChange={(o) => !o && setCloseModal(false)}
        width={440}
        layout="vertical"
        key={closeModal ? 'close-open' : 'close-closed'}
        onFinish={onClose}
        submitter={{ searchConfig: { submitText: '마감 처리', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProFormText
          name="closeMonth"
          label="정산월"
          rules={[
            { required: true, message: '정산월을 입력하세요' },
            {
              validator: (_, v) =>
                !v || isValidYYYYMM(v)
                  ? Promise.resolve()
                  : Promise.reject(new Error('YYYYMM 6자리로 입력하세요 (예: 202501)')),
            },
          ]}
          width="md"
          placeholder="예: 202501"
          fieldProps={{ maxLength: 6 }}
        />
        <ProFormTextArea
          name="note"
          label="비고"
          width="xl"
          placeholder="마감 관련 메모를 입력하세요 (선택)"
          fieldProps={{ rows: 3 }}
        />
      </ModalForm>

      {/* ── 재오픈 모달 ────────────────────────────────────────────────── */}
      <ModalForm
        title={`재오픈 처리 — ${reopenModal.record?.closeMonth ?? ''}`}
        open={reopenModal.open}
        onOpenChange={(o) => !o && setReopenModal({ open: false })}
        width={440}
        layout="vertical"
        key={reopenModal.record?.closeId ?? 'reopen-closed'}
        onFinish={onReopen}
        submitter={{ searchConfig: { submitText: '재오픈', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <div style={{ marginBottom: 16, color: '#666', fontSize: 13 }}>
          재오픈 사유를 입력하면 해당 정산월이 다시 편집 가능 상태로 변경됩니다.
        </div>
        <ProFormTextArea
          name="reopenReason"
          label="재오픈 사유"
          rules={[{ required: true, message: '재오픈 사유를 입력하세요' }]}
          width="xl"
          placeholder="재오픈 사유를 상세히 입력하세요"
          fieldProps={{ rows: 4 }}
        />
      </ModalForm>
    </PageContainer>
  );
}
