import { useState } from 'react';
import { Alert, Checkbox, Form, Input, Modal, Typography, 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 AttachmentUpload from '@/components/biz/AttachmentUpload';
import { complaintApi, ComplaintRow, ComplaintSaveReq, ComplaintSearchParam } from '@/api/complaint';
import { GRAY, RADIUS, SHADOW, COLOR_ERROR_BG, COLOR_ERROR_BORDER } from '@/theme/tokens';

const { Text } = Typography;
const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';

const COLUMNS: ColDef<ComplaintRow>[] = [
  { field: 'contractNo',  headerName: '계약번호',   width: 150, pinned: 'left' },
  { field: 'agentName',   headerName: '설계사',     width: 120 },
  { field: 'complaintType', headerName: '민원유형', width: 120 },
  { field: 'content',     headerName: '민원내용',   flex: 1 },
  { field: 'receivedDate', headerName: '접수일',    width: 120 },
  {
    field: 'status', headerName: '상태', width: 100,
    cellRenderer: (p: { value: string }) => <CodeBadge groupCode="COMPLAINT_STATUS" value={p.value} />,
  },
  {
    field: 'chargebackTriggered', headerName: '환수', width: 80,
    cellRenderer: (p: { value: boolean }) =>
      p.value ? <Text style={{ color: '#E24B4A', fontWeight: 700 }}>환수</Text> : <Text style={{ color: GRAY[400] }}>-</Text>,
  },
  { field: 'chargebackAmount', headerName: '환수금액', width: 120, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'closedAt', headerName: '처리일', width: 120 },
];

export default function Complaints() {
  const qc = useQueryClient();
  const [params, setParams] = useState<ComplaintSearchParam>({ pageSize: 100 });
  const [createOpen, setCreateOpen] = useState(false);
  const [closeTarget, setCloseTarget] = useState<number | null>(null);
  const [processNote, setProcessNote] = useState('');
  const [createdId, setCreatedId] = useState<number | null>(null);
  const [form] = Form.useForm();

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

  const rows = data?.list ?? [];
  const chargebackCount = rows.filter((r) => r.chargebackTriggered).length;

  const handleCreate = async () => {
    const values = await form.validateFields() as ComplaintSaveReq;
    try {
      const created = await complaintApi.create(values);
      message.success('민원 등록 완료');
      qc.invalidateQueries({ queryKey: ['complaints'] });
      setCreatedId(created.complaintId);
      setCreateOpen(false);
      form.resetFields();
    } catch { /* handled */ }
  };

  const handleClose = async () => {
    if (!closeTarget) return;
    try {
      await complaintApi.close(closeTarget, processNote);
      message.success('처리완료');
      qc.invalidateQueries({ queryKey: ['complaints'] });
      setCloseTarget(null);
      setProcessNote('');
    } catch { /* handled */ }
  };

  return (
    <PageContainer
      title="민원 관리"
      description="고객 민원 접수, 처리, 환수 연동"
      extra={
        <PermissionButton menuCode="COMPLAINTS" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
          + 민원 등록
        </PermissionButton>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/complaints 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      {chargebackCount > 0 && (
        <div style={{
          padding: '12px 20px',
          background: COLOR_ERROR_BG,
          border: `1px solid ${COLOR_ERROR_BORDER}`,
          borderRadius: RADIUS.md,
          marginBottom: 16,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Text style={{ fontSize: 13, color: '#E24B4A', fontWeight: 700 }}>환수 민원 {chargebackCount}건 — 정산 시 자동 반영</Text>
        </div>
      )}

      <SearchForm
        conditions={[
          { type: 'text',      name: 'contractNo',   label: '계약번호', span: 6 },
          { type: 'text',      name: 'agentName',    label: '설계사명', span: 6 },
          { type: 'code',      name: 'complaintType', label: '민원유형', groupCode: 'COMPLAINT_TYPE', span: 6 },
          { type: 'code',      name: 'status',       label: '상태',     groupCode: 'COMPLAINT_STATUS', span: 6 },
          { type: 'dateRange', name: 'receivedDate', label: '접수일',   span: 8 },
        ]}
        onSearch={(v) => setParams({ ...v as ComplaintSearchParam, pageSize: 100 })}
        onReset={() => setParams({ pageSize: 100 })}
      />

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<ComplaintRow>
          rows={rows}
          columns={[
            ...COLUMNS,
            {
              headerName: '액션', width: 120, pinned: 'right',
              cellRenderer: (p: { data: ComplaintRow }) => (
                <PermissionButton
                  menuCode="COMPLAINTS" permCode="APPROVE" size="small" type="primary"
                  disabled={p.data.status === 'CLOSED'}
                  onClick={() => { setCloseTarget(p.data.complaintId); setProcessNote(''); }}
                >
                  처리완료
                </PermissionButton>
              ),
            },
          ]}
          loading={isLoading}
          height={600}
          rowKey="complaintId"
          getRowStyle={(params) => {
            if (params.data?.chargebackTriggered) {
              return { background: '#FEF0F1' };
            }
            return undefined;
          }}
        />
      </ProCard>

      {/* 등록 모달 */}
      <Modal title="민원 등록" open={createOpen} onOk={handleCreate} onCancel={() => setCreateOpen(false)} okText="등록" cancelText="취소" width={560}>
        <Form form={form} layout="vertical">
          <Form.Item name="contractNo" label="계약번호" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="agentId" label="설계사 ID" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="complaintType" label="민원유형" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="content" label="민원내용" rules={[{ required: true }]}>
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item name="receivedDate" label="접수일" rules={[{ required: true }]}>
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="chargebackTriggered" label="환수 연동" valuePropName="checked">
            <Checkbox>환수 트리거 (13M 이내 민원)</Checkbox>
          </Form.Item>
        </Form>
      </Modal>

      {/* 처리완료 모달 */}
      <Modal
        title="처리완료 확인"
        open={closeTarget !== null}
        onOk={handleClose}
        onCancel={() => setCloseTarget(null)}
        okText="처리완료"
        cancelText="취소"
      >
        <Form layout="vertical">
          <Form.Item label="처리 내용" required>
            <Input.TextArea
              rows={4}
              value={processNote}
              onChange={(e) => setProcessNote(e.target.value)}
              placeholder="처리 내용을 입력하세요"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 첨부파일 (마지막 등록 건) */}
      {createdId && (
        <ProCard
          title="첨부파일"
          style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm, marginTop: 16 }}
        >
          <AttachmentUpload refType="COMPLAINT" refId={createdId} />
        </ProCard>
      )}
    </PageContainer>
  );
}
