import { useRef, useState } from 'react';
import {
  Badge,
  Form,
  Input,
  InputNumber,
  Modal,
  Radio,
  Select,
  Space,
  Tag,
  message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  ProTable,
  type ActionType,
  type ProColumns,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import DatePicker from 'antd/es/date-picker';
import PageContainer from '@/components/common/PageContainer';
import MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import {
  incentiveApi,
  IncentiveProgramResp,
  IncentiveProgramSaveReq,
  IncentiveProgramSearchParam,
} from '@/api/incentive';

const { MonthPicker } = DatePicker;

// ── 옵션 상수 ────────────────────────────────────────────────────────────────
const TARGET_TYPE_OPTIONS = [
  { label: '설계사', value: 'AGENT' },
  { label: '조직', value: 'ORG' },
  { label: '직급', value: 'GRADE' },
];

const PAY_TYPE_OPTIONS = [
  { label: '지급률 (%)', value: 'RATE' },
  { label: '고정금액 (원)', value: 'FIXED_AMOUNT' },
];

const TARGET_TYPE_COLOR: Record<string, string> = {
  AGENT: 'cyan',
  ORG:   'purple',
  GRADE: 'geekblue',
};

// ── 폼 내부 타입 ─────────────────────────────────────────────────────────────
interface ProgramFormValues extends Omit<IncentiveProgramSaveReq, 'startMonth' | 'endMonth'> {
  startMonthPicker?: unknown;
  endMonthPicker?: unknown;
}

export default function IncentiveProgram() {
  const actionRef = useRef<ActionType>();

  // 생성/수정 모달
  const [formOpen, setFormOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [editTarget, setEditTarget] = useState<IncentiveProgramResp | null>(null);
  const [form] = Form.useForm<ProgramFormValues>();
  const payType = Form.useWatch('payType', form);

  // ── 모달 열기 ────────────────────────────────────────────────────────────────
  const openCreate = () => {
    setEditTarget(null);
    form.resetFields();
    form.setFieldsValue({ payType: 'RATE' });
    setFormOpen(true);
  };

  const openEdit = (record: IncentiveProgramResp) => {
    setEditTarget(record);
    form.setFieldsValue({
      programName:     record.programName,
      programType:     record.programType,
      targetType:      record.targetType as 'AGENT' | 'ORG' | 'GRADE',
      targetGradeId:   record.targetGradeId,
      targetOrgId:     record.targetOrgId,
      productCategory: record.productCategory,
      startMonthPicker: record.startMonth
        ? dayjs(record.startMonth, 'YYYYMM')
        : undefined,
      endMonthPicker: record.endMonth
        ? dayjs(record.endMonth, 'YYYYMM')
        : undefined,
      conditionDesc:   record.conditionDesc,
      payRate:         record.payRate,
      payAmountFixed:  record.payAmountFixed,
      payType:         record.payType,
      budgetAmount:    record.budgetAmount,
    });
    setFormOpen(true);
  };

  // ── 저장 처리 ────────────────────────────────────────────────────────────────
  const handleSave = async () => {
    const values = await form.validateFields();
    const payload: IncentiveProgramSaveReq = {
      programName:     values.programName,
      programType:     values.programType,
      targetType:      values.targetType,
      targetGradeId:   values.targetGradeId,
      targetOrgId:     values.targetOrgId,
      productCategory: values.productCategory,
      startMonth:      values.startMonthPicker
        ? dayjs(values.startMonthPicker as Parameters<typeof dayjs>[0]).format('YYYYMM')
        : '',
      endMonth:        values.endMonthPicker
        ? dayjs(values.endMonthPicker as Parameters<typeof dayjs>[0]).format('YYYYMM')
        : '',
      conditionDesc:   values.conditionDesc,
      payRate:         values.payType === 'RATE' ? values.payRate : undefined,
      payAmountFixed:  values.payType === 'FIXED_AMOUNT' ? values.payAmountFixed : undefined,
      payType:         values.payType,
      budgetAmount:    values.budgetAmount,
    };
    setSaving(true);
    try {
      if (editTarget) {
        await incentiveApi.update(editTarget.programId, payload);
        message.success('시책 프로그램이 수정되었습니다');
      } else {
        await incentiveApi.create(payload);
        message.success('시책 프로그램이 등록되었습니다');
      }
      setFormOpen(false);
      setEditTarget(null);
      actionRef.current?.reload();
    } finally {
      setSaving(false);
    }
  };

  // ── 비활성화 처리 ────────────────────────────────────────────────────────────
  const handleDeactivate = (record: IncentiveProgramResp) => {
    Modal.confirm({
      title: '시책 비활성화',
      content: `"${record.programName}"을(를) 비활성화하시겠습니까?`,
      okText: '비활성화',
      okButtonProps: { danger: true },
      cancelText: '취소',
      onOk: async () => {
        await incentiveApi.deactivate(record.programId);
        message.success('비활성화되었습니다');
        actionRef.current?.reload();
      },
    });
  };

  // ── 컬럼 정의 ────────────────────────────────────────────────────────────────
  const columns: ProColumns<IncentiveProgramResp>[] = [
    {
      title: '시책명',
      dataIndex: 'programName',
      width: 180,
      fixed: 'left',
      ellipsis: true,
      search: false,
    },
    {
      title: '유형',
      dataIndex: 'programType',
      width: 110,
      search: false,
      render: (_, r) => <Tag color="blue">{r.programTypeName ?? r.programType}</Tag>,
    },
    {
      title: '대상구분',
      dataIndex: 'targetType',
      width: 90,
      valueType: 'select',
      valueEnum: Object.fromEntries(
        TARGET_TYPE_OPTIONS.map((o) => [o.value, { text: o.label }]),
      ),
      render: (_, r) => (
        <Tag color={TARGET_TYPE_COLOR[r.targetType] ?? 'default'}>
          {TARGET_TYPE_OPTIONS.find((o) => o.value === r.targetType)?.label ?? r.targetType}
        </Tag>
      ),
    },
    {
      title: '대상 조직/직급',
      dataIndex: 'targetOrgName',
      width: 140,
      ellipsis: true,
      search: false,
      render: (_, r) => r.targetOrgName ?? r.targetGradeName ?? '-',
    },
    {
      title: '시작월',
      dataIndex: 'startMonth',
      width: 90,
      valueType: 'dateMonth',
      fieldProps: { format: 'YYYYMM' },
    },
    {
      title: '종료월',
      dataIndex: 'endMonth',
      width: 90,
      valueType: 'dateMonth',
      fieldProps: { format: 'YYYYMM' },
    },
    {
      title: '지급방식',
      dataIndex: 'payType',
      width: 100,
      search: false,
      render: (_, r) =>
        r.payType === 'RATE' ? (
          <Tag color="gold">지급률</Tag>
        ) : (
          <Tag color="volcano">고정금액</Tag>
        ),
    },
    {
      title: '지급률/지급액',
      dataIndex: 'payRate',
      width: 130,
      align: 'right',
      search: false,
      render: (_, r) =>
        r.payType === 'RATE' ? (
          <span style={{ fontVariantNumeric: 'tabular-nums' }}>
            {r.payRate != null ? `${r.payRate}%` : '-'}
          </span>
        ) : (
          <MoneyText value={r.payAmountFixed} />
        ),
    },
    {
      title: '예산',
      dataIndex: 'budgetAmount',
      width: 130,
      align: 'right',
      search: false,
      render: (_, r) => <MoneyText value={r.budgetAmount} />,
    },
    {
      title: '활성여부',
      dataIndex: 'isActive',
      width: 90,
      search: false,
      render: (_, r) =>
        r.isActive ? (
          <Badge status="success" text="활성" />
        ) : (
          <Badge status="default" text="비활성" />
        ),
    },
    {
      title: '액션',
      dataIndex: 'programId',
      width: 160,
      fixed: 'right',
      search: false,
      render: (_, r) => (
        <Space>
          <PermissionButton
            menuCode="INCENTIVE_PROG"
            permCode="UPDATE"
            size="small"
            onClick={() => openEdit(r)}
          >
            수정
          </PermissionButton>
          {r.isActive && (
            <PermissionButton
              menuCode="INCENTIVE_PROG"
              permCode="UPDATE"
              size="small"
              danger
              onClick={() => handleDeactivate(r)}
            >
              비활성화
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      title="시책 프로그램 관리"
      description="설계사/조직/직급 대상 시책 프로그램 등록 및 관리"
    >
      <ProTable<IncentiveProgramResp, IncentiveProgramSearchParam>
        actionRef={actionRef}
        rowKey="programId"
        columns={columns}
        scroll={{ x: 1400 }}
        request={async (params) => {
          const { current, pageSize, programType, targetType, startMonth, endMonth } =
            params as any;
          const res = await incentiveApi.list({
            programType,
            targetType,
            startMonth: startMonth
              ? dayjs(startMonth).format('YYYYMM')
              : undefined,
            endMonth: endMonth
              ? dayjs(endMonth).format('YYYYMM')
              : undefined,
            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 }}
        dateFormatter="string"
        toolBarRender={() => [
          <PermissionButton
            key="create"
            menuCode="INCENTIVE_PROG"
            permCode="CREATE"
            type="primary"
            icon={<PlusOutlined />}
            onClick={openCreate}
          >
            시책 등록
          </PermissionButton>,
        ]}
      />

      {/* ── 생성/수정 모달 ────────────────────────────────────────────────────── */}
      <Modal
        title={editTarget ? '시책 프로그램 수정' : '시책 프로그램 등록'}
        open={formOpen}
        onOk={handleSave}
        onCancel={() => setFormOpen(false)}
        confirmLoading={saving}
        okText={editTarget ? '수정' : '등록'}
        cancelText="닫기"
        destroyOnClose
        width={640}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="programName"
            label="시책명"
            rules={[{ required: true, message: '시책명을 입력해주세요' }]}
          >
            <Input placeholder="시책 프로그램명" />
          </Form.Item>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item
              name="programType"
              label="시책 유형"
              rules={[{ required: true, message: '시책 유형을 입력해주세요' }]}
              style={{ flex: 1 }}
            >
              <Input placeholder="시책 유형 코드 (예: RECRUIT_BOOST)" />
            </Form.Item>
            <Form.Item
              name="targetType"
              label="대상 구분"
              rules={[{ required: true, message: '대상 구분을 선택해주세요' }]}
              style={{ flex: 1 }}
            >
              <Select placeholder="대상 구분" options={TARGET_TYPE_OPTIONS} />
            </Form.Item>
          </Space>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item name="targetOrgId" label="대상 조직 ID" style={{ flex: 1 }}>
              <InputNumber style={{ width: '100%' }} placeholder="조직 ID (선택)" min={1} />
            </Form.Item>
            <Form.Item name="targetGradeId" label="대상 직급 ID" style={{ flex: 1 }}>
              <InputNumber style={{ width: '100%' }} placeholder="직급 ID (선택)" min={1} />
            </Form.Item>
          </Space>

          <Form.Item name="productCategory" label="상품 카테고리">
            <Input placeholder="상품 카테고리 (선택)" />
          </Form.Item>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item
              name="startMonthPicker"
              label="시작월"
              rules={[{ required: true, message: '시작월을 선택해주세요' }]}
              style={{ flex: 1 }}
            >
              <MonthPicker style={{ width: '100%' }} format="YYYYMM" placeholder="YYYYMM" />
            </Form.Item>
            <Form.Item
              name="endMonthPicker"
              label="종료월"
              rules={[{ required: true, message: '종료월을 선택해주세요' }]}
              style={{ flex: 1 }}
            >
              <MonthPicker style={{ width: '100%' }} format="YYYYMM" placeholder="YYYYMM" />
            </Form.Item>
          </Space>

          <Form.Item name="conditionDesc" label="조건 설명">
            <Input.TextArea rows={2} placeholder="지급 조건 상세 설명" />
          </Form.Item>

          <Form.Item
            name="payType"
            label="지급 방식"
            rules={[{ required: true, message: '지급 방식을 선택해주세요' }]}
          >
            <Radio.Group>
              {PAY_TYPE_OPTIONS.map((o) => (
                <Radio key={o.value} value={o.value}>
                  {o.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          {payType === 'RATE' && (
            <Form.Item
              name="payRate"
              label="지급률 (%)"
              rules={[{ required: true, message: '지급률을 입력해주세요' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                max={100}
                precision={2}
                placeholder="지급률 (예: 5.5)"
                addonAfter="%"
              />
            </Form.Item>
          )}

          {payType === 'FIXED_AMOUNT' && (
            <Form.Item
              name="payAmountFixed"
              label="고정 지급액 (원)"
              rules={[{ required: true, message: '고정 지급액을 입력해주세요' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                formatter={(v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(v) => Number(v?.replace(/,/g, '') ?? 0) as unknown as 0}
                placeholder="고정 지급액"
                min={0}
                addonAfter="원"
              />
            </Form.Item>
          )}

          <Form.Item name="budgetAmount" label="예산 (원)">
            <InputNumber
              style={{ width: '100%' }}
              formatter={(v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={(v) => Number(v?.replace(/,/g, '') ?? 0) as unknown as 0}
              placeholder="예산 (선택)"
              min={0}
              addonAfter="원"
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
