import type { InferPageProps } from '@adonisjs/inertia/types'
import { OrderStatus, PaymentStatus } from '@baguspay/db/types'
import { DataTable } from '@baguspay/ui/components/data-table'
import { Button } from '@baguspay/ui/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@baguspay/ui/components/ui/dialog'
import { Input } from '@baguspay/ui/components/ui/input'
import { Label } from '@baguspay/ui/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@baguspay/ui/components/ui/select'
import { cn } from '@baguspay/ui/lib/utils'
import { router } from '@inertiajs/react'
import type { ColumnDef } from '@tanstack/react-table'
import { type FormEvent, useState } from 'react'
import type OfferController from '#controllers/offer_controller'
import AdminLayout from '~/components/layout/admin-layout'
import { formatDate, formatPrice } from '~/utils'

type Props = InferPageProps<OfferController, 'getUsedOffers'>

const columns: ColumnDef<Props['usedOffer'][number]>[] = [
  {
    accessorKey: 'id',
    header: 'Id',
  },
  {
    accessorKey: 'user.name',
    header: 'User',
  },
  {
    accessorKey: 'offer.name',
    header: 'Offer',
  },
  {
    accessorKey: 'offer.code',
    header: 'Offer Code',
  },
  {
    accessorKey: 'Product',
    header: 'Product',
    cell: ({ row }) =>
      `${row.original.order?.product_snapshot?.name} - ${row.original.order?.product_snapshot?.category_name}`,
  },
  {
    accessorKey: 'order.discount_price',
    header: 'Fee',
    cell: ({ row }) => formatPrice(row.original.order?.fee || 0),
  },
  {
    accessorKey: 'order.cost_price',
    header: 'Cost Price',
    cell: ({ row }) => formatPrice(row.original.order?.cost_price || 0),
  },
  {
    accessorKey: 'profit',
    header: 'Profit',
    cell: ({ row }) => (
      <span
        className={cn({
          'text-green-500': (row.original.order?.profit ?? 0) >= 0,
          'text-red-500': (row.original.order?.profit ?? 0) < 0,
        })}
      >
        {formatPrice(row.original.order?.profit || 0)}
      </span>
    ),
  },
  {
    accessorKey: 'price_before_discount',
    header: 'Before Discount',
    cell: ({ row }) =>
      formatPrice(
        (row.original.order?.total_price || 0) + (row.original.order?.discount_price || 0),
      ),
  },
  {
    accessorKey: 'order.total_price',
    header: 'Total Price',
    cell: ({ row }) => formatPrice(row.original.order?.total_price || 0),
  },

  {
    accessorKey: 'order.payment_status',
    header: 'Payment Status',
    cell: ({ row }) => {
      let badgeColor = 'text-primary bg-primary'
      const order = row.original.order

      if (!order) {
        return (
          <div className="flex gap-2">
            <span className="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium text-muted-foreground bg-muted">
              N/A
            </span>
          </div>
        )
      }

      switch (order.payment_status) {
        case PaymentStatus.PENDING:
          badgeColor = 'text-yellow-500 bg-yellow-100'
          break
        case PaymentStatus.SUCCESS:
          badgeColor = 'text-green-500 bg-green-100'
          break
        case PaymentStatus.FAILED:
          badgeColor = 'text-red-500 bg-red-100'
          break
        case PaymentStatus.CANCELLED:
          badgeColor = 'text-muted-foreground bg-muted'
          break
        case PaymentStatus.EXPIRED:
          badgeColor = 'text-muted-foreground bg-muted'
          break
      }

      return (
        <div className="flex gap-2">
          <span
            className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${badgeColor}`}
          >
            {row.original.order?.payment_status}
          </span>
        </div>
      )
    },
  },
  {
    accessorKey: 'order.order_status',
    header: 'Order Status',
    cell: ({ row }) => {
      let badgeColor = 'text-primary bg-primary'
      const order = row.original.order

      if (!order) {
        return (
          <div className="flex gap-2">
            <span className="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium text-muted-foreground bg-muted">
              N/A
            </span>
          </div>
        )
      }

      switch (order.order_status) {
        case OrderStatus.PENDING:
          badgeColor = 'text-yellow-500 bg-yellow-100'
          break
        case OrderStatus.COMPLETED:
          badgeColor = 'text-green-500 bg-green-100'
          break
        case OrderStatus.FAILED:
          badgeColor = 'text-red-500 bg-red-100'
          break
        case OrderStatus.CANCELLED:
          badgeColor = 'text-muted-foreground bg-muted'
          break
        case OrderStatus.NONE:
          badgeColor = 'text-muted-foreground bg-muted'
          break
      }

      return (
        <div className="flex gap-2">
          <span
            className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${badgeColor}`}
          >
            {row.original.order?.order_status}
          </span>
        </div>
      )
    },
  },

  {
    accessorKey: 'created_at',
    header: 'Created At',
    cell: ({ row }) => formatDate(row.getValue('created_at')),
  },
]

export default function OrderPrepaidIndex(props: Props) {
  const { usedOffer, pagination, filters } = props
  const [userId, setUserId] = useState(filters.userId || undefined)
  const [sortBy, setSortBy] = useState(filters.sortBy || 'asc')
  const [sortColumn, setSortColumn] = useState(filters.sortColumn || 'created_at')
  const [limit, setLimit] = useState(pagination.limit || 10)

  const [startDate, setStartDate] = useState(filters.startDate || undefined)
  const [endDate, setEndDate] = useState(filters.endDate || undefined)
  const [offerId, setOfferId] = useState(filters.offerId || undefined)

  // For closing dialog after filter
  const [open, setOpen] = useState(false)
  const handleSearch = (e: FormEvent) => {
    e.preventDefault()
    router.get(
      '/adminoffers/history',
      {
        userId: userId && userId !== '' ? userId : undefined,
        startDate: startDate || undefined,
        endDate: endDate || undefined,
        offerId: offerId || undefined,
        page: 1,
        sortBy,
        sortColumn,
        limit,
      },
      {
        onSuccess: () => setOpen(false),
      },
    )
  }

  const handleReset = () => {
    setUserId(undefined)
    setStartDate(undefined)
    setEndDate(undefined)
    setOfferId(undefined)
    setSortBy('desc')
    setSortColumn('created_at')
    setLimit(10)
    router.get(
      '/adminoffers/history',
      { limit: 10, page: 1, sortBy, sortColumn },
      { onSuccess: () => setOpen(false) },
    )
  }

  const handleLimitChange = (v: string) => {
    const newLimit = parseInt(v, 10)
    setLimit(newLimit)
    router.get('/adminoffers/history', {
      ...filters,
      limit: newLimit,
      page: 1,
    })
  }

  const handlePageChange = (page: number) => {
    router.get('/adminoffers/history', { ...filters, page, limit })
  }

  return (
    <AdminLayout>
      <div className="flex justify-between mt-5 mb-2">
        <h1 className="text-2xl font-bold">Offers History</h1>
        <div className="flex items-center gap-2">
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
              <Button variant="outline">Filter</Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Filter Balance Mutations</DialogTitle>
                <DialogDescription>Set filter options for balance mutations.</DialogDescription>
              </DialogHeader>
              <form onSubmit={handleSearch} className="space-y-4">
                <div className="flex flex-col gap-6">
                  {/* Kelompok Tanggal */}
                  <div className="flex flex-col md:flex-row gap-4">
                    <div className="flex-1">
                      <Label className="mb-1">Start Date</Label>
                      <Input
                        type="date"
                        value={startDate || ''}
                        onChange={(e) => setStartDate(e.target.value)}
                      />
                    </div>
                    <div className="flex-1">
                      <Label className="mb-1">End Date</Label>
                      <Input
                        type="date"
                        value={endDate || ''}
                        onChange={(e) => setEndDate(e.target.value)}
                      />
                    </div>
                  </div>
                  {/* Kelompok User & Offer */}
                  <div className="flex flex-col md:flex-row gap-4">
                    <div className="flex-1">
                      <Label className="mb-1">User ID</Label>
                      <Input
                        type="text"
                        value={userId || ''}
                        onChange={(e) => setUserId(e.target.value)}
                      />
                    </div>
                    <div className="flex-1">
                      <Label className="mb-1">Offer ID</Label>
                      <Input
                        type="text"
                        value={offerId || ''}
                        onChange={(e) => setOfferId(e.target.value)}
                      />
                    </div>
                  </div>
                  {/* Kelompok Sort */}
                  <div className="flex flex-col md:flex-row gap-4">
                    <div className="flex-1">
                      <Label className="mb-1">Sort By</Label>
                      <Select onValueChange={(v) => setSortBy(v as 'asc' | 'desc')} value={sortBy}>
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="Select Sort Order" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="asc">Ascending</SelectItem>
                          <SelectItem value="desc">Descending</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="flex-1">
                      <Label className="mb-1">Sort Column</Label>
                      <Select
                        onValueChange={(v) => setSortColumn(v as typeof sortColumn)}
                        value={sortColumn}
                      >
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="Select Sort Column" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="created_at">Created At</SelectItem>
                          <SelectItem value="updated_at">Updated At</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
                <DialogFooter className="flex flex-col items-stretch gap-2">
                  <Button type="submit" variant="default">
                    Apply Filter
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
          {(userId ||
            startDate ||
            endDate ||
            offerId ||
            sortBy !== 'desc' ||
            sortColumn !== 'created_at') && (
            <Button type="button" variant="outline" onClick={handleReset}>
              Reset Filter
            </Button>
          )}
          <Select value={String(limit)} onValueChange={handleLimitChange}>
            <SelectTrigger className="w-[100px]">
              <SelectValue placeholder="Limit" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="10">10</SelectItem>
              <SelectItem value="20">20</SelectItem>
              <SelectItem value="50">50</SelectItem>
              <SelectItem value="100">100</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="grid">
        <DataTable columns={columns} data={usedOffer} />
      </div>
      <div className="flex justify-between items-center mt-4">
        <span>
          Page {pagination.page} of {pagination.totalPages}
        </span>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={pagination.page <= 1}
            onClick={() => handlePageChange(pagination.page - 1)}
          >
            Previous
          </Button>
          <Button
            variant="outline"
            size="sm"
            disabled={pagination.page >= pagination.totalPages}
            onClick={() => handlePageChange(pagination.page + 1)}
          >
            Next
          </Button>
        </div>
      </div>
    </AdminLayout>
  )
}
