'use client'

import { useState, useEffect } from 'react'
import DashboardLayout from '@/components/DashboardLayout'
import { 
  MdContentCopy, 
  MdOpenInNew, 
  MdHistory, 
  MdRefresh, 
  MdNavigateBefore, 
  MdNavigateNext 
} from 'react-icons/md'
import toast from 'react-hot-toast'

interface Transaction {
  id: string
  type: string
  amount: string
  hash: string
  dateTime: string
  status: string
}

export default function TransactionsPage() {
  const [loading, setLoading] = useState(true)
  const [transactions, setTransactions] = useState<Transaction[]>([])
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 8

  const fetchTransactions = async (mId: string) => {
    setLoading(true)
    try {
      const res = await fetch(`/api/transactions?memberId=${mId}`)
      const data = await res.json()
      if (data.success) {
        setTransactions(data.transactions || [])
      } else {
        toast.error(data.error || 'Failed to fetch transactions')
      }
    } catch (e) {
      console.error(e)
      toast.error('An error occurred while loading transactions')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const session = localStorage.getItem('memberSession')
    if (!session) {
      window.location.href = '/'
      return
    }

    try {
      const parsed = JSON.parse(session)
      fetchTransactions(parsed.memberId)
    } catch (e) {
      console.error(e)
      setLoading(false)
    }
  }, [])

  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text)
    toast.success('Transaction hash copied!', { id: 'copy-toast' })
  }

  const handleRefresh = () => {
    const session = localStorage.getItem('memberSession')
    if (session) {
      try {
        const parsed = JSON.parse(session)
        fetchTransactions(parsed.memberId)
        setCurrentPage(1)
      } catch (e) {
        console.error(e)
      }
    }
  }

  // Pagination calculations
  const indexOfLastItem = currentPage * itemsPerPage
  const indexOfFirstItem = indexOfLastItem - itemsPerPage
  const currentItems = transactions.slice(indexOfFirstItem, indexOfLastItem)
  const totalPages = Math.ceil(transactions.length / itemsPerPage)

  const paginate = (pageNumber: number) => {
    if (pageNumber >= 1 && pageNumber <= totalPages) {
      setCurrentPage(pageNumber)
    }
  }

  return (
    <DashboardLayout>
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-3xl font-extrabold text-white tracking-tight flex items-center gap-2">
            <MdHistory className="text-violet-400" />
            <span>Transaction History</span>
          </h1>
          <p className="text-slate-400 text-sm mt-1">
            Browse and track your deposits, withdrawals, swaps, and token mints.
          </p>
        </div>
        <button
          onClick={handleRefresh}
          className="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-violet-500/10 bg-violet-950/20 text-slate-350 hover:text-white hover:bg-violet-950/45 text-sm font-semibold transition cursor-pointer self-start md:self-auto"
        >
          <MdRefresh className={loading ? 'animate-spin' : ''} size={18} />
          <span>Refresh</span>
        </button>
      </div>

      <div className="glass-panel rounded-3xl p-6 md:p-8 overflow-hidden">
        {loading ? (
          <div className="flex flex-col items-center justify-center py-20 gap-4">
            <div className="w-10 h-10 border-4 border-violet-500/20 border-t-violet-500 rounded-full animate-spin"></div>
            <p className="text-sm text-slate-400 font-medium">Fetching transactions from MongoDB...</p>
          </div>
        ) : transactions.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-center gap-3">
            <MdHistory size={48} className="text-slate-600" />
            <h3 className="text-lg font-bold text-white">No Transactions Found</h3>
            <p className="text-sm text-slate-400 max-w-sm">
              You haven't executed any transactions on this account yet.
            </p>
          </div>
        ) : (
          <div className="flex flex-col gap-6">
            {/* Table Container */}
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="border-b border-violet-950/20 text-slate-400 text-xs font-bold uppercase tracking-wider">
                    <th className="py-4 px-4"># / Sl No</th>
                    <th className="py-4 px-4">Type / Method</th>
                    <th className="py-4 px-4">Amount</th>
                    <th className="py-4 px-4">Transaction Hash</th>
                    <th className="py-4 px-4">Date & Time</th>
                    <th className="py-4 px-4 text-center">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-violet-950/10 text-sm text-slate-300">
                  {currentItems.map((tx, idx) => {
                    const serialNumber = indexOfFirstItem + idx + 1
                    
                    // Style badges based on Type
                    const isIncoming = tx.type === 'Mint' || tx.type === 'Deposit'
                    const typeBadgeClass = isIncoming
                      ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'
                      : 'bg-violet-500/10 border-violet-500/20 text-violet-300'

                    // Style badges based on Status
                    let statusBadgeClass = 'bg-amber-500/10 border-amber-500/20 text-amber-400' // Pending default
                    if (tx.status === 'Success') {
                      statusBadgeClass = 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'
                    } else if (tx.status === 'Failed') {
                      statusBadgeClass = 'bg-rose-500/10 border-rose-500/20 text-rose-300'
                    }

                    // Format truncated hash
                    const truncatedHash = tx.hash 
                      ? `${tx.hash.slice(0, 6)}...${tx.hash.slice(-4)}`
                      : 'N/A'

                    const isExplorerLink = tx.hash && !tx.hash.startsWith('0xdummy')

                    return (
                      <tr key={tx.id} className="hover:bg-violet-950/5 transition duration-150">
                        <td className="py-4.5 px-4 font-mono text-slate-450">{serialNumber}</td>
                        <td className="py-4.5 px-4">
                          <span className={`inline-flex items-center px-2.5 py-1 rounded-lg border text-xs font-semibold ${typeBadgeClass}`}>
                            {tx.type}
                          </span>
                        </td>
                        <td className="py-4.5 px-4 font-semibold text-white">{tx.amount}</td>
                        <td className="py-4.5 px-4">
                          {isExplorerLink ? (
                            <div className="flex items-center gap-2">
                              <a
                                href={`https://testnet.bscscan.com/tx/${tx.hash}`}
                                target="_blank"
                                rel="noreferrer"
                                className="font-mono text-violet-400 hover:text-violet-300 hover:underline flex items-center gap-1"
                              >
                                <span>{truncatedHash}</span>
                                <MdOpenInNew size={13} className="inline opacity-80" />
                              </a>
                              <button
                                onClick={() => handleCopy(tx.hash)}
                                className="p-1 rounded-md text-slate-500 hover:text-slate-200 hover:bg-slate-900 transition cursor-pointer"
                                title="Copy full hash"
                              >
                                <MdContentCopy size={13} />
                              </button>
                            </div>
                          ) : (
                            <span className="font-mono text-slate-500">{truncatedHash}</span>
                          )}
                        </td>
                        <td className="py-4.5 px-4 font-medium text-slate-400">{tx.dateTime}</td>
                        <td className="py-4.5 px-4 text-center">
                          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full border text-xs font-bold ${statusBadgeClass}`}>
                            {tx.status}
                          </span>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>

            {/* Pagination Controls */}
            {totalPages > 1 && (
              <div className="flex flex-col sm:flex-row items-center justify-between border-t border-violet-950/20 pt-6 gap-4">
                <span className="text-xs text-slate-400 font-medium">
                  Showing {indexOfFirstItem + 1} to {Math.min(indexOfLastItem, transactions.length)} of {transactions.length} entries
                </span>
                <div className="flex items-center gap-1.5">
                  {/* Previous Button */}
                  <button
                    onClick={() => paginate(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="p-2 rounded-xl border border-violet-500/10 bg-violet-950/20 text-slate-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed hover:bg-violet-950/45 transition cursor-pointer"
                  >
                    <MdNavigateBefore size={20} />
                  </button>

                  {/* Page Numbers */}
                  {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNum) => (
                    <button
                      key={pageNum}
                      onClick={() => paginate(pageNum)}
                      className={`w-9 h-9 rounded-xl border text-xs font-bold transition cursor-pointer ${
                        currentPage === pageNum
                          ? 'bg-violet-600 border-violet-500 text-white shadow-md shadow-violet-500/20'
                          : 'border-violet-500/10 bg-violet-950/20 text-slate-400 hover:text-white hover:bg-violet-950/45'
                      }`}
                    >
                      {pageNum}
                    </button>
                  ))}

                  {/* Next Button */}
                  <button
                    onClick={() => paginate(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="p-2 rounded-xl border border-violet-500/10 bg-violet-950/20 text-slate-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed hover:bg-violet-950/45 transition cursor-pointer"
                  >
                    <MdNavigateNext size={20} />
                  </button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </DashboardLayout>
  )
}
