import { useRef, useState } from 'react';
import { Modal, Switch, Tag, message } from 'antd';
import {
  ModalForm, ProForm, ProFormSelect, ProFormText,
  ProTable, type ActionType, type ProColumns,
} from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import PageContainer from '@/components/common/PageContainer';
import PermissionButton from '@/components/common/PermissionButton';
import { companyApi, CompanyResp, CompanySaveReq, CompanySearchParam } from '@/api/company';

const COMPANY_TYPE_OPTIONS = [
  { value: 'LIFE', label: '생명보험' },
  { value: 'NON_LIFE', label: '손해보험' },
  { value: 'OTHER', label: '기타' },
];

export default function CompanyList() {
  const actionRef = useRef<ActionType>();
  const [modal, setModal] = useState<{ open: boolean; editId?: number }>({ open: false });

  const { data: editing } = useQuery({
    queryKey: ['company', 'detail', modal.editId],
    queryFn: async () => {
      // 목록에서 선택한 행 데이터를 editing으로 쓰기 위해 단건 조회가 없으면 목록에서 찾음
      // 백엔드 단건 엔드포인트가 없으므로 editRecord state로 대체
      return null;
    },
    enabled: false,
  });
  const [editRecord, setEditRecord] = useState<CompanyResp | null>(null);

  const openCreate = () => {
    setEditRecord(null);
    setModal({ open: true });
  };

  const openEdit = (record: CompanyResp) => {
    setEditRecord(record);
    setModal({ open: true, editId: record.companyId });
  };

  const onSubmit = async (v: any) => {
    const req: CompanySaveReq = {
      ...v,
      isActive: v.isActive ? 'Y' : 'N',
    };
    if (modal.editId) {
      await companyApi.update(modal.editId, req);
      message.success('수정 완료');
    } else {
      await companyApi.create(req);
      message.success('등록 완료');
    }
    setModal({ open: false });
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<CompanyResp>[] = [
    { title: '검색어', dataIndex: 'searchKeyword', hideInTable: true,
      fieldProps: { placeholder: '회사명 / 사업자번호' } },
    { title: '회사코드', dataIndex: 'companyCode', width: 100, search: false },
    { title: '회사명', dataIndex: 'companyName', width: 180,
      render: (_, r) => <strong>{r.companyName}</strong> },
    { title: '구분', dataIndex: 'companyType', width: 100, search: false },
    { title: '사업자번호', dataIndex: 'bizNo', width: 130, search: false },
    { title: '담당자', dataIndex: 'contactName', width: 100, search: false },
    { title: '연락처', dataIndex: 'contactPhone', width: 130, search: false },
    { title: '이메일', dataIndex: 'contactEmail', width: 200, search: false },
    {
      title: '활성', dataIndex: 'isActive', width: 80, search: false,
      render: (_, r) => <Tag color={r.isActive === 'Y' ? 'success' : 'default'}>
        {r.isActive === 'Y' ? '활성' : '비활성'}</Tag>,
    },
    {
      title: '액션', valueType: 'option', width: 100, fixed: 'right',
      render: (_, r) => [
        <PermissionButton key="edit" menuCode="PRODUCT_COMPANY" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
      ],
    },
  ];

  return (
    <PageContainer title="보험사 관리" description="제휴 보험사 정보 / 데이터 수신 프로파일">
      <ProTable<CompanyResp, CompanySearchParam>
        actionRef={actionRef}
        rowKey="companyId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, ...rest } = params as any;
          const res = await companyApi.list({ ...rest, pageNum: current, pageSize });
          return { data: res.list, total: res.total, success: true };
        }}
        pagination={{ pageSize: 20, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
        search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="PRODUCT_COMPANY" permCode="CREATE" type="primary"
            onClick={openCreate}>+ 보험사 등록</PermissionButton>,
        ]}
        dateFormatter="string"
      />

      <ModalForm
        title={modal.editId ? '보험사 수정' : '보험사 등록'}
        open={modal.open}
        onOpenChange={(o) => !o && setModal({ open: false })}
        width={580}
        layout="vertical"
        key={modal.editId ?? 'new'}
        initialValues={editRecord ? {
          ...editRecord,
          isActive: editRecord.isActive === 'Y',
        } : { isActive: true }}
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: modal.editId ? '수정' : '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormText
            name="companyCode" label="회사코드" rules={[{ required: true }]}
            width="md" placeholder="SAMSUNG"
            disabled={!!modal.editId}
          />
          <ProFormText
            name="companyName" label="회사명" rules={[{ required: true }]}
            width="md" placeholder="삼성생명"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            name="companyType" label="구분" width="md"
            options={COMPANY_TYPE_OPTIONS}
          />
          <ProFormText name="bizNo" label="사업자번호" width="md" placeholder="000-00-00000" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="contactName" label="담당자명" width="md" />
          <ProFormText name="contactPhone" label="연락처" width="md" placeholder="02-1234-5678" />
        </ProForm.Group>
        <ProFormText
          name="contactEmail" label="이메일" placeholder="contact@company.com"
          rules={[{ type: 'email', message: '이메일 형식이 아닙니다' }]}
        />
        <ProForm.Item name="isActive" label="활성" valuePropName="checked">
          <Switch checkedChildren="활성" unCheckedChildren="비활성" />
        </ProForm.Item>
      </ModalForm>
    </PageContainer>
  );
}
