"use client"

import { useEffect, useMemo, useState } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Loader2, ChevronLeft, ChevronRight } from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

type Tx = {
  id: number
  full_name: string
  email: string
  amount: string
  fee: string
  charged_amount: string
  invoice_id: string
  order_id: string
  product_id: string
  payment_method: string
  sender_number: string
  transaction_id: string
  wallet: string
  date: string
  status: string
  txn_hash: string | null
  created_at: string
  updated_at: string
}

type Paginated<T> = {
  current_page: number
  data: T[]
  first_page_url: string
  from: number | null
  last_page: number
  last_page_url: string
  links: { url: string | null; label: string; active: boolean }[]
  next_page_url: string | null
  path: string
  per_page: number
  prev_page_url: string | null
  to: number | null
  total: number
}

function StatusPill({ status }: { status: string }) {
  const s = (status || "").toUpperCase()
  const cls =
    s === "COMPLETED"
      ? "bg-emerald-100 text-emerald-700 border-emerald-200"
      : s === "FAILED"
        ? "bg-red-100 text-red-700 border-red-200"
        : "bg-amber-100 text-amber-700 border-amber-200"
  return (
    <span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${cls}`}>{s}</span>
  )
}

function MobileTxCard({ t }: { t: Tx }) {
  return (
    <div className="rounded-lg border p-3">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="font-medium text-sm">{t.full_name}</div>
          <div className="text-xs text-muted-foreground break-all">{t.email}</div>
        </div>
        <StatusPill status={t.status} />
      </div>

      <div className="mt-3 grid grid-cols-2 gap-2 text-xs">
        <div className="space-y-0.5">
          <div className="text-muted-foreground">Amount</div>
          <div className="font-medium tabular-nums">{t.amount}</div>
        </div>
        <div className="space-y-0.5">
          <div className="text-muted-foreground">Method</div>
          <div className="font-medium capitalize">{t.payment_method}</div>
        </div>
        <div className="space-y-0.5 col-span-2">
          <div className="text-muted-foreground">Date</div>
          <div className="font-medium">{t.date}</div>
        </div>
        <div className="space-y-0.5">
          <div className="text-muted-foreground">Order ID</div>
          <div className="font-medium break-all">{t.order_id}</div>
        </div>
        <div className="space-y-0.5">
          <div className="text-muted-foreground">Invoice</div>
          <div className="font-medium break-all">{t.invoice_id}</div>
        </div>
        <div className="space-y-0.5 col-span-2">
          <div className="text-muted-foreground">Txn ID</div>
          <div className="font-medium break-all">{t.transaction_id}</div>
        </div>
      </div>
    </div>
  )
}

export default function TransactionsPage() {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [perPage, setPerPage] = useState("10")
  const [resp, setResp] = useState<Paginated<Tx> | null>(null)

  // Filters (client-side on the current page)
  const [search, setSearch] = useState("")
  const [status, setStatus] = useState<string>("all")
  const [method, setMethod] = useState<string>("all")

  useEffect(() => {
    let mounted = true
    async function load() {
      setLoading(true)
      setError(null)
      try {
        const res = await fetch(`/api/transactions?page=${page}&per_page=${perPage}`, { cache: "no-store" })
        const data = res.ok ? await res.json() : null
        if (!mounted) return
        if (!res.ok) {
          setError(data?.message ?? res.statusText)
          setResp(null)
        } else {
          if (data && Array.isArray(data.data)) {
            setResp(data as Paginated<Tx>)
          } else if (Array.isArray(data)) {
            setResp({
              current_page: 1,
              data,
              first_page_url: "",
              from: data.length ? 1 : 0,
              last_page: 1,
              last_page_url: "",
              links: [],
              next_page_url: null,
              path: "",
              per_page: Number(perPage),
              prev_page_url: null,
              to: data.length,
              total: data.length,
            })
          } else {
            setResp(null)
          }
        }
      } catch (e: any) {
        if (!mounted) return
        setError(e?.message ?? "Failed to load transactions.")
        setResp(null)
      } finally {
        if (mounted) setLoading(false)
      }
    }
    load()
    return () => {
      mounted = false
    }
  }, [page, perPage])

  const filtered = useMemo(() => {
    const rows = resp?.data ?? []
    const q = search.trim().toLowerCase()
    return rows.filter((t) => {
      const matchesSearch =
        !q ||
        t.full_name?.toLowerCase().includes(q) ||
        t.email?.toLowerCase().includes(q) ||
        t.order_id?.toLowerCase().includes(q) ||
        t.invoice_id?.toLowerCase().includes(q) ||
        t.transaction_id?.toLowerCase().includes(q)
      const matchesStatus = status === "all" || (t.status ?? "").toLowerCase() === status.toLowerCase()
      const matchesMethod = method === "all" || (t.payment_method ?? "").toLowerCase() === method.toLowerCase()
      return matchesSearch && matchesStatus && matchesMethod
    })
  }, [resp, search, status, method])

  const currentPage = resp?.current_page ?? page
  const lastPage = resp?.last_page ?? 1
  const total = resp?.total ?? filtered.length

  const canPrev = currentPage > 1 && !!resp?.prev_page_url
  const canNext = currentPage < lastPage && !!resp?.next_page_url

  function toPage(p: number) {
    if (p < 1 || p > (resp?.last_page ?? 1)) return
    setPage(p)
  }

  // Build a compact page list around current page
  const pages = (() => {
    const lp = lastPage
    const cur = currentPage
    const delta = 1
    const start = Math.max(1, cur - delta)
    const end = Math.min(lp, cur + delta)
    const arr: number[] = []
    for (let i = start; i <= end; i++) arr.push(i)
    if (!arr.includes(1)) arr.unshift(1)
    if (!arr.includes(lp)) arr.push(lp)
    return Array.from(new Set(arr)).sort((a, b) => a - b)
  })()

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl sm:text-2xl font-semibold">Transactions</h1>
        <p className="text-sm text-muted-foreground">Browse and filter transactions</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base sm:text-lg">Filters</CardTitle>
          <CardDescription>Use these to refine the current page of results.</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-3 sm:gap-4 md:grid-cols-4">
          <div className="space-y-2 md:col-span-2">
            <Label htmlFor="search">Search</Label>
            <Input
              id="search"
              placeholder="Name, email, order ID, invoice ID, or transaction ID"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label>Status</Label>
            <Select value={status} onValueChange={setStatus}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="All" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="completed">COMPLETED</SelectItem>
                <SelectItem value="pending">PENDING</SelectItem>
                <SelectItem value="failed">FAILED</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Payment Method</Label>
            <Select value={method} onValueChange={setMethod}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="All" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="bkash">bkash</SelectItem>
                <SelectItem value="nagad">nagad</SelectItem>
                <SelectItem value="rocket">rocket</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div>
            <CardTitle className="text-base sm:text-lg">Transactions</CardTitle>
            <CardDescription>
              Page {currentPage} of {lastPage} • {total} total
            </CardDescription>
          </div>
          <div className="flex items-center gap-2">
            <Label htmlFor="perpage" className="text-sm text-muted-foreground">
              Per page
            </Label>
            <Select
              value={perPage}
              onValueChange={(v) => {
                setPerPage(v)
                setPage(1)
              }}
            >
              <SelectTrigger id="perpage" className="w-[100px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="25">25</SelectItem>
                <SelectItem value="50">50</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              Loading...
            </div>
          ) : error ? (
            <div className="text-sm text-red-600">{error}</div>
          ) : filtered.length === 0 ? (
            <div className="text-sm text-muted-foreground">No transactions found on this page.</div>
          ) : (
            <>
              {/* Mobile list (small screens) */}
              <div className="md:hidden space-y-3">
                {filtered.map((t) => (
                  <MobileTxCard key={t.id} t={t} />
                ))}
              </div>

              {/* Table (md and up) */}
              <div className="hidden md:block rounded-md border overflow-x-auto max-w-full">
                <table className="w-full text-xs sm:text-sm">
                  <thead className="bg-muted">
                    <tr className="whitespace-nowrap">
                      <th className="px-3 py-2 text-left">ID</th>
                      <th className="px-3 py-2 text-left">Full Name</th>
                      <th className="px-3 py-2 text-left hidden sm:table-cell">Email</th>
                      <th className="px-3 py-2 text-left">Amount</th>
                      <th className="px-3 py-2 text-left hidden lg:table-cell">Charged</th>
                      <th className="px-3 py-2 text-left">Method</th>
                      <th className="px-3 py-2 text-left hidden lg:table-cell">Sender</th>
                      <th className="px-3 py-2 text-left hidden lg:table-cell">Order ID</th>
                      <th className="px-3 py-2 text-left hidden xl:table-cell">Invoice</th>
                      <th className="px-3 py-2 text-left hidden xl:table-cell">Txn ID</th>
                      <th className="px-3 py-2 text-left hidden xl:table-cell">Wallet</th>
                      <th className="px-3 py-2 text-left hidden md:table-cell">Date</th>
                      <th className="px-3 py-2 text-left">Status</th>
                      <th className="px-3 py-2 text-left hidden xl:table-cell">Txn Hash</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map((t) => (
                      <tr key={t.id} className="border-t align-top">
                        <td className="px-3 py-2">{t.id}</td>
                        <td className="px-3 py-2">{t.full_name}</td>
                        <td className="px-3 py-2 hidden sm:table-cell break-all">{t.email}</td>
                        <td className="px-3 py-2 tabular-nums">{t.amount}</td>
                        <td className="px-3 py-2 tabular-nums hidden lg:table-cell">{t.charged_amount}</td>
                        <td className="px-3 py-2 capitalize">{t.payment_method}</td>
                        <td className="px-3 py-2 hidden lg:table-cell break-all">{t.sender_number}</td>
                        <td className="px-3 py-2 hidden lg:table-cell break-all">{t.order_id}</td>
                        <td className="px-3 py-2 hidden xl:table-cell break-all">{t.invoice_id}</td>
                        <td className="px-3 py-2 hidden xl:table-cell break-all">{t.transaction_id}</td>
                        <td className="px-3 py-2 hidden xl:table-cell break-all">{t.wallet}</td>
                        <td className="px-3 py-2 hidden md:table-cell">{t.date}</td>
                        <td className="px-3 py-2">
                          <StatusPill status={t.status} />
                        </td>
                        <td className="px-3 py-2 hidden xl:table-cell break-all">{t.txn_hash ?? "—"}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}

          {!loading && !error && (resp?.last_page ?? 1) > 1 && (
            <div className="mt-4 flex flex-wrap items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => toPage(Math.max(1, currentPage - 1))}
                disabled={!canPrev}
              >
                <ChevronLeft className="mr-1 h-4 w-4" />
                Prev
              </Button>
              {pages.map((p) => (
                <Button key={p} variant={p === currentPage ? "default" : "outline"} size="sm" onClick={() => toPage(p)}>
                  {p}
                </Button>
              ))}
              <Button
                variant="outline"
                size="sm"
                onClick={() => toPage(Math.min(lastPage, currentPage + 1))}
                disabled={!canNext}
              >
                Next
                <ChevronRight className="ml-1 h-4 w-4" />
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
