"use client"

import { useState, useEffect } from "react"
import { useTranslation } from "react-i18next"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { format } from "date-fns"
import {
  ArrowLeft,
  Calendar,
  CreditCard,
  Download,
  FileText,
  Clock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Clock3,
} from "lucide-react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

import { orders } from "@/services/orders/query"
import { orderPayments, getPaymentsByOrderId } from "@/services/order_payments/query"

export default function StudentPaymentDetailPage({ params }: { params: { id: string } }) {
  const { t } = useTranslation()
  const router = useRouter()
  const paymentId = Number.parseInt(params.id)

  const [payment, setPayment] = useState<any>(null)
  const [order, setOrder] = useState<any>(null)
  const [studentId, setStudentId] = useState<number | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // Get student ID from localStorage
    const storedStudentId = localStorage.getItem("studentId")
    if (storedStudentId) {
      setStudentId(Number.parseInt(storedStudentId, 10))
    }

    // Find the payment
    const foundPayment = orderPayments.find((p) => p.id === paymentId)
    if (!foundPayment) {
      router.push("/student/payments")
      return
    }

    // Find the associated order
    const foundOrder = orders.find((o) => o.id === foundPayment.order_id)
    if (!foundOrder) {
      router.push("/student/payments")
      return
    }

    // Check if this payment belongs to the current student
    if (foundOrder.student_id !== Number.parseInt(storedStudentId || "0", 10)) {
      router.push("/student/payments")
      return
    }

    setPayment(foundPayment)
    setOrder(foundOrder)
    setLoading(false)
  }, [paymentId, router])

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <Clock className="h-10 w-10 text-muted-foreground mx-auto mb-4 animate-spin" />
          <p className="text-muted-foreground">{t("student.loading", "Loading payment details...")}</p>
        </div>
      </div>
    )
  }

  if (!payment || !order) {
    return <div>{t("student.notFound", "Payment not found")}</div>
  }

  // Format currency
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("zh-CN", {
      style: "currency",
      currency: "CNY",
    }).format(amount)
  }

  // Get status badge
  const getStatusBadge = (status: string) => {
    switch (status) {
      case "completed":
        return (
          <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
            <CheckCircle2 className="h-3 w-3 mr-1" />
            {t("student.payments.status.completed", "Completed")}
          </Badge>
        )
      case "pending":
        return (
          <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-200">
            <Clock3 className="h-3 w-3 mr-1" />
            {t("student.payments.status.pending", "Pending")}
          </Badge>
        )
      case "failed":
        return (
          <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">
            <XCircle className="h-3 w-3 mr-1" />
            {t("student.payments.status.failed", "Failed")}
          </Badge>
        )
      default:
        return (
          <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">
            <AlertCircle className="h-3 w-3 mr-1" />
            {status}
          </Badge>
        )
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="sm" asChild>
            <Link href="/student/payments">
              <ArrowLeft className="h-4 w-4 mr-1" />
              {t("student.payments.backToList", "Back to payments")}
            </Link>
          </Button>
        </div>
        {false && (
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" asChild>
            <Link href={`/student/payment/${payment.id}/receipt`}>
              <FileText className="h-4 w-4 mr-1" />
              {t("student.payments.viewReceipt", "View Receipt")}
            </Link>
          </Button>
          <Button variant="outline" size="sm">
            <Download className="h-4 w-4 mr-1" />
            {t("student.payments.downloadReceipt", "Download Receipt")}
          </Button>
        </div>
           )}
      </div>
   

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="md:col-span-2 space-y-6">
          <Card className="border-0 bg-white shadow-sm">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle>{t("student.payments.paymentDetails", "Payment Details")}</CardTitle>
                {getStatusBadge(payment.status)}
              </div>
              <CardDescription>
                {t("student.payments.orderId", "Order ID")}: #{order.id.toString().padStart(6, "0")}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <h3 className="text-sm font-medium text-muted-foreground mb-1">
                      {t("student.payments.reference", "Reference")}
                    </h3>
                    <p>{payment.reference}</p>
                  </div>
                  <div>
                    <h3 className="text-sm font-medium text-muted-foreground mb-1">
                      {t("student.payments.method", "Payment Method")}
                    </h3>
                    <div className="flex items-center">
                      <CreditCard className="h-4 w-4 mr-2 text-muted-foreground" />
                      <span>{payment.method}</span>
                    </div>
                  </div>
                  <div>
                    <h3 className="text-sm font-medium text-muted-foreground mb-1">
                      {t("student.payments.amount", "Amount")}
                    </h3>
                    <p className="text-lg font-semibold">{formatCurrency(payment.amount_paid)}</p>
                  </div>
                  <div>
                    <h3 className="text-sm font-medium text-muted-foreground mb-1">
                      {t("student.payments.paidAt", "Paid At")}
                    </h3>
                    <div className="flex items-center">
                      <Calendar className="h-4 w-4 mr-2 text-muted-foreground" />
                      <span>{payment.paid_at ? format(new Date(payment.paid_at), "PPP") : "Not paid yet"}</span>
                    </div>
                  </div>
                </div>

                <Separator />

                <div>
                  <h3 className="text-sm font-medium mb-2">{t("student.payments.description", "Description")}</h3>
                  <p className="text-muted-foreground">{payment.description}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Tabs defaultValue="details" className="w-full">
            <TabsList className="bg-gray-100">
              <TabsTrigger value="details">{t("student.payments.orderDetails", "Order Details")}</TabsTrigger>
              <TabsTrigger value="history">{t("student.payments.paymentHistory", "Payment History")}</TabsTrigger>
            </TabsList>

            <TabsContent value="details" className="mt-6">
              <Card className="border-0 bg-white shadow-sm">
                <CardHeader>
                  <CardTitle>{t("student.payments.orderSummary", "Order Summary")}</CardTitle>
                  <CardDescription>
                    {t("student.payments.orderDate", "Order Date")}: {format(new Date(order.created_at), "PPP")}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <h3 className="text-sm font-medium text-muted-foreground mb-1">
                          {t("student.payments.orderStatus", "Order Status")}
                        </h3>
                        <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
                          {order.status}
                        </Badge>
                      </div>
                      <div>
                        <h3 className="text-sm font-medium text-muted-foreground mb-1">
                          {t("student.payments.paymentStatus", "Payment Status")}
                        </h3>
                        <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                          {order.payment_status}
                        </Badge>
                      </div>
                    </div>

                    <Separator />

                    <div className="flex flex-col gap-2">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">{t("student.payments.subtotal", "Subtotal")}</span>
                        <span>{formatCurrency(order.total_amount)}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">{t("student.payments.discount", "Discount")}</span>
                        <span>-{formatCurrency(order.discount_amount)}</span>
                      </div>
                      <div className="flex justify-between font-medium">
                        <span>{t("student.payments.total", "Total")}</span>
                        <span>{formatCurrency(order.final_amount)}</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="history" className="mt-6">
              <Card className="border-0 bg-white shadow-sm">
                <CardHeader>
                  <CardTitle>{t("student.payments.transactionHistory", "Transaction History")}</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {getPaymentsByOrderId(order.id).map((p, index) => (
                      <div
                        key={index}
                        className="flex justify-between items-start border-b pb-3 last:border-0 last:pb-0"
                      >
                        <div>
                          <p className="font-medium">{p.method}</p>
                          <p className="text-sm text-muted-foreground">{format(new Date(p.created_at), "PPP")}</p>
                          <p className="text-sm text-muted-foreground">{p.reference}</p>
                        </div>
                        <div className="text-right">
                          <p className="font-medium">{formatCurrency(p.amount_paid)}</p>
                          <Badge
                            variant="outline"
                            className={`
                            ${
                              p.status === "completed"
                                ? "bg-green-50 text-green-700 border-green-200"
                                : p.status === "pending"
                                  ? "bg-yellow-50 text-yellow-700 border-yellow-200"
                                  : "bg-red-50 text-red-700 border-red-200"
                            }
                          `}
                          >
                            {p.status}
                          </Badge>
                        </div>
                      </div>
                    ))}

                    {getPaymentsByOrderId(order.id).length === 0 && (
                      <div className="text-center py-6 text-muted-foreground">
                        {t("student.payments.noTransactions", "No transaction history available")}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>

        <div className="space-y-6">
          <Card className="border-0 bg-white shadow-sm">
            <CardHeader>
              <CardTitle>{t("student.payments.actions", "Actions")}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <Button className="w-full" asChild>
                  <Link href={`/student/payment/${payment.id}/receipt`}>
                    <FileText className="h-4 w-4 mr-2" />
                    {t("student.payments.viewReceipt", "View Receipt")}
                  </Link>
                </Button>
                <Button variant="outline" className="w-full">
                  <Download className="h-4 w-4 mr-2" />
                  {t("student.payments.downloadReceipt", "Download Receipt")}
                </Button>
                {payment.status === "pending" && (
                  <Button variant="secondary" className="w-full">
                    <CreditCard className="h-4 w-4 mr-2" />
                    {t("student.payments.payNow", "Pay Now")}
                  </Button>
                )}
              </div>
            </CardContent>
          </Card>

          <Card className="border-0 bg-white shadow-sm">
            <CardHeader>
              <CardTitle>{t("student.payments.timeline", "Timeline")}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {payment.status === "completed" && (
                  <div className="flex gap-3">
                    <div className="flex flex-col items-center">
                      <div className="h-6 w-6 rounded-full bg-green-100 flex items-center justify-center">
                        <CheckCircle2 className="h-4 w-4 text-green-600" />
                      </div>
                      <div className="w-0.5 h-12 bg-gray-200"></div>
                    </div>
                    <div>
                      <p className="font-medium">{t("student.payments.paymentReceived", "Payment Received")}</p>
                      <p className="text-sm text-muted-foreground">
                        {format(new Date(payment.paid_at || payment.created_at), "PPP p")}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        {payment.method} - {payment.reference}
                      </p>
                    </div>
                  </div>
                )}

                <div className="flex gap-3">
                  <div className="flex flex-col items-center">
                    <div className="h-6 w-6 rounded-full bg-blue-100 flex items-center justify-center">
                      <Clock className="h-4 w-4 text-blue-600" />
                    </div>
                  </div>
                  <div>
                    <p className="font-medium">{t("student.payments.orderCreated", "Order Created")}</p>
                    <p className="text-sm text-muted-foreground">{format(new Date(order.created_at), "PPP p")}</p>
                    <p className="text-sm text-muted-foreground">Order #{order.id.toString().padStart(6, "0")}</p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
