import { useRef, useState } from 'react';
import { Input, Modal, Space, message } from 'antd';
import { ProTable, type ActionType, type ProColumns } from '@ant-design/pro-components';
import { useQueryClient } from '@tanstack/react-query';
import PageContainer from '@/components/common/PageContainer';
import CodeBadge from '@/components/common/CodeBadge';
import PermissionButton from '@/components/common/PermissionButton';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import { userApi, UserResp } from '@/api/user';

export default function UserList() {
  const qc = useQueryClient();
  const actionRef = useRef<ActionType>();
  const { data: statusCodes = [] } = useCommonCodes('AGENT_STATUS');

  const refresh = () => {
    qc.invalidateQueries({ queryKey: ['user'] });
    actionRef.current?.reload();
  };

  const onReset = (id: number) =>
    Modal.confirm({
      title: '비밀번호 초기화',
      content: '이 사용자의 비밀번호를 임시 비밀번호로 재설정합니다. 진행하시겠습니까?',
      onOk: async () => { await userApi.resetPassword(id); message.success('초기화 완료'); refresh(); },
    });

  const onUnlock = (id: number) =>
    Modal.confirm({
      title: '계정 잠금 해제',
      onOk: async () => { await userApi.unlock(id); message.success('해제 완료'); refresh(); },
    });

  const [phoneEdit, setPhoneEdit] = useState<{ id: number; loginId: string; phone: string } | null>(null);
  const submitPhone = async () => {
    if (!phoneEdit) return;
    await userApi.updatePhone(phoneEdit.id, phoneEdit.phone);
    message.success('전화번호 저장 완료');
    setPhoneEdit(null);
    refresh();
  };

  const columns: ProColumns<UserResp>[] = [
    {
      title: '검색어', dataIndex: 'searchKeyword', hideInTable: true,
      fieldProps: { placeholder: '아이디 / 이름' },
    },
    {
      title: '상태', dataIndex: 'status', width: 100, valueType: 'select',
      valueEnum: Object.fromEntries(statusCodes.map((c) => [c.code, { text: c.codeName }])),
      render: (_, r) => <CodeBadge groupCode="AGENT_STATUS" value={r.status} />,
    },
    { title: '로그인 ID',   dataIndex: 'loginId',   width: 120, search: false },
    { title: '이름',        dataIndex: 'userName',  width: 120, search: false },
    { title: '이메일',      dataIndex: 'email',     width: 200, search: false },
    { title: '전화번호',    dataIndex: 'phone',     width: 140, search: false,
      render: (_, r) => r.phone ?? <span style={{ color: '#bbb' }}>미등록</span> },
    { title: '소속',        dataIndex: 'orgName',   width: 160, search: false },
    { title: '연결 설계사', dataIndex: 'agentName', width: 100, search: false },
    { title: '실패횟수',    dataIndex: 'failCount', width: 90, align: 'right', search: false },
    { title: '마지막 로그인', dataIndex: 'lastLoginAt', width: 160, search: false },
    {
      title: '액션', width: 300, fixed: 'right', search: false,
      render: (_, r) => (
        <Space>
          <PermissionButton menuCode="SYSTEM_USER" permCode="UPDATE" size="small"
                            onClick={() => setPhoneEdit({ id: r.userId, loginId: r.loginId, phone: r.phone ?? '' })}>
            전화번호
          </PermissionButton>
          <PermissionButton menuCode="SYSTEM_USER" permCode="UPDATE" size="small"
                            onClick={() => onReset(r.userId)}>비번초기화</PermissionButton>
          {r.status === 'LOCKED' && (
            <PermissionButton menuCode="SYSTEM_USER" permCode="UPDATE" size="small" type="primary"
                              onClick={() => onUnlock(r.userId)}>잠금해제</PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer title="사용자 관리" description="시스템 사용자 / 역할 매핑 / 비밀번호">
      <ProTable<UserResp>
        actionRef={actionRef}
        rowKey="userId"
        columns={columns}
        scroll={{ x: 1300 }}
        request={async (params) => {
          const { current, pageSize, ...rest } = params as any;
          const res = await userApi.list({ ...rest, 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"
      />

      <Modal
        title={`전화번호 등록${phoneEdit ? ` — ${phoneEdit.loginId}` : ''}`}
        open={!!phoneEdit}
        onCancel={() => setPhoneEdit(null)}
        onOk={submitPhone}
        okText="저장"
        cancelText="취소"
        destroyOnClose
      >
        <Input
          autoFocus
          placeholder="010-1234-5678"
          value={phoneEdit?.phone ?? ''}
          onChange={(e) => setPhoneEdit((p) => (p ? { ...p, phone: e.target.value } : p))}
          onPressEnter={submitPhone}
        />
        <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
          SMS 결재 알림 발송 시 사용됩니다. 비워두면 SMS 발송이 스킵됩니다.
        </div>
      </Modal>
    </PageContainer>
  );
}
