'use client'
import {useCallback, useEffect, useState} from 'react'
import {PageRecord} from '@/lib/api'
import {Balance} from '@/lib/models'
import {useStatus} from '@/lib/states'
import {Search, Eraser} from 'lucide-react'
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'
import {Input} from '@/components/ui/input'
import {listBalances} from '@/actions/balance'

const filterSchema = zod.object({
  created_at_start: zod.date().optional(),
  created_at_end: zod.date().optional(),
  bill_no: zod.string().optional(),
})
type FilterSchema = zod.infer<typeof filterSchema>

export type BalancePageProps = {}

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

  const form = useForm<FilterSchema>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      bill_no: '',
      created_at_start: undefined,
      created_at_end: undefined,
    },
  })

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

  const refresh = useCallback(async (page: number, size: number) => {
    setStatus('load')
    try {
      const created_at_start = form.getValues('created_at_start')
      const created_at_end = form.getValues('created_at_end')
      const bill_no = form.getValues('bill_no')

      const res = await listBalances({
        page, size,
        created_at_start,
        created_at_end,
        bill_no: bill_no || undefined,
      })

      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">
        <Form form={form} handler={form.handleSubmit(onSubmit)} className="flex-auto flex flex-wrap gap-4 items-end">
          <FormField name="bill_no" label={<span className="text-sm">账单编号</span>}>
            {({id, field}) => {
              return <Input {...field} id={id} className="h-9"/>
            }}
          </FormField>
          <div className="flex flex-col gap-2">
            <Label className="text-sm">创建时间</Label>
            <div className="flex items-center">
              <FormField name="created_at_start">
                {({field}) => {
                  const dateValue = typeof field.value === 'string' && field.value ? new Date(field.value) : undefined
                  return (
                    <DatePicker
                      placeholder="选择开始时间"
                      {...field}
                      format="yyyy-MM-dd"
                    />
                  )
                }
                }
              </FormField>
              <span className="px-1">-</span>
              <FormField name="created_at_end">
                {({field}) => (
                  <DatePicker
                    placeholder="选择结束时间"
                    {...field}
                    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()
              refresh(1, data.size)
            }}
          >
            <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: `账单编号`,
            accessorFn: row => row.bill?.bill_no || '',
          },
          {
            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 = row.original.amount
              const isPositive = Number(amount) > 0
              return (
                <div className="flex items-center gap-1">
                  <span
                    className={`font-semibold ${
                      isPositive ? 'text-green-600' : 'text-red-600'
                    }`}
                  >
                    {isPositive ? '+' : ''}
                    {Number(amount).toFixed(2)}
                  </span>
                </div>
              )
            },
          },
          {
            header: '余额变化',
            accessorKey: 'balance_prev',
            cell: ({row}) => (
              <div className="flex items-center gap-2">
                <span className="text-gray-500 text-sm">¥{Number(row.original.balance_prev).toFixed(2)}</span>
                <span className="text-muted-foreground">→</span>
                <span>¥{Number(row.original.balance_curr).toFixed(2)}</span>
              </div>
            ),
          },
          {
            header: '备注',
            accessorKey: 'remark',
          },
          {
            header: '创建时间',
            accessorKey: 'created_at',
            cell: ({row}) =>
              format(new Date(row.original.created_at), 'yyyy-MM-dd HH:mm'),
          },
        ]}
      />
    </Page>
  )
}
