'use client'
import {useCallback, useEffect, useState} from 'react'
import {PageRecord} from '@/lib/api'
import {Bill} from '@/lib/models'
import {useStatus} from '@/lib/states'
import {listBills} from '@/actions/bill'
import {Search, Eraser, CreditCard} from 'lucide-react'
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from '@/components/ui/select'
import {Button} from '@/components/ui/button'
import DataTable from '@/components/data-table'
import {format} from 'date-fns'
import DatePicker from '@/components/date-picker'
import {Form, FormField} from '@/components/ui/form'
import {useForm} from 'react-hook-form'
import zod from 'zod'
import {zodResolver} from '@hookform/resolvers/zod'
import {Label} from '@/components/ui/label'
import Page from '@/components/page'
import {CheckCircle, AlertCircle} from 'lucide-react'

const filterSchema = zod.object({
  type: zod.enum(['all', '3', '1', '2']).default('all'),
  create_after: zod.date().optional(),
  create_before: zod.date().optional(),
  trade_id: zod.string().optional(),
})

type FilterSchema = zod.infer<typeof filterSchema>

export type BillsPageProps = {}

export default function BillsPage(props: BillsPageProps) {
  const [status, setStatus] = useStatus()
  const [data, setData] = useState<PageRecord<Bill>>({
    page: 1,
    size: 10,
    total: 0,
    list: [],
  })

  const form = useForm<FilterSchema>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      type: 'all',
      trade_id: '',
      create_after: undefined,
      create_before: undefined,
    },
  })

  const onSubmit = async (value: FilterSchema) => {
    console.log(value)
    await refresh(1, data.size)
  }

  const refresh = useCallback(async (page: number, size: number) => {
    setStatus('load')
    try {
      const typeValue = form.getValues('type')
      const type = typeValue === 'all' ? undefined : parseInt(typeValue)
      const create_after = form.getValues('create_after')
      const create_before = form.getValues('create_before')
      const trade_id = form.getValues('trade_id')

      const res = await listBills({
        page, size, type, create_after, create_before, trade_id,
      })
      console.log(res, 'res')

      if (res.success) {
        setData(res.data)
        setStatus('done')
      }
      else {
        throw new Error('Failed to load bills')
      }
    }
    catch (e) {
      setStatus('fail')
    }
  }, [form, setStatus])

  useEffect(() => {
    refresh(1, 10).then()
  }, [refresh])

  return (
    <Page>
      <section className="flex justify-between flex-wrap">
        <div>
        </div>

        <Form form={form} onSubmit={onSubmit} className="flex items-end gap-4 flex-wrap">
          <FormField name="type" label={<span className="text-sm">账单类型</span>}>
            {({id, field}) => (
              <Select value={field.value} onValueChange={field.onChange}>
                <SelectTrigger className="w-24 h-9">
                  <SelectValue placeholder="选择类型"/>
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="3">充值</SelectItem>
                  <SelectItem value="1">消费</SelectItem>
                  <SelectItem value="2">退款</SelectItem>
                </SelectContent>
              </Select>
            )}
          </FormField>
          <div className="flex flex-col gap-2">
            <Label className="text-sm">创建时间</Label>
            <div className="flex items-center">
              <FormField name="create_after">
                {({field}) => (
                  <DatePicker
                    {...field}
                    className="w-36"
                    placeholder="开始时间"
                    format="yyyy-MM-dd"
                  />
                )}
              </FormField>
              <span className="px-1">-</span>
              <FormField name="create_before">
                {({field}) => (
                  <DatePicker
                    {...field}
                    className="w-36"
                    placeholder="结束时间"
                    format="yyyy-MM-dd"
                  />
                )}
              </FormField>
            </div>
          </div>
          <Button className="h-9" type="submit">
            <Search/>
            <span>筛选</span>
          </Button>
          <Button theme="outline" className="h-9" type="button" onClick={() => form.reset()}>
            <Eraser/>
            <span>重置</span>
          </Button>
        </Form>
      </section>

      <DataTable
        data={data.list}
        status={status}
        pagination={{
          total: data.total,
          page: data.page,
          size: data.size,
          onPageChange: async (page: number) => {
            await refresh(page, data.size)
          },
          onSizeChange: async (size: number) => {
            await refresh(data.page, size)
          },
        }}
        columns={[
          {
            accessorKey: 'bill_no', header: `账单编号`,
          },
          {
            accessorKey: 'info',
            header: `账单详情`,
            cell: ({row}) => {
              const bill = row.original
              return (
                <div className="flex items-center gap-2">
                  {/* 类型展示 */}
                  <div className="shrink-0">
                    {bill.type === 1 && (
                      <div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
                        <CreditCard size={16}/>
                        <span>消费</span>
                      </div>
                    )}
                    {bill.type === 2 && (
                      <div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
                        <CreditCard size={16}/>
                        <span>退款</span>
                      </div>
                    )}
                    {bill.type === 3 && (
                      <div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
                        <CreditCard size={16}/>
                        <span>充值</span>
                      </div>
                    )}
                  </div>

                  {/* 账单详情 */}
                  <div className="text-sm">
                    {bill.info}
                  </div>
                </div>
              )
            },
          },
          {
            accessorKey: 'status',
            header: `状态`,
            cell: ({row}) => {
              const trade = row.original.trade
              if (![1, 2, 3, 4, 5].includes(trade?.method)) {
                return (
                  <div className="flex items-center gap-2">
                    <CheckCircle size={16} className="text-done"/>
                    <span>已完成</span>
                  </div>
                )
              }
              if (!trade) return <span>-</span>
              return (
                <div className="flex items-center gap-2">
                  {trade?.status === 1 ? (
                    <CheckCircle size={16} className="text-done"/>
                  ) : trade?.status === 2 ? (
                    <AlertCircle size={16} className="text-weak"/>
                  ) : trade?.status === 3 ? (
                    <AlertCircle size={16} className="text-fail"/>
                  ) : null}
                  <span>
                    {trade?.status === 1 ? '已完成'
                      : trade?.status === 2 ? '已取消'
                        : trade?.status === 3 ? '已退款' : '-'}
                  </span>
                </div>
              )
            },
          },
          {
            accessorKey: 'amount',
            header: '支付信息',
            cell: ({row}) => {
              const amount = typeof row.original.amount === 'string'
                ? parseFloat(row.original.amount)
                : row.original.amount || 0
              const trade = row.original.trade
              const paymentMethodMap = {
                1: '支付宝*',
                2: '微信*',
                3: '其他',
                4: '支付宝',
                5: '微信',
              }
              const paymentMethod = trade ? paymentMethodMap[trade.method as keyof typeof paymentMethodMap] || '余额' : '余额'
              return (
                <div className="flex gap-1">
                  <span className="text-sm">
                    {paymentMethod}
                  </span>
                  <span className={amount > 0 ? 'text-green-500' : 'text-orange-500'}>
                    ￥{amount.toFixed(2)}
                  </span>
                </div>
              )
            },
          },
          {
            accessorKey: 'platform',
            header: '支付平台',
            cell: ({row}) => {
              const trade = row.original.trade
              if (!trade) return <span>-</span>
              return (
                <div className="flex items-center gap-2">
                  {trade.platform === 1 ? (
                    <>
                      <span>电脑网站</span>
                    </>
                  ) : trade.platform === 2 ? (
                    <>
                      <span>手机网站</span>
                    </>
                  ) : (
                    <span>-</span>
                  )}
                </div>
              )
            },
          },
          {
            accessorKey: 'created_at', header: '创建时间', cell: ({row}) => (
              format(new Date(row.original.created_at), 'yyyy-MM-dd HH:mm')
            ),
          },
          {
            accessorKey: 'action', header: `操作`, cell: item => (
              <div className="flex gap-2">
                -
              </div>
            ),
          },
        ]}
      />
    </Page>
  )
}
