'use client';

import React, { useState, useEffect } from 'react';
import { apiRequest } from '@/lib/api';
import {
  Receipt,
  CreditCard,
  CheckCircle,
  Clock,
  AlertCircle,
  BookOpen,
  Calendar,
  DollarSign,
  RefreshCw,
  Eye,
  X,
} from 'lucide-react';

interface Course {
  _id: string;
  title: string;
  level?: string;
  regularPrice?: number;
  offerPrice?: number;
}

interface Order {
  _id: string;
  courses: Course[];
  gateway: string;
  amount: number;
  currency: string;
  status: 'initiated' | 'completed' | 'failed' | 'pending';
  bankTransferDetails?: {
    adminConfirmationStatus: string;
    receiptScreenshotUrl?: string;
  };
  createdAt: string;
}

export default function StudentPurchasesPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);

  const fetchPurchases = async () => {
    setLoading(true);
    const res = await apiRequest('/orders');
    if (res.success && res.orders) {
      setOrders(res.orders);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchPurchases();

    // Check if returning from official Stripe Checkout Session
    if (typeof window !== 'undefined') {
      const urlParams = new URLSearchParams(window.location.search);
      const sessionId = urlParams.get('session_id');
      const orderId = urlParams.get('order_id');

      if (sessionId || orderId) {
        const verifyStripeSession = async () => {
          const verifyRes = await apiRequest(
            `/payments/verify-session?session_id=${sessionId || ''}&order_id=${orderId || ''}`
          );
          if (verifyRes.success) {
            fetchPurchases();
          }
        };
        verifyStripeSession();
      }
    }
  }, []);

  const totalSpent = orders
    .filter((o) => o.status === 'completed')
    .reduce((sum, o) => sum + (o.amount || 0), 0);

  const completedCount = orders.filter((o) => o.status === 'completed').length;
  const pendingCount = orders.filter((o) => o.status === 'pending' || o.status === 'initiated').length;

  return (
    <div className="space-y-8 max-w-6xl mx-auto">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight flex items-center gap-3">
            <span>Purchase History & Receipts</span>
          </h1>
          <p className="text-sm text-gray-500 mt-1">
            Track your course enrollment invoices, payment receipts, and order statuses
          </p>
        </div>

        <button
          onClick={fetchPurchases}
          className="px-4 py-2 rounded-xl bg-white hover:bg-gray-100 text-gray-700 font-bold text-xs border border-gray-200 shadow-xs transition flex items-center gap-2 self-start md:self-auto"
        >
          <RefreshCw className="w-3.5 h-3.5 text-gray-500" />
          <span>Refresh Orders</span>
        </button>
      </div>

      {/* Summary KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        <div className="p-5 rounded-2xl bg-white border border-gray-200 shadow-xs flex items-center justify-between">
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-500">Total Purchases</p>
            <p className="text-2xl font-black text-gray-900 mt-1">{loading ? '...' : orders.length}</p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center">
            <Receipt className="w-5 h-5" />
          </div>
        </div>

        <div className="p-5 rounded-2xl bg-white border border-gray-200 shadow-xs flex items-center justify-between">
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-500">Active Enrollments</p>
            <p className="text-2xl font-black text-gray-900 mt-1">{loading ? '...' : completedCount}</p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 border border-emerald-100 flex items-center justify-center">
            <CheckCircle className="w-5 h-5" />
          </div>
        </div>

        <div className="p-5 rounded-2xl bg-white border border-gray-200 shadow-xs flex items-center justify-between">
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-500">Total Spent</p>
            <p className="text-2xl font-black text-gray-900 mt-1">{loading ? '...' : `€${totalSpent.toFixed(2)}`}</p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 border border-amber-100 flex items-center justify-center">
            <CreditCard className="w-5 h-5" />
          </div>
        </div>
      </div>

      {/* Orders List Table */}
      <div className="bg-white rounded-2xl border border-gray-200 shadow-xs overflow-hidden">
        <div className="p-6 border-b border-gray-200 bg-gray-50/50 flex items-center justify-between">
          <h2 className="text-base font-bold text-gray-900">Your Invoices & Transactions</h2>
          <span className="text-xs font-semibold text-gray-500">Showing {orders.length} Records</span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm text-gray-700">
            <thead className="bg-gray-50 text-xs uppercase font-bold text-gray-500 border-b border-gray-200">
              <tr>
                <th className="px-6 py-4">Order ID & Date</th>
                <th className="px-6 py-4">Course(s)</th>
                <th className="px-6 py-4">Gateway</th>
                <th className="px-6 py-4">Amount</th>
                <th className="px-6 py-4">Status</th>
                <th className="px-6 py-4 text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-gray-500 text-sm font-semibold">
                    Loading your purchase history...
                  </td>
                </tr>
              ) : orders.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-gray-500 text-sm">
                    No purchase history found. Explore our course catalog to get started!
                  </td>
                </tr>
              ) : (
                orders.map((order) => {
                  const courseTitles = order.courses?.map((c) => c.title).join(', ') || 'German Course Package';

                  return (
                    <tr key={order._id} className="hover:bg-gray-50/80 transition">
                      <td className="px-6 py-4">
                        <div>
                          <p className="font-mono font-bold text-xs text-gray-900">#{order._id.slice(-8).toUpperCase()}</p>
                          <div className="flex items-center gap-1 text-[11px] text-gray-400 mt-0.5">
                            <Calendar className="w-3 h-3 text-gray-400" />
                            <span>{new Date(order.createdAt).toLocaleDateString()}</span>
                          </div>
                        </div>
                      </td>

                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <BookOpen className="w-4 h-4 text-amber-600 shrink-0" />
                          <span className="font-bold text-gray-900 line-clamp-1 max-w-xs">{courseTitles}</span>
                        </div>
                      </td>

                      <td className="px-6 py-4 capitalize font-semibold text-xs text-gray-600">
                        {order.gateway === 'bank_transfer' ? 'Bank Transfer' : order.gateway}
                      </td>

                      <td className="px-6 py-4 font-black text-gray-900">
                        €{order.amount ? order.amount.toFixed(2) : '0.00'}
                      </td>

                      <td className="px-6 py-4">
                        <span
                          className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-bold border ${order.status === 'completed'
                              ? 'bg-emerald-50 text-emerald-800 border-emerald-200'
                              : order.status === 'pending'
                                ? 'bg-amber-50 text-amber-800 border-amber-200'
                                : order.status === 'initiated'
                                  ? 'bg-blue-50 text-blue-800 border-blue-200'
                                  : 'bg-rose-50 text-rose-700 border-rose-200'
                            }`}
                        >
                          {order.status === 'completed' ? (
                            <>
                              <CheckCircle className="w-3 h-3 text-emerald-600" /> Access Granted
                            </>
                          ) : order.status === 'pending' ? (
                            <>
                              <Clock className="w-3 h-3 text-amber-600" /> Pending Review
                            </>
                          ) : (
                            <>
                              <AlertCircle className="w-3 h-3 text-blue-600" /> Initiated
                            </>
                          )}
                        </span>
                      </td>

                      <td className="px-6 py-4 text-right">
                        <button
                          onClick={() => setSelectedOrder(order)}
                          className="px-3 py-1.5 rounded-lg text-xs font-bold text-gray-700 hover:bg-gray-100 border border-gray-200 transition inline-flex items-center gap-1"
                        >
                          <Eye className="w-3.5 h-3.5 text-gray-500" />
                          <span>Details</span>
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Order Details Modal */}
      {selectedOrder && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-xs animate-fadeIn !m-0">
          <div className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl border border-gray-100 p-6 space-y-6">
            <button
              onClick={() => setSelectedOrder(null)}
              className="absolute top-5 right-5 p-2 rounded-full text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition"
            >
              <X className="w-5 h-5" />
            </button>

            <div className="border-b border-gray-100 pb-4">
              <span className="text-xs font-bold uppercase tracking-wider text-gray-400">Order Invoice Summary</span>
              <h3 className="text-xl font-extrabold text-gray-900 mt-1">
                #{selectedOrder._id.slice(-8).toUpperCase()}
              </h3>
            </div>

            <div className="space-y-4 text-sm">
              <div className="flex justify-between border-b border-gray-100 pb-2">
                <span className="text-gray-500 font-medium">Date & Time</span>
                <span className="font-bold text-gray-900">{new Date(selectedOrder.createdAt).toLocaleString()}</span>
              </div>

              <div className="flex justify-between border-b border-gray-100 pb-2">
                <span className="text-gray-500 font-medium">Payment Gateway</span>
                <span className="font-bold text-gray-900 uppercase">{selectedOrder.gateway}</span>
              </div>

              <div className="flex justify-between border-b border-gray-100 pb-2">
                <span className="text-gray-500 font-medium">Total Amount</span>
                <span className="font-black text-emerald-600 text-base">€{selectedOrder.amount.toFixed(2)}</span>
              </div>

              <div className="space-y-2 pt-2">
                <span className="text-xs font-bold uppercase tracking-wider text-gray-400">Enrolled Courses</span>
                <div className="space-y-2">
                  {selectedOrder.courses?.map((course) => (
                    <div key={course._id} className="p-3 rounded-xl bg-gray-50 border border-gray-200 flex justify-between items-center">
                      <span className="font-bold text-gray-900 text-xs">{course.title}</span>
                      <span className="text-xs font-extrabold text-amber-600 bg-amber-50 px-2 py-0.5 rounded border border-amber-200">
                        {course.level || 'German'}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="pt-2 flex justify-end">
              <button
                onClick={() => setSelectedOrder(null)}
                className="px-5 py-2.5 rounded-xl bg-gray-900 text-white font-extrabold text-xs hover:bg-black transition"
              >
                Close Summary
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
