"use client";

import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Download, ChevronLeft, ChevronRight } from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { useCallback, useEffect, useState } from "react";
import PriceDisplay from "@/components/ui/formattedPrice";


// Mock data for payment history



export function PaymentHistory() {

  console.log("HELLO WORLD")

  const [payments, setPayments] = useState<Payments[]>([])
  const [total, setTotal] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(10)
  const [previousDisabled, setPreviousDisabled] = useState(true)
  const [nextDisabled, setNextDisabled] = useState(false)

  const fetchPayments = useCallback(async () => {

    const response = await fetch(`/api/user/payment?page=${page}&limit=${limit}`)

    const data = await response.json()

    setPayments(data.data)
    setTotal(data.total)
    setTotalPages(data.totalPages)

    if (data.total <= page * limit) {
      setNextDisabled(true)
    }
    else {
      setNextDisabled(false)
    }


    if (page * limit > limit) {
      setPreviousDisabled(false)
    }

    if (page * limit <= limit) {
      setPreviousDisabled(true)
    }

    // console.log(data)

  }, [page, limit])

  useEffect(() => {


    fetchPayments()
  }, [fetchPayments])

  const increasePage = () => {
    if (page * limit < total) {
      setPage(prev => prev + 1);

    }
    else {

    }
  }

  const decreasePage = () => {
    if (page * limit > limit) {
      setPage(prev => prev - 1)
    }
    else {

    }
  }


  return (
    <Card>
      <CardHeader>
        <CardTitle>Payment History</CardTitle>
        <CardDescription>
          View your recent payment transactions.
        </CardDescription>
      </CardHeader>

      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>ID</TableHead>
              <TableHead>PaymentID</TableHead>
              <TableHead>Date</TableHead>
              <TableHead>Amount</TableHead>
              <TableHead>Method</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {payments.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-6 text-gray-500">
                  No payment history found
                </TableCell>
              </TableRow>
            ) : (
              payments.map((payment) => (
                <TableRow key={payment.id}>
                  <TableCell className="font-medium">{payment.id}</TableCell>
                  <TableCell className="font-medium">{payment.paymentID}</TableCell>
                  <TableCell>
                    {payment.created_on instanceof Date
                      ? payment.created_on.toLocaleDateString()
                      : payment.created_on}
                  </TableCell>
                  <TableCell>
                    <PriceDisplay price={payment.amount} />
                  </TableCell>
                  <TableCell>{payment.payment_method}</TableCell>
                  <TableCell>{payment.payment_status}</TableCell>
                  <TableCell className="text-right">
                    <Dialog>
                      <DialogTrigger asChild>
                        <Button variant="ghost" size="sm">
                          View
                        </Button>
                      </DialogTrigger>
                      <DialogContent className="bg-white">
                        <DialogHeader>
                          <DialogTitle>Payment Details</DialogTitle>
                          <DialogDescription>
                            Transaction information for {payment.id}
                          </DialogDescription>
                        </DialogHeader>
                        <div className="space-y-4 py-4">
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <h4 className="text-sm font-medium mb-1">
                                Transaction ID
                              </h4>
                              <p className="text-sm">{payment.id}</p>
                            </div>
                            <div>
                              <h4 className="text-sm font-medium mb-1">Order ID</h4>
                              <p className="text-sm">{payment.order_id}</p>
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <h4 className="text-sm font-medium mb-1">Date</h4>
                              <p className="text-sm">
                                {payment.payment_date instanceof Date
                                  ? payment.payment_date.toLocaleDateString()
                                  : payment.payment_date}
                              </p>
                            </div>
                            <div>
                              <h4 className="text-sm font-medium mb-1">Status</h4>
                              {payment.payment_status}
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <h4 className="text-sm font-medium mb-1">Amount</h4>
                              <p className="text-sm font-bold">{payment.amount}</p>
                            </div>
                            <div>
                              <h4 className="text-sm font-medium mb-1">
                                Payment Method
                              </h4>
                              <p className="text-sm">{payment.payment_method}</p>
                            </div>
                          </div>
                        </div>
                      </DialogContent>
                    </Dialog>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </CardContent>

      {total > 0 && (
        <CardFooter className="flex justify-between">
          <div className="text-sm text-muted-foreground">
            Showing <strong>{page * limit}</strong> of <strong>{total}</strong> transactions
          </div>
          <div className="flex items-center space-x-2">
            <Button onClick={decreasePage} variant="outline" size="sm" disabled={previousDisabled}>
              <ChevronLeft className="h-4 w-4 mr-1" />
              Previous
            </Button>
            <Button onClick={increasePage} variant="outline" size="sm" disabled={nextDisabled}>
              Next
              <ChevronRight className="h-4 w-4 ml-1" />
            </Button>
          </div>
        </CardFooter>
      )}
    </Card>
  );
}
