import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, Space, 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 PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import CodeBadge from '@/components/common/CodeBadge';
import {
  agentContractApi,
  AgentContractRow,
  AgentContractSaveReq,
  AgentContractSearchParam,
} from '@/api/agent-contract';
import { GRAY, RADIUS, SHADOW, COLOR_WARNING_BG, COLOR_WARNING_BORDER } from '@/theme/tokens';

const COLUMNS: ColDef<AgentContractRow>[] = [
  { field: 'agentName',       headerName: '설계사',     width: 120, pinned: 'left' },
  { field: 'carrierName',     headerName: '보험사',     width: 140 },
  { field: 'contractType',    headerName: '계약유형',   width: 120 },
  { field: 'effectiveFrom',   headerName: '효력시작',   width: 120 },
  { field: 'effectiveTo',     headerName: '효력종료',   width: 120 },
  { field: 'commissionRate',  headerName: '위촉수수료율(%)', width: 140, type: 'numericColumn' },
  {
    field: 'status', headerName: '상태', width: 100,
    cellRenderer: (p: { value: string }) => <CodeBadge groupCode="AGENT_CONTRACT_STATUS" value={p.value} />,
  },
  { field: 'terminatedAt',    headerName: '해촉일',     width: 120 },
];

export default function AgentContracts() {
  const qc = useQueryClient();
  const [params, setParams] = useState<AgentContractSearchParam>({ pageSize: 100 });
  const [createOpen, setCreateOpen] = useState(false);
  const [terminateId, setTerminateId] = useState<number | null>(null);
  const [terminateReason, setTerminateReason] = useState('');
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['agent-contracts', params],
    queryFn: () => agentContractApi.list(params),
    retry: false,
  });

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

  const handleCreate = async () => {
    const values = await form.validateFields() as AgentContractSaveReq;
    try {
      await agentContractApi.create(values);
      message.success('위촉계약 등록 완료');
      qc.invalidateQueries({ queryKey: ['agent-contracts'] });
      setCreateOpen(false);
      form.resetFields();
    } catch { /* handled */ }
  };

  const handleTerminate = async () => {
    if (!terminateId) return;
    try {
      await agentContractApi.terminate(terminateId, terminateReason);
      message.success('해촉 처리 완료');
      qc.invalidateQueries({ queryKey: ['agent-contracts'] });
      setTerminateId(null);
      setTerminateReason('');
    } catch { /* handled */ }
  };

  return (
    <PageContainer
      title="위촉계약 관리"
      description="보험사-설계사 위촉계약 목록 및 해촉 처리"
      extra={
        <PermissionButton menuCode="AGENT_CONTRACTS" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
          + 위촉계약 등록
        </PermissionButton>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/agent-contracts 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'agentName', label: '설계사명', span: 6 },
          { type: 'code', name: 'status',    label: '상태',     groupCode: 'AGENT_CONTRACT_STATUS', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as AgentContractSearchParam, pageSize: 100 })}
        onReset={() => setParams({ pageSize: 100 })}
      />

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<AgentContractRow>
          rows={rows}
          columns={[
            ...COLUMNS,
            {
              headerName: '액션', width: 180, pinned: 'right',
              cellRenderer: (p: { data: AgentContractRow }) => (
                <Space>
                  <PermissionButton
                    menuCode="AGENT_CONTRACTS" permCode="APPROVE" size="small" danger
                    disabled={p.data.status === 'TERMINATED'}
                    onClick={() => { setTerminateId(p.data.contractId); setTerminateReason(''); }}
                  >
                    해촉
                  </PermissionButton>
                </Space>
              ),
            },
          ]}
          loading={isLoading}
          height={600}
          rowKey="contractId"
          getRowStyle={(params) => {
            if (params.data?.status === 'TERMINATED') {
              return { background: COLOR_WARNING_BG, borderLeft: `3px solid ${COLOR_WARNING_BORDER}` };
            }
            return undefined;
          }}
        />
      </ProCard>

      {/* 등록 모달 */}
      <Modal title="위촉계약 등록" open={createOpen} onOk={handleCreate} onCancel={() => setCreateOpen(false)} okText="등록" cancelText="취소">
        <Form form={form} layout="vertical">
          <Form.Item name="agentId" label="설계사 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="carrierId" label="보험사 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="contractType" label="계약유형" rules={[{ required: true }]}>
            <Input placeholder="EXCLUSIVE / GENERAL" />
          </Form.Item>
          <Form.Item name="effectiveFrom" label="효력시작일" rules={[{ required: true }]}>
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="effectiveTo" label="효력종료일">
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="commissionRate" label="위촉수수료율(%)" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} max={100} step={0.01} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 해촉 모달 */}
      <Modal
        title="해촉 처리"
        open={terminateId !== null}
        onOk={handleTerminate}
        onCancel={() => setTerminateId(null)}
        okText="해촉 확정"
        okButtonProps={{ danger: true }}
        cancelText="취소"
      >
        <Form layout="vertical">
          <Form.Item label="해촉 사유" required>
            <Input.TextArea
              rows={3}
              value={terminateReason}
              onChange={(e) => setTerminateReason(e.target.value)}
              placeholder="해촉 사유를 입력하세요"
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
