'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import {
  ShoppingCart,
  CheckCircle2,
  XCircle,
  Search,
  Filter,
  Eye,
  FileText,
  Clock,
  RefreshCw,
  Globe,
  Server,
  Zap,
} from 'lucide-react';
import { Order } from '@/types';
import AdminSidebar from '@/components/admin/AdminSidebar';

export default function AdminOrdersClient({ initialOrders }: { initialOrders: Order[] }) {
  const [orders, setOrders] = useState<Order[]>(initialOrders);
  const [statusFilter, setStatusFilter] = useState<'all' | 'pending' | 'completed' | 'rejected'>('all');
  const [search, setSearch] = useState('');
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);

  const fetchLatestOrders = async () => {
    setIsRefreshing(true);
    try {
      const res = await fetch('/api/orders');
      const data = await res.json();
      if (data.orders) {
        setOrders(data.orders);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleUpdateStatus = async (orderId: string, status: 'completed' | 'rejected') => {
    setLoadingId(orderId);
    try {
      const res = await fetch(`/api/orders/${orderId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      });
      const data = await res.json();
      if (data.order) {
        setOrders(orders.map((o) => (o.id === orderId ? data.order : o)));
      }
    } catch {
      setOrders(orders.map((o) => (o.id === orderId ? { ...o, payment_status: status } : o)));
    } finally {
      setLoadingId(null);
    }
  };

  const filteredOrders = orders.filter((o) => {
    if (statusFilter !== 'all' && o.payment_status !== statusFilter) return false;
    if (search.trim()) {
      const q = search.toLowerCase();
      const matchNum = o.order_number.toLowerCase().includes(q);
      const matchName = o.customer_name.toLowerCase().includes(q);
      const matchEmail = o.customer_email.toLowerCase().includes(q);
      const matchTrx = o.trx_id?.toLowerCase().includes(q);
      if (!matchNum && !matchName && !matchEmail && !matchTrx) return false;
    }
    return true;
  });

  return (
    <div className="py-8 md:py-12 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-7xl">
        <div className="flex flex-col lg:flex-row gap-8 items-start">
          <AdminSidebar />

          <div className="flex-1 space-y-6 w-full">
            {/* Header */}
            <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-gray-100 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <h1 className="text-2xl sm:text-3xl font-black text-gray-900">
                  Orders & Transaction Verification
                </h1>
                <p className="text-xs sm:text-sm text-gray-500 mt-1">
                  Inspect manual bKash, Nagad, Rocket, Upay, and Crypto payments. Approve to activate customer licenses immediately.
                </p>
              </div>

              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={fetchLatestOrders}
                  disabled={isRefreshing}
                  className="px-4 py-2 bg-gray-50 hover:bg-gray-100 border border-gray-200 text-gray-700 font-bold text-xs rounded-xl transition flex items-center gap-1.5"
                >
                  <RefreshCw className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin text-indigo-600' : ''}`} />
                  <span>{isRefreshing ? 'Refreshing...' : 'Refresh Orders'}</span>
                </button>
              </div>
            </div>

            {/* Filters Toolbar */}
            <div className="bg-white rounded-2xl p-4 sm:p-5 shadow-sm border border-gray-100 flex flex-col sm:flex-row items-center justify-between gap-4">
              {/* Status Segmented Buttons */}
              <div className="flex items-center gap-1.5 bg-gray-100 p-1 rounded-xl w-full sm:w-auto">
                {(['all', 'pending', 'completed', 'rejected'] as const).map((st) => (
                  <button
                    key={st}
                    onClick={() => setStatusFilter(st)}
                    className={`flex-1 sm:flex-initial px-3.5 py-1.5 rounded-lg text-xs font-bold capitalize transition ${
                      statusFilter === st
                        ? 'bg-white text-gray-900 shadow-sm'
                        : 'text-gray-600 hover:text-gray-900'
                    }`}
                  >
                    {st}
                  </button>
                ))}
              </div>

              {/* Search */}
              <div className="relative w-full sm:w-72">
                <input
                  type="text"
                  placeholder="Search Order#, Name, TrxID..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full text-xs py-2 pl-9 pr-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
                <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
              </div>
            </div>

            {/* Orders Table */}
            <div className="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead className="bg-gray-50/80 text-gray-400 font-bold uppercase tracking-wider border-b border-gray-100">
                    <tr>
                      <th className="px-6 py-4">Order Ref</th>
                      <th className="px-4 py-4">Customer Details</th>
                      <th className="px-4 py-4">Payment & TrxID</th>
                      <th className="px-4 py-4">Ordered Items & Domain</th>
                      <th className="px-4 py-4">Total Amount</th>
                      <th className="px-4 py-4">Status</th>
                      <th className="px-6 py-4 text-right">Verification Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 text-gray-700">
                    {filteredOrders.map((order) => (
                      <tr key={order.id} className="hover:bg-gray-50/50 transition">
                        <td className="px-6 py-4">
                          <span className="font-mono font-bold text-sm text-gray-900 block">
                            #{order.order_number}
                          </span>
                          <span className="text-[11px] text-gray-400">
                            {new Date(order.created_at).toLocaleDateString()}
                          </span>
                        </td>

                        <td className="px-4 py-4 space-y-0.5">
                          <strong className="text-gray-900 block font-bold">
                            {order.customer_name}
                          </strong>
                          <span className="text-gray-500 block">{order.customer_email}</span>
                          {order.customer_phone && (
                            <span className="text-[11px] text-gray-400 block font-mono">
                              {order.customer_phone}
                            </span>
                          )}
                        </td>

                        <td className="px-4 py-4 space-y-1">
                          <span className="px-2 py-0.5 rounded text-[10px] font-extrabold uppercase bg-gray-100 text-gray-700 inline-block">
                            {order.payment_method}
                          </span>
                          <p className="font-mono font-bold text-indigo-600 text-xs">
                            Trx: {order.trx_id || 'Instant / Free'}
                          </p>
                          {order.sender_number && (
                            <p className="text-[11px] text-gray-500 font-mono">
                              Sender: <strong>{order.sender_number}</strong>
                            </p>
                          )}
                        </td>

                        <td className="px-4 py-4 space-y-1 max-w-xs">
                          {order.items.map((it, i) => (
                            <div key={i} className="text-[11px]">
                              <span className="font-bold text-gray-800 line-clamp-1">{it.product_title}</span>
                              <div className="flex items-center gap-2 text-[10px] text-gray-400">
                                <span className="uppercase text-indigo-600 font-bold">{it.plan_name}</span>
                                {it.domain && <span className="font-mono text-gray-600 truncate">🌐 {it.domain}</span>}
                              </div>
                            </div>
                          ))}
                        </td>

                        <td className="px-4 py-4">
                          <span className="font-black text-sm text-gray-900">
                            ${order.total.toFixed(2)}
                          </span>
                        </td>

                        <td className="px-4 py-4">
                          <span
                            className={`inline-flex items-center gap-1 font-bold text-xs uppercase px-2.5 py-0.5 rounded-full ${
                              order.payment_status === 'completed'
                                ? 'bg-emerald-100 text-emerald-700'
                                : order.payment_status === 'pending'
                                ? 'bg-amber-100 text-amber-700 animate-pulse'
                                : 'bg-red-100 text-red-700'
                            }`}
                          >
                            {order.payment_status}
                          </span>
                        </td>

                        <td className="px-6 py-4 text-right">
                          <div className="flex items-center justify-end gap-2">
                            {order.payment_status === 'pending' ? (
                              <>
                                <button
                                  type="button"
                                  disabled={loadingId === order.id}
                                  onClick={() => handleUpdateStatus(order.id, 'completed')}
                                  className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl text-xs flex items-center gap-1.5 shadow-sm transition active:scale-95"
                                  title="Approve Payment & Activate Licenses"
                                >
                                  <CheckCircle2 className="w-3.5 h-3.5" />
                                  <span>{loadingId === order.id ? 'Activating...' : 'Approve & Activate'}</span>
                                </button>
                                <button
                                  type="button"
                                  disabled={loadingId === order.id}
                                  onClick={() => handleUpdateStatus(order.id, 'rejected')}
                                  className="p-1.5 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl transition"
                                  title="Reject Order"
                                >
                                  <XCircle className="w-4 h-4" />
                                </button>
                              </>
                            ) : (
                              <button
                                type="button"
                                disabled={loadingId === order.id}
                                onClick={() => handleUpdateStatus(order.id, order.payment_status === 'completed' ? 'rejected' : 'completed')}
                                className="px-2.5 py-1 text-[11px] font-semibold text-gray-500 hover:text-gray-800 bg-gray-100 hover:bg-gray-200 rounded-lg transition"
                              >
                                {order.payment_status === 'completed' ? 'Revoke' : 'Re-Activate'}
                              </button>
                            )}

                            <Link
                              href={`/order-success/${order.id}`}
                              target="_blank"
                              className="p-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition"
                              title="View Invoice"
                            >
                              <FileText className="w-4 h-4" />
                            </Link>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
