import { useRef, useState } from 'react';
import { Form, Input, Modal, Tag, message } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import { ProTable, type ProColumns, type ActionType } from '@ant-design/pro-components';
import PageContainer from '@/components/common/PageContainer';
import PermissionButton from '@/components/common/PermissionButton';
import { configApi, SystemConfigResp } from '@/api/config';

const MENU = 'SYSTEM_CONFIG';

const GROUP_COLOR: Record<string, string> = {
  GENERAL: 'blue',
  BATCH: 'cyan',
  SECURITY: 'red',
  MAIL: 'green',
  TAX: 'orange',
};

/* ------------------------------------------------------------------ */
/*  수정 모달 상태 타입                                                  */
/* ------------------------------------------------------------------ */
type EditState =
  | { open: false }
  | { open: true; row: SystemConfigResp };

/* ------------------------------------------------------------------ */
/*  메인 컴포넌트                                                        */
/* ------------------------------------------------------------------ */
export default function SystemConfig() {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm<{ value: string }>();
  const [editState, setEditState] = useState<EditState>({ open: false });
  const [saving, setSaving] = useState(false);

  /* ---------------------------------------------------------------- */
  /*  수정 모달 열기                                                    */
  /* ---------------------------------------------------------------- */
  const openEdit = (row: SystemConfigResp) => {
    form.resetFields();
    // 암호화 항목은 현재값을 초기화하지 않음
    form.setFieldsValue({ value: row.isEncrypted === 'Y' ? '' : (row.configValue ?? '') });
    setEditState({ open: true, row });
  };

  /* ---------------------------------------------------------------- */
  /*  저장 처리                                                         */
  /* ---------------------------------------------------------------- */
  const handleSave = async () => {
    if (!editState.open) return;
    try {
      setSaving(true);
      const values = await form.validateFields();
      await configApi.update(editState.row.configKey!, values.value);
      message.success('설정 값이 수정되었습니다.');
      setEditState({ open: false });
      actionRef.current?.reload();
    } catch {
      // validateFields 실패 — 폼 에러 표시로 대체
    } finally {
      setSaving(false);
    }
  };

  /* ---------------------------------------------------------------- */
  /*  컬럼 정의                                                         */
  /* ---------------------------------------------------------------- */
  const columns: ProColumns<SystemConfigResp>[] = [
    {
      title: '그룹',
      dataIndex: 'configGroup',
      width: 110,
      valueType: 'select',
      valueEnum: {
        GENERAL: { text: '일반' },
        BATCH: { text: '배치' },
        SECURITY: { text: '보안' },
        MAIL: { text: '메일' },
        TAX: { text: '세금' },
      },
      render: (_, r) => (
        <Tag color={GROUP_COLOR[r.configGroup ?? ''] ?? 'default'}>
          {r.configGroup}
        </Tag>
      ),
    },
    {
      title: '설정 키',
      dataIndex: 'configKey',
      width: 240,
      search: false,
      render: (_, r) => (
        <code style={{ background: '#f5f5f5', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>
          {r.configKey}
        </code>
      ),
    },
    {
      title: '설정 값',
      dataIndex: 'configValue',
      search: false,
      render: (_, r) =>
        r.isEncrypted === 'Y' ? (
          <Tag color="red">암호화 (***)</Tag>
        ) : (
          <span>{r.configValue}</span>
        ),
    },
    {
      title: '타입',
      dataIndex: 'valueType',
      width: 90,
      search: false,
    },
    {
      title: '설명',
      dataIndex: 'configDesc',
      ellipsis: true,
      search: false,
    },
    {
      title: '수정 가능',
      dataIndex: 'isEditable',
      width: 100,
      align: 'center',
      search: false,
      render: (_, r) =>
        r.isEditable === 'Y' ? (
          <Tag color="success">가능</Tag>
        ) : (
          <Tag>잠김</Tag>
        ),
    },
    {
      title: '수정일시',
      dataIndex: 'updatedAt',
      width: 160,
      search: false,
    },
    {
      title: '작업',
      key: 'actions',
      width: 80,
      align: 'center',
      search: false,
      render: (_, r) => {
        if (r.isEditable !== 'Y') return null;
        return (
          <PermissionButton
            menuCode={MENU}
            permCode="UPDATE"
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => openEdit(r)}
          >
            수정
          </PermissionButton>
        );
      },
    },
  ];

  /* ---------------------------------------------------------------- */
  /*  렌더                                                              */
  /* ---------------------------------------------------------------- */
  return (
    <PageContainer
      title="시스템 설정"
      description="배치 / 보안 / 세금 / 메일 등 키-값 설정"
    >
      <ProTable<SystemConfigResp>
        actionRef={actionRef}
        rowKey="configKey"
        columns={columns}
        scroll={{ x: 1200 }}
        request={async (params) => {
          const list = await configApi.list((params as Record<string, string>).configGroup);
          return { data: list, total: list.length, success: true };
        }}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t}건` }}
        search={{
          labelWidth: 'auto',
          searchText: '검색',
          resetText: '초기화',
          collapsed: false,
          collapseRender: false,
        }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        dateFormatter="string"
      />

      {/* ========================================================= */}
      {/* 수정 모달                                                   */}
      {/* ========================================================= */}
      <Modal
        title="설정 값 수정"
        open={editState.open}
        onOk={handleSave}
        onCancel={() => setEditState({ open: false })}
        okText="저장"
        cancelText="취소"
        confirmLoading={saving}
        destroyOnClose
        width={440}
      >
        {editState.open && (
          <>
            <div style={{ marginBottom: 16, padding: '8px 12px', background: '#fafafa', borderRadius: 6, border: '1px solid #f0f0f0' }}>
              <div style={{ fontSize: 12, color: '#999', marginBottom: 4 }}>설정 키</div>
              <code style={{ fontSize: 13 }}>{editState.row.configKey}</code>
              {editState.row.configDesc && (
                <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>{editState.row.configDesc}</div>
              )}
            </div>
            <Form form={form} layout="vertical">
              <Form.Item
                name="value"
                label="새 값"
                rules={[{ required: true, message: '값을 입력하세요' }]}
              >
                {editState.row.isEncrypted === 'Y' ? (
                  <Input.Password
                    placeholder="새 비밀번호 / 암호화 값 입력"
                    autoComplete="new-password"
                  />
                ) : (
                  <Input placeholder="새 값 입력" />
                )}
              </Form.Item>
            </Form>
            {editState.row.isEncrypted === 'Y' && (
              <div style={{ fontSize: 12, color: '#faad14', marginTop: -8 }}>
                암호화 항목입니다. 저장 시 서버에서 암호화 처리됩니다.
              </div>
            )}
          </>
        )}
      </Modal>
    </PageContainer>
  );
}
