import { useState } from 'react';
import { Alert, Button, Form, Input, Modal, Space, Tag, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef } from '@ag-grid-community/core';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import { operationApi, StepCloseRow } from '@/api/operation';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

const STATUS_COLOR: Record<string, string> = { OPEN: 'green', CLOSED: 'red' };
const STATUS_LABEL: Record<string, string> = { OPEN: '열림', CLOSED: '마감' };
const STEP_LABEL: Record<string, string> = { RECEIVE: '수신마감', CALC: '계산마감', VERIFY: '검증마감', PAY: '지급마감' };

const COLS: ColDef<StepCloseRow>[] = [
  { field: 'settleMonth',  headerName: '정산월',   width: 110 },
  { field: 'stepSeq',      headerName: '순서',     width: 70, type: 'numericColumn' },
  { field: 'stepCode',     headerName: '단계코드', width: 120,
    valueFormatter: (p) => STEP_LABEL[p.value as string] ?? p.value },
  { field: 'status',       headerName: '상태',     width: 100,
    cellRenderer: (p: { value: string }) => (
      <Tag color={STATUS_COLOR[p.value] ?? 'default'}>{STATUS_LABEL[p.value] ?? p.value}</Tag>
    ) },
  { field: 'closedAt',     headerName: '마감일시', flex: 1 },
];

export default function StepClose() {
  const qc = useQueryClient();
  const [searchParams, setSearchParams] = useState<{ settleMonth?: string }>({
    settleMonth: dayjs().format('YYYYMM'),
  });
  const [createOpen, setCreateOpen] = useState(false);
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['step-close', 'list', searchParams],
    queryFn: () => operationApi.stepCloseList(searchParams),
    retry: false,
  });

  const rows = data?.list ?? [];

  const handleClose = (id: number) => Modal.confirm({
    title: '단계 마감',
    content: '해당 단계를 마감하시겠습니까?',
    onOk: async () => {
      await operationApi.stepCloseClose(id);
      message.success('마감 완료');
      qc.invalidateQueries({ queryKey: ['step-close', 'list'] });
    },
  });

  const handleReopen = (id: number) => Modal.confirm({
    title: '단계 재오픈',
    content: '해당 단계를 재오픈하시겠습니까?',
    onOk: async () => {
      await operationApi.stepCloseReopen(id);
      message.success('재오픈 완료');
      qc.invalidateQueries({ queryKey: ['step-close', 'list'] });
    },
  });

  const handleCreate = async () => {
    const values = await form.validateFields();
    try {
      await operationApi.stepCloseCreate(values);
      message.success('등록 완료');
      qc.invalidateQueries({ queryKey: ['step-close', 'list'] });
      setCreateOpen(false);
      form.resetFields();
    } catch { /* request.ts 처리 */ }
  };

  const actionCol: ColDef<StepCloseRow> = {
    headerName: '액션',
    width: 160,
    pinned: 'right',
    cellRenderer: (p: { data: StepCloseRow }) => (
      <Space>
        {p.data.status === 'OPEN' ? (
          <PermissionButton
            menuCode="STEP_CLOSE"
            permCode="APPROVE"
            size="small"
            type="primary"
            onClick={() => handleClose(p.data.stepCloseId)}
          >
            마감
          </PermissionButton>
        ) : (
          <PermissionButton
            menuCode="STEP_CLOSE"
            permCode="APPROVE"
            size="small"
            onClick={() => handleReopen(p.data.stepCloseId)}
          >
            재오픈
          </PermissionButton>
        )}
      </Space>
    ),
  };

  return (
    <PageContainer title="단계마감" description="월 정산 단계별 마감 관리">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/step-closes 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'month', name: 'settleMonth', label: '정산월', span: 6 },
        ]}
        initialValues={{ settleMonth: dayjs() }}
        onSearch={(v) => setSearchParams({ settleMonth: v.settleMonth as string })}
        onReset={() => setSearchParams({ settleMonth: dayjs().format('YYYYMM') })}
      />

      <ProCard style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <PermissionButton menuCode="STEP_CLOSE" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
            + 단계 등록
          </PermissionButton>
        </div>
        <DataGrid<StepCloseRow>
          rows={rows}
          columns={[...COLS, actionCol]}
          loading={isLoading}
          height={520}
          rowKey="stepCloseId"
        />
      </ProCard>

      <Modal title="단계 등록" open={createOpen} onOk={handleCreate} onCancel={() => { setCreateOpen(false); form.resetFields(); }} okText="저장" cancelText="취소">
        <Form form={form} layout="vertical">
          <Form.Item name="settleMonth" label="정산월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="202506" />
          </Form.Item>
          <Form.Item name="stepCode" label="단계코드" rules={[{ required: true }]}>
            <Input placeholder="RECEIVE / CALC / VERIFY / PAY" />
          </Form.Item>
          <Form.Item name="stepSeq" label="순서" rules={[{ required: true }]}>
            <Input type="number" placeholder="1~4" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
