import { useMemo, useState } from 'react'
import Modal from '../../components/DraggableModal'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import dayjs, { type Dayjs } from 'dayjs'
import {
  Button,
  Card,
  Checkbox,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  Space,
  Tabs,
  Tooltip,
  message } from 'antd'
import CareTable from '../../components/CareTable'
import {
  CloseOutlined, DownloadOutlined, EditOutlined, MailOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { resourceApi } from '../../api/resources'

const { RangePicker } = DatePicker
const tabs = [
  ['ALL', '전체'],
  ['정산차감', '정산차감'],
  ['유심차감', '유심차감'],
  ['홈상품차감', '홈상품차감'],
  ['정산추가', '정산추가'],
] as const
const gubunOptions = ['정산차감', '유심차감', '홈상품차감', '정산추가']
const searchTypes = ['개통번호(뒷4자리)', '고객명', '사유', '출고처']
const options = (values: string[]) => values.map((value) => ({ value, label: value }))
const isDeduct = (gubun?: string) => Boolean(gubun && gubun.includes('차감'))

type BalanceRow = Record<string, unknown> & { id: number; gubun?: string; amount?: number; memo?: string }
type BalanceSearch = { total: number; list: BalanceRow[]; counts: Record<string, number> }

const initial = {
  page: 0,
  size: 15,
  tab: 'ALL',
  dateBasis: '정산일기준',
  searchType: '개통번호(뒷4자리)' } as Record<string, unknown>

export default function OpenBalancePage() {
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const clientQuery = useQueryClient()
  const [filters, setFilters] = useState<Record<string, unknown>>(initial)
  const [editing, setEditing] = useState<BalanceRow | null>(null)
  const [creating, setCreating] = useState(false)
  const [amountSign, setAmountSign] = useState<'+' | '-'>('+')

  const companies = useQuery({ queryKey: ['balance-companies'], queryFn: () => resourceApi.list('companies', { size: 200 }) })
  const inOptions = useMemo(
    () => (companies.data?.items ?? []).filter((c) => String(c.type) === 'IN').map((c) => ({ value: c.id, label: String(c.name) })),
    [companies.data],
  )

  const query = useQuery({
    queryKey: ['balance-search', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<BalanceSearch>>(`${apiPrefix()}/balances/search`, { params: filters })
      return unwrap(data)
    } })

  const refresh = () => clientQuery.invalidateQueries({ queryKey: ['balance-search'] })

  const save = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const raw = Number(values.amountAbs ?? 0)
      const signed = amountSign === '-' ? -Math.abs(raw) : Math.abs(raw)
      const payload: Record<string, unknown> = {
        ...values,
        amount: signed,
        basedate: values.basedate ? dayjs(values.basedate as Dayjs).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        opendate: values.opendate ? dayjs(values.opendate as Dayjs).format('YYYY-MM-DD') : undefined }
      delete payload.amountAbs
      if (editing) {
        const { data } = await client.put(`${apiPrefix()}/balances/${editing.id}`, payload)
        return unwrap(data as ApiResponse)
      }
      const { data } = await client.post(`${apiPrefix()}/balances`, payload)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success(editing ? '수정했습니다.' : '후정산을 등록했습니다.')
      setCreating(false)
      setEditing(null)
      editForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message || '저장에 실패했습니다.') })

  const setPreset = (from: Dayjs, to: Dayjs) => form.setFieldsValue({ dates: [from, to] })

  const onSearch = (values: Record<string, unknown>) => {
    const dates = values.dates as [Dayjs, Dayjs] | undefined
    setFilters({
      ...initial,
      ...values,
      dateFrom: dates?.[0]?.format('YYYY-MM-DD'),
      dateTo: dates?.[1]?.format('YYYY-MM-DD'),
      page: 0,
      size: values.size ?? filters.size ?? 15,
      tab: filters.tab })
  }

  const reset = () => {
    form.resetFields()
    form.setFieldsValue({ dateBasis: '정산일기준', searchType: '개통번호(뒷4자리)', size: 15 })
    setFilters(initial)
  }

  const openCreate = () => {
    setEditing(null)
    setCreating(true)
    setAmountSign('+')
    editForm.setFieldsValue({
      gubun: '정산차감',
      basedate: dayjs(),
      amountAbs: undefined,
      outcompanyName: undefined,
      reason: undefined,
      memo: undefined,
      incompanyId: undefined })
  }

  const openEdit = (row: BalanceRow) => {
    setCreating(false)
    setEditing(row)
    const amount = Number(row.amount ?? 0)
    setAmountSign(amount < 0 ? '-' : '+')
    editForm.setFieldsValue({
      ...row,
      amountAbs: Math.abs(amount),
      basedate: row.basedate ? dayjs(String(row.basedate)) : dayjs(),
      opendate: row.opendate ? dayjs(String(row.opendate)) : undefined })
  }

  const download = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/balances/export`, { params: filters, responseType: 'blob' })
      const url = URL.createObjectURL(data)
      const a = document.createElement('a')
      a.href = url
      a.download = '개통후정산.csv'
      a.click()
      URL.revokeObjectURL(url)
    } catch {
      message.error('엑셀 다운로드에 실패했습니다.')
    }
  }

  const columns = [
    { title: <Checkbox />, width: 42, render: () => <Checkbox /> },
    { title: '개통일', dataIndex: 'opendate', width: 100, render: (v: string) => v || '-' },
    { title: '출고처', dataIndex: 'outcompanyName', width: 120, ellipsis: true },
    { title: '고객명', dataIndex: 'customerName', width: 90, render: (v: string) => v || '-' },
    { title: '개통번호', dataIndex: 'openphone', width: 120, render: (v: string) => v || '-' },
    {
      title: '구분',
      dataIndex: 'gubun',
      width: 100,
      render: (v: string) => <span className={isDeduct(v) ? 'balance-deduct' : ''}>{v}</span> },
    { title: '기준일', dataIndex: 'basedate', width: 100 },
    { title: '사유', dataIndex: 'reason', width: 140, ellipsis: true },
    {
      title: '정산금액',
      dataIndex: 'amount',
      width: 110,
      align: 'right' as const,
      render: (v: unknown, row: BalanceRow) => {
        if (v == null || v === '') return '-'
        const n = Number(v)
        const cls = isDeduct(row.gubun) || n < 0 ? 'balance-amount-deduct' : 'balance-amount'
        return <span className={cls}>{n.toLocaleString()}</span>
      } },
    {
      title: '비고',
      dataIndex: 'memo',
      width: 54,
      align: 'center' as const,
      render: (v: string) => (v ? <Tooltip title={v}><MailOutlined className="memo-icon" /></Tooltip> : '-') },
    {
      title: '관리',
      width: 58,
      fixed: 'right' as const,
      render: (_: unknown, row: BalanceRow) => (
        <Button size="small" type="text" icon={<EditOutlined style={{ color: '#1677ff' }} />} onClick={() => openEdit(row)} />
      ) },
  ]

  const modalOpen = creating || Boolean(editing)

  return (
    <div className="stock-page balance-page">
      <div className="stock-title">
        <div>
          <h2>개통후정산</h2>
          <p>등록된 개통정산 외 추가로 후정산을 등록 및 관리하실 수 있습니다.</p>
        </div>
        <Button type="primary" icon={<EditOutlined />} onClick={openCreate}>후정산등록</Button>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form
          form={form}
          layout="inline"
          className="balance-filter"
          initialValues={{ dateBasis: '정산일기준', searchType: '개통번호(뒷4자리)', size: 15 }}
          onFinish={onSearch}
        >
          <div className="stock-filter-row">
            <Form.Item name="dateBasis">
              <Select className="w-120" options={options(['정산일기준', '개통일기준'])} />
            </Form.Item>
            <Form.Item name="dates">
              <RangePicker className="w-230" placeholder={['YYYY-MM-DD', 'YYYY-MM-DD']} />
            </Form.Item>
            <Space.Compact className="sheet-presets">
              <Button onClick={() => setPreset(dayjs(), dayjs())}>오늘</Button>
              <Button onClick={() => setPreset(dayjs().subtract(6, 'day'), dayjs())}>1주일</Button>
              <Button onClick={() => setPreset(dayjs().startOf('month'), dayjs().endOf('month'))}>당월</Button>
              <Button onClick={() => setPreset(dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month'))}>전월</Button>
              <Button onClick={() => setPreset(dayjs().subtract(2, 'month').startOf('month'), dayjs().subtract(2, 'month').endOf('month'))}>전전월</Button>
            </Space.Compact>
            <Button className="sheet-clear" icon={<CloseOutlined />} onClick={() => form.setFieldValue('dates', undefined)} />
          </div>
          <div className="stock-filter-row">
            <Form.Item name="telecom">
              <Select allowClear placeholder="-통신사-" className="w-110" options={options(['SKT', 'KT', 'LGU+'])} />
            </Form.Item>
            <Form.Item name="incompanyId">
              <Select allowClear placeholder="-입고처-" className="w-150" options={inOptions} />
            </Form.Item>
            <Form.Item name="outCategory">
              <Select allowClear placeholder="-출고분류-" className="w-120" options={options(['판매점', '도매'])} />
            </Form.Item>
            <Form.Item name="outcompanyName">
              <Input placeholder="출고처" className="w-130" allowClear />
            </Form.Item>
            <Form.Item name="searchType">
              <Select className="w-150" options={searchTypes.map((v) => ({ value: v, label: v }))} />
            </Form.Item>
            <Form.Item name="keyword">
              <Input className="w-130" allowClear />
            </Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
            <Button icon={<ReloadOutlined />} onClick={reset}>초기화</Button>
            <Form.Item name="size" className="sheet-size">
              <Select
                className="w-150"
                options={[15, 30, 50, 100].map((n) => ({ value: n, label: `목록 ${n}개씩 보기` }))}
                onChange={(size) => {
                  form.setFieldValue('size', size)
                  setFilters((v) => ({ ...v, size, page: 0 }))
                }}
              />
            </Form.Item>
          </div>
        </Form>
      </Card>

      <Card className="stock-table-card" size="small">
        <div className="stock-table-actions">
          <Tabs
            activeKey={String(filters.tab)}
            onChange={(tab) => setFilters((v) => ({ ...v, tab, page: 0 }))}
            items={tabs.map(([key, label]) => ({
              key,
              label: `${label} ${query.data?.counts?.[key] ?? 0}` }))}
          />
          <Button type="link" icon={<DownloadOutlined />} onClick={download}>엑셀다운로드</Button>
        </div>
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          scroll={{ x: 1200 }}
          pagination={{
            current: Number(filters.page) + 1,
            pageSize: Number(filters.size),
            total: query.data?.total,
            showSizeChanger: false,
            showTotal: (total) => `총 ${total}건`,
            onChange: (page) => setFilters((v) => ({ ...v, page: page - 1 })) }}
        />
      </Card>

      <Modal
        title={editing ? '개통후정산 수정' : '개통후정산 등록'}
        open={modalOpen}
        onCancel={() => { setCreating(false); setEditing(null) }}
        footer={null}
        destroyOnHidden
        width={520}
        className="balance-modal"
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ flex: '110px' }}
          wrapperCol={{ flex: 1 }}
          onFinish={(values) => save.mutate(values)}
          className="balance-edit-form"
        >
          <Form.Item name="outcompanyName" label="출고처" rules={[{ required: true, message: '출고처를 입력하세요' }]}>
            <Input placeholder="출고처명을 입력해주세요." />
          </Form.Item>
          <Form.Item name="basedate" label="후정산일" rules={[{ required: true, message: '후정산일을 선택하세요' }]}>
            <DatePicker className="full-width" />
          </Form.Item>
          <Form.Item name="gubun" label="구분" rules={[{ required: true }]}>
            <Radio.Group options={gubunOptions.map((v) => ({ value: v, label: v }))} />
          </Form.Item>
          <Form.Item label="정산금액" required>
            <Space.Compact className="balance-amount-input">
              <Button onClick={() => setAmountSign((s) => (s === '+' ? '-' : '+'))}>{amountSign}</Button>
              <Form.Item name="amountAbs" noStyle rules={[{ required: true, message: '정산금액을 입력하세요' }]}>
                <InputNumber controls={false} min={0} className="full-width" />
              </Form.Item>
              <Button disabled>원</Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item name="reason" label="사유" rules={[{ required: true, message: '사유를 입력하세요' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="memo" label="비고">
            <Input.TextArea rows={3} />
          </Form.Item>
          <Form.Item name="incompanyId" label="입고처 (옵션)">
            <Select allowClear placeholder="- 선택 -" options={inOptions} />
          </Form.Item>
          <Form.Item name="customerName" label="고객명"><Input placeholder="선택" /></Form.Item>
          <Form.Item name="openphone" label="개통번호"><Input placeholder="010-****-0000" /></Form.Item>
          <Form.Item name="opendate" label="개통일"><DatePicker className="full-width" /></Form.Item>
          <Form.Item name="telecom" label="통신사">
            <Select allowClear placeholder="- 선택 -" options={options(['SKT', 'KT', 'LGU+'])} />
          </Form.Item>
          <div className="balance-modal-footer">
            <Button type="primary" htmlType="submit" loading={save.isPending} icon={<PlusOutlined />}>
              {editing ? '수정합니다' : '등록'}
            </Button>
            <Button onClick={() => { setCreating(false); setEditing(null) }}>취소</Button>
          </div>
        </Form>
      </Modal>
    </div>
  )
}
