import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import dayjs, { type Dayjs } from 'dayjs'
import { Button, Card, Empty } from 'antd'
import CareTable from '../../components/CareTable'
import { BarChartOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { money } from './homesShared'

type DailyContract = {
  id: number
  status?: string
  customerName?: string
  phone?: string
  products?: string
  employee?: string
  agency?: string
  settleAmount?: number
  margin?: number
}

type DailyPending = {
  id: number
  status?: string
  pendingType?: string
  contents?: string
  customerName?: string
  phone?: string
  employee?: string
}

type DailyBooking = {
  id: number
  status?: string
  customerName?: string
  phone?: string
  products?: string
  internetProducts?: string
  rentalProducts?: string
  employee?: string
}

type DailyReport = {
  date?: string
  title?: string
  summary?: {
    internetCount?: number
    homeCount?: number
    pendingCount?: number
    bookingCount?: number
  }
  internet?: DailyContract[]
  home?: DailyContract[]
  pendings?: DailyPending[]
  bookings?: DailyBooking[]
}

const maskName = (name?: string) => {
  if (!name) return '-'
  if (name.length <= 1) return name
  if (name.length === 2) return `${name[0]}*`
  return `${name[0]}*${name.slice(2)}`
}

const countLabel = (n?: number) => (n && n > 0 ? String(n) : '-')

export default function ReportDailyPage() {
  const [date, setDate] = useState<Dayjs>(dayjs())

  const query = useQuery({
    queryKey: ['homes-report-daily', date.format('YYYY-MM-DD')],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<DailyReport>>(`${apiPrefix()}/homes/reports/daily`, {
        params: { date: date.format('YYYY-MM-DD') } })
      return unwrap(data)
    } })

  const summary = query.data?.summary
  const internet = query.data?.internet || []
  const home = query.data?.home || []
  const pendings = query.data?.pendings || []
  const bookings = query.data?.bookings || []

  const contractColumns = useMemo(() => [
    { title: '상태', dataIndex: 'status', width: 80 },
    { title: '고객명', dataIndex: 'customerName', width: 100, render: (v: string) => maskName(v) },
    { title: '상품', dataIndex: 'products', ellipsis: true },
    { title: '거래처', dataIndex: 'agency', width: 120, render: (v: string) => v || '-' },
    { title: '직원', dataIndex: 'employee', width: 90 },
    { title: '정산금액', dataIndex: 'settleAmount', width: 110, align: 'right' as const, render: money },
  ], [])

  const pendingColumns = useMemo(() => [
    { title: '상태', dataIndex: 'status', width: 80 },
    { title: '과목', dataIndex: 'pendingType', width: 90 },
    { title: '고객명', dataIndex: 'customerName', width: 100, render: (v: string) => maskName(v) },
    { title: '내용', dataIndex: 'contents', ellipsis: true },
    { title: '접수직원', dataIndex: 'employee', width: 100 },
  ], [])

  const bookingColumns = useMemo(() => [
    { title: '상태', dataIndex: 'status', width: 80 },
    { title: '고객명', dataIndex: 'customerName', width: 100, render: (v: string) => maskName(v) },
    {
      title: '상품',
      key: 'products',
      ellipsis: true,
      render: (_: unknown, row: DailyBooking) =>
        [row.internetProducts, row.rentalProducts, row.products].filter(Boolean).join(' / ') || '-' },
    { title: '접수직원', dataIndex: 'employee', width: 100 },
  ], [])

  const renderSection = (
    title: string,
    rows: { id: number }[],
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    columns: any[],
  ) => (
    <Card className="daily-report-section" size="small" title={title}>
      {rows.length ? (
        <CareTable
          rowKey="id"
          size="small"
          pagination={false}
          dataSource={rows}
          columns={columns}
          scroll={{ x: 700 }}
        />
      ) : (
        <Empty className="daily-report-empty" image={Empty.PRESENTED_IMAGE_SIMPLE} description="자료가 없습니다." />
      )}
    </Card>
  )

  return (
    <div className="stock-page daily-report-page">
      <div className="stock-title">
        <div>
          <h2>
            <BarChartOutlined className="product-title-icon daily-report-icon" />
            일일리포트
          </h2>
          <p>원하시는 날짜의 일일리포트를 확인하실 수 있습니다.</p>
        </div>
      </div>

      <Card className="daily-report-date-card" size="small">
        <div className="daily-report-date-nav">
          <Button type="text" icon={<LeftOutlined />} onClick={() => setDate((d) => d.subtract(1, 'day'))} />
          <span className="daily-report-date-label">{date.format('YYYY년 M월 D일')}</span>
          <Button type="text" icon={<RightOutlined />} onClick={() => setDate((d) => d.add(1, 'day'))} />
        </div>
      </Card>

      <Card className="daily-report-summary-card" size="small" title="집계" loading={query.isLoading}>
        <div className="daily-report-summary-grid">
          <div className="daily-report-summary-item">
            <div className="label">인터넷접수</div>
            <div className="value">{countLabel(summary?.internetCount)}</div>
          </div>
          <div className="daily-report-summary-item">
            <div className="label">홈렌탈접수</div>
            <div className="value">{countLabel(summary?.homeCount)}</div>
          </div>
          <div className="daily-report-summary-item">
            <div className="label">일정관리</div>
            <div className="value">{countLabel(summary?.pendingCount)}</div>
          </div>
          <div className="daily-report-summary-item">
            <div className="label">예약관리</div>
            <div className="value">{countLabel(summary?.bookingCount)}</div>
          </div>
        </div>
      </Card>

      {renderSection('인터넷접수', internet, contractColumns)}
      {renderSection('홈렌탈접수', home, contractColumns)}
      {renderSection('일정관리', pendings, pendingColumns)}
      {renderSection('예약관리', bookings, bookingColumns)}
    </div>
  )
}
