import { useState } from 'react';
import { Alert, Col, Form, Input, InputNumber, Modal, Row, Space, Statistic, Tabs, 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 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 { operationApi, HqSettleRow } from '@/api/operation';
import { GRAY, RADIUS, SHADOW, COLOR_SUCCESS, COLOR_ERROR } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

const COLS: ColDef<HqSettleRow>[] = [
  { field: 'settleMonth', headerName: '정산월',   width: 110 },
  { field: 'itemType',    headerName: '항목유형', width: 100,
    valueFormatter: (p) => p.value === 'INCOME' ? '수입' : '비용' },
  { field: 'itemName',    headerName: '항목명',   flex: 1 },
  { field: 'amount',      headerName: '금액',     width: 160, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'memo',        headerName: '메모',     flex: 1 },
  { field: 'status',      headerName: '상태',     width: 100 },
];

export default function HqSettle() {
  const qc = useQueryClient();
  const [settleMonth, setSettleMonth] = useState(dayjs().format('YYYYMM'));
  const [modalOpen, setModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<HqSettleRow | null>(null);
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['hq-settle', 'list', settleMonth],
    queryFn: () => operationApi.hqSettleList({ settleMonth }),
    retry: false,
  });

  const { data: summary } = useQuery({
    queryKey: ['hq-settle', 'summary', settleMonth],
    queryFn: () => operationApi.hqSettleSummary(settleMonth),
    retry: false,
    enabled: !!settleMonth,
  });

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

  const openCreate = () => { setEditingItem(null); form.resetFields(); setModalOpen(true); };
  const openEdit = (row: HqSettleRow) => { setEditingItem(row); form.setFieldsValue(row); setModalOpen(true); };

  const handleSave = async () => {
    const values = await form.validateFields();
    try {
      if (editingItem) {
        await operationApi.hqSettleUpdate(editingItem.itemId, values);
        message.success('수정 완료');
      } else {
        await operationApi.hqSettleCreate(values);
        message.success('등록 완료');
      }
      qc.invalidateQueries({ queryKey: ['hq-settle'] });
      setModalOpen(false);
    } catch { /* request.ts 처리 */ }
  };

  const handleDelete = (id: number) => Modal.confirm({
    title: '항목 삭제',
    content: '삭제하시겠습니까?',
    onOk: async () => {
      await operationApi.hqSettleDelete(id);
      message.success('삭제 완료');
      qc.invalidateQueries({ queryKey: ['hq-settle'] });
    },
  });

  const actionCol: ColDef<HqSettleRow> = {
    headerName: '액션',
    width: 160,
    pinned: 'right',
    cellRenderer: (p: { data: HqSettleRow }) => (
      <Space>
        <PermissionButton menuCode="HQ_SETTLE" permCode="UPDATE" size="small" onClick={() => openEdit(p.data)}>수정</PermissionButton>
        <PermissionButton menuCode="HQ_SETTLE" permCode="DELETE" size="small" danger onClick={() => handleDelete(p.data.itemId)}>삭제</PermissionButton>
      </Space>
    ),
  };

  return (
    <PageContainer title="본사정산" description="GA 본사 수입/비용 정산 항목 관리">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/hq-settles 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'month', name: 'settleMonth', label: '정산월', span: 6 },
        ]}
        initialValues={{ settleMonth: dayjs() }}
        onSearch={(v) => setSettleMonth(v.settleMonth as string ?? dayjs().format('YYYYMM'))}
        onReset={() => setSettleMonth(dayjs().format('YYYYMM'))}
      />

      {/* 손익 요약 카드 */}
      {summary && (
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <ProCard style={cardStyle}>
              <Statistic title="총 수입" value={summary.incomeTotal} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_SUCCESS }} />
            </ProCard>
          </Col>
          <Col span={8}>
            <ProCard style={cardStyle}>
              <Statistic title="총 비용" value={summary.expenseTotal} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_ERROR }} />
            </ProCard>
          </Col>
          <Col span={8}>
            <ProCard style={cardStyle}>
              <Statistic
                title="손익"
                value={summary.profitLoss}
                formatter={(v) => (v as number).toLocaleString()}
                suffix="원"
                valueStyle={{ color: summary.profitLoss >= 0 ? COLOR_SUCCESS : COLOR_ERROR }}
              />
            </ProCard>
          </Col>
        </Row>
      )}

      <Tabs
        defaultActiveKey="items"
        items={[
          {
            key: 'items',
            label: '정산 항목',
            children: (
              <ProCard style={cardStyle}>
                <div style={{ marginBottom: 12 }}>
                  <PermissionButton menuCode="HQ_SETTLE" permCode="CREATE" type="primary" onClick={openCreate}>
                    + 항목 등록
                  </PermissionButton>
                </div>
                <DataGrid<HqSettleRow>
                  rows={rows}
                  columns={[...COLS, actionCol]}
                  loading={isLoading}
                  height={520}
                  rowKey="itemId"
                  pinnedBottomRow={rows.length > 0 ? {
                    itemName: '합계',
                    amount: rows.reduce((s, r) => s + (r.amount ?? 0), 0),
                  } as Partial<HqSettleRow> : undefined}
                />
              </ProCard>
            ),
          },
        ]}
      />

      <Modal
        title={editingItem ? '항목 수정' : '항목 등록'}
        open={modalOpen}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        okText="저장"
        cancelText="취소"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="settleMonth" label="정산월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="202506" />
          </Form.Item>
          <Form.Item name="itemType" label="항목유형" rules={[{ required: true }]}>
            <Input placeholder="INCOME / EXPENSE" />
          </Form.Item>
          <Form.Item name="itemName" label="항목명" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="amount" label="금액" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
          <Form.Item name="memo" label="메모">
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
