import { useState, useCallback } from 'react';
import { Alert, Form, Input, Modal, Space, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef, SelectionChangedEvent } from '@ag-grid-community/core';
import dayjs from 'dayjs';
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 {
  retentionAnomalyApi,
  RetentionAnomalyResp,
  RetentionAnomalySearchParam,
} from '@/api/retention-anomaly';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const rate = (v: unknown) => (v == null ? '-' : `${((v as number) * 100).toFixed(2)}%`);

const COLUMNS: ColDef<RetentionAnomalyResp>[] = [
  { field: 'alertMonth',     headerName: '발생월',   width: 110, pinned: 'left' },
  { field: 'targetTypeName', headerName: '대상구분', width: 100 },
  { field: 'targetName',     headerName: '대상',     width: 150 },
  { field: 'retentionBand',  headerName: '유지율밴드', width: 100 },
  { field: 'expectedRate',   headerName: '기대유지율', flex: 1, type: 'numericColumn', valueFormatter: (p) => rate(p.value) },
  { field: 'actualRate',     headerName: '실제유지율', flex: 1, type: 'numericColumn', valueFormatter: (p) => rate(p.value) },
  { field: 'deviation',      headerName: '편차',     flex: 1, type: 'numericColumn', valueFormatter: (p) => rate(p.value) },
  { field: 'severityName',   headerName: '심각도',   width: 90 },
  { field: 'statusName',     headerName: '상태',     width: 90 },
  { field: 'note',           headerName: '비고',     flex: 1 },
  { field: 'detectedAt',     headerName: '탐지일시', width: 150 },
];

const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

export default function RetentionAnomalyList() {
  const qc = useQueryClient();
  const lastMonth = dayjs().subtract(1, 'month').format('YYYY-MM');
  const [params, setParams] = useState<RetentionAnomalySearchParam>({ pageSize: 200 });
  const [selectedRows, setSelectedRows] = useState<RetentionAnomalyResp[]>([]);
  const [detectOpen, setDetectOpen] = useState(false);
  const [reviewOpen, setReviewOpen] = useState(false);
  const [detectForm] = Form.useForm();
  const [reviewForm] = Form.useForm();

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

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

  const handleSelectionChanged = useCallback((e: SelectionChangedEvent<RetentionAnomalyResp>) => {
    setSelectedRows(e.api.getSelectedRows());
  }, []);

  const handleDetect = async () => {
    const values = await detectForm.validateFields();
    try {
      const affected = await retentionAnomalyApi.detect(values.alertMonth);
      message.success(`이상치 재탐지 완료 (${affected}건)`);
      qc.invalidateQueries({ queryKey: ['retention-anomalies'] });
      setDetectOpen(false);
      detectForm.resetFields();
    } catch { /* request.ts 처리 */ }
  };

  const handleReview = async () => {
    const values = await reviewForm.validateFields();
    try {
      await retentionAnomalyApi.review({
        ids: selectedRows.map((r) => r.alertId),
        status: values.status,
        note: values.note,
      });
      message.success('검토 처리 완료');
      qc.invalidateQueries({ queryKey: ['retention-anomalies'] });
      setReviewOpen(false);
      reviewForm.resetFields();
      setSelectedRows([]);
    } catch { /* request.ts 처리 */ }
  };

  return (
    <PageContainer
      title="유지율 이상치"
      description="13M/25M 유지율 이상 탐지 및 검토 관리"
      extra={
        <Space>
          <PermissionButton menuCode="RETENTION_ANOMALY" permCode="UPDATE"
            onClick={() => setDetectOpen(true)}>
            재탐지
          </PermissionButton>
          <PermissionButton menuCode="RETENTION_ANOMALY" permCode="UPDATE"
            type="primary" disabled={selectedRows.length === 0} onClick={() => setReviewOpen(true)}>
            검토 처리 ({selectedRows.length}건)
          </PermissionButton>
        </Space>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답"
          description="/api/retention-anomalies 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'alertMonth',    label: '발생월(YYYY-MM)', span: 7 },
          { type: 'text', name: 'retentionBand', label: '밴드(13M/25M)', span: 6 },
          { type: 'text', name: 'severity',      label: '심각도(LOW/MED/HIGH)', span: 7 },
          { type: 'text', name: 'status',        label: '상태(NEW/REVIEWED/RESOLVED)', span: 8 },
        ]}
        onSearch={(v) => setParams({ ...v as RetentionAnomalySearchParam, pageSize: 200 })}
        onReset={() => setParams({ pageSize: 200 })}
      />

      <ProCard style={cardStyle}>
        <DataGrid<RetentionAnomalyResp>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={520}
          rowKey="alertId"
          rowSelection="multiple"
          onSelectionChanged={handleSelectionChanged}
        />
      </ProCard>

      {/* 재탐지 */}
      <Modal
        title="유지율 이상치 재탐지"
        open={detectOpen}
        onOk={handleDetect}
        onCancel={() => { setDetectOpen(false); detectForm.resetFields(); }}
        okText="재탐지"
        cancelText="취소"
      >
        <Form form={detectForm} layout="vertical" initialValues={{ alertMonth: lastMonth }} style={{ marginTop: 16 }}>
          <Form.Item name="alertMonth" label="탐지 대상월"
            rules={[{ required: true, message: '대상월을 입력하세요 (YYYY-MM)' }]}>
            <Input placeholder="예: 2025-04" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 검토 처리 */}
      <Modal
        title="이상치 검토 처리"
        open={reviewOpen}
        onOk={handleReview}
        onCancel={() => { setReviewOpen(false); reviewForm.resetFields(); }}
        okText="처리"
        cancelText="취소"
      >
        <p>선택한 {selectedRows.length}건의 이상치를 처리합니다.</p>
        <Form form={reviewForm} layout="vertical" initialValues={{ status: 'REVIEWED' }} style={{ marginTop: 16 }}>
          <Form.Item name="status" label="처리 상태"
            rules={[{ required: true, message: '상태를 선택하세요' }]}>
            <Input placeholder="REVIEWED / RESOLVED" />
          </Form.Item>
          <Form.Item name="note" label="검토 비고">
            <Input.TextArea rows={3} placeholder="검토 내용" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
