'use client';

import { useEffect, useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { CheckCircle, Package, ArrowRight, Loader2, Ghost, Bot, FileText, CreditCard, PiggyBank } from 'lucide-react';
import { VOCAB } from '@/lib/white-label/constants';

interface OrderDetails {
  orderNumber: string;
  customerEmail: string;
  total: number;
  status: string;
  items: Array<{
    product: { name: string };
    quantity: number;
    totalPrice: number;
  }>;
  invoiceId?: string;
  transactionId?: string;
  arRecordId?: string;
}

interface ExecutionStep {
  stage: string;
  timestamp: string;
  agent?: string;
  autonomous?: boolean;
}

function SuccessContent() {
  const searchParams = useSearchParams();
  const sessionId = searchParams.get('session_id');
  const [order, setOrder] = useState<OrderDetails | null>(null);
  const [executionSteps, setExecutionSteps] = useState<ExecutionStep[]>([]);
  const [loading, setLoading] = useState(true);
  const [agentProgress, setAgentProgress] = useState(0);

  useEffect(() => {
    if (!sessionId) {
      setLoading(false);
      return;
    }

    // Fetch order details
    const fetchOrder = async () => {
      try {
        const res = await fetch(`/api/swag/orders/by-session?sessionId=${sessionId}`);
        if (res.ok) {
          const data = await res.json();
          setOrder(data.order);
          
          // Fetch execution details
          if (data.order?.id) {
            const execRes = await fetch(`/api/order-to-cash/execution?orderId=${data.order.id}`);
            if (execRes.ok) {
              const execData = await execRes.json();
              setExecutionSteps(execData.stageHistory || []);
            }
          }
        }
      } catch (error) {
        console.error('Error fetching order:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchOrder();

    // Simulate agent progress animation
    const interval = setInterval(() => {
      setAgentProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          return 100;
        }
        return prev + 2;
      });
    }, 50);

    return () => clearInterval(interval);
  }, [sessionId]);

  const formatCurrency = (amount: number) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);

  const agentStages = [
    { icon: CreditCard, label: 'Payment Confirmed', done: agentProgress > 20 },
    { icon: FileText, label: 'Invoice Generated', done: agentProgress > 40 },
    { icon: PiggyBank, label: 'Transaction Recorded', done: agentProgress > 60 },
    { icon: Bot, label: 'AR Updated', done: agentProgress > 80 },
    { icon: Package, label: 'Ready for Fulfillment', done: agentProgress >= 100 },
  ];

  return (
    <div className="min-h-screen bg-brand-bg py-12 px-4">
      <div className="max-w-3xl mx-auto">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-8 h-8 text-brand animate-spin" />
          </div>
        ) : (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="space-y-8"
          >
            {/* Success Header */}
            <div className="text-center">
              <motion.div
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.2, type: 'spring' }}
                className="w-20 h-20 mx-auto bg-gradient-to-br from-green-400 to-brand-deep rounded-full flex items-center justify-center mb-6"
              >
                <CheckCircle className="w-10 h-10 text-white" />
              </motion.div>
              <h1 className="text-3xl font-bold text-white mb-2">Order Confirmed!</h1>
              <p className="text-gray-400">
                Your order {order?.orderNumber} has been placed successfully.
              </p>
            </div>

            {/* Autonomous Processing Card */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
              className="glass-card p-6 border border-brand-secondary/30 relative overflow-hidden"
            >
              <div className="absolute top-0 left-0 w-full h-1 bg-gray-800">
                <motion.div
                  className="h-full bg-gradient-to-r from-brand-secondary to-brand-deep"
                  initial={{ width: 0 }}
                  animate={{ width: `${agentProgress}%` }}
                  transition={{ duration: 0.5 }}
                />
              </div>

              <div className="flex items-center gap-3 mb-6">
                <Ghost className="w-6 h-6 text-brand-secondary-light" />
                <h2 className="text-lg font-semibold text-white">{VOCAB.agents} Processing</h2>
                <span className="text-sm text-brand-secondary-light ml-auto">
                  {agentProgress >= 100 ? 'Complete' : 'Working...'}
                </span>
              </div>

              <div className="grid grid-cols-5 gap-2">
                {agentStages.map((stage, idx) => (
                  <motion.div
                    key={idx}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4 + idx * 0.1 }}
                    className={`text-center p-3 rounded-lg transition-all ${
                      stage.done ? 'bg-brand-secondary/20' : 'bg-white/5'
                    }`}
                  >
                    <stage.icon
                      className={`w-6 h-6 mx-auto mb-2 transition-colors ${
                        stage.done ? 'text-brand' : 'text-gray-500'
                      }`}
                    />
                    <span
                      className={`text-xs transition-colors ${
                        stage.done ? 'text-white' : 'text-gray-500'
                      }`}
                    >
                      {stage.label}
                    </span>
                  </motion.div>
                ))}
              </div>

              <p className="text-xs text-gray-500 mt-4 text-center">
                Zero human intervention required. Your order is being processed autonomously.
              </p>
            </motion.div>

            {/* Order Details */}
            {order && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.5 }}
                className="glass-card p-6 border border-white/10"
              >
                <h2 className="text-lg font-semibold text-white mb-4">Order Details</h2>
                
                <div className="space-y-4">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Order Number</span>
                    <span className="text-white font-mono">{order.orderNumber}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Confirmation sent to</span>
                    <span className="text-white">{order.customerEmail}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Status</span>
                    <span className="text-brand capitalize">{order.status}</span>
                  </div>

                  <div className="border-t border-white/10 pt-4">
                    {order.items.map((item, idx) => (
                      <div key={idx} className="flex justify-between text-sm py-2">
                        <span className="text-gray-300">
                          {item.product.name} × {item.quantity}
                        </span>
                        <span className="text-white">{formatCurrency(item.totalPrice)}</span>
                      </div>
                    ))}
                  </div>

                  <div className="border-t border-white/10 pt-4 flex justify-between">
                    <span className="text-white font-semibold">Total</span>
                    <span className="text-xl font-bold text-brand">
                      {formatCurrency(order.total)}
                    </span>
                  </div>
                </div>

                {/* System Records */}
                {(order.invoiceId || order.transactionId || order.arRecordId) && (
                  <div className="mt-6 p-4 bg-white/5 rounded-lg">
                    <h3 className="text-sm font-medium text-gray-300 mb-2">System Records Created</h3>
                    <div className="text-xs text-gray-500 space-y-1">
                      {order.invoiceId && <div>✓ Invoice: INV-{order.orderNumber}</div>}
                      {order.transactionId && <div>✓ Transaction recorded</div>}
                      {order.arRecordId && <div>✓ AR entry updated</div>}
                    </div>
                  </div>
                )}
              </motion.div>
            )}

            {/* Actions */}
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Link
                href="/swag-store"
                className="px-6 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg flex items-center justify-center gap-2 transition-colors"
              >
                <Package className="w-5 h-5" />
                Continue Shopping
              </Link>
              <Link
                href="/ghost-control/operations"
                className="px-6 py-3 bg-gradient-to-r from-brand-secondary-deep to-brand-deep hover:from-brand-secondary hover:to-brand-deep text-white rounded-lg flex items-center justify-center gap-2 transition-all"
              >
                View in Operations
                <ArrowRight className="w-5 h-5" />
              </Link>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}

export default function SuccessPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-brand-bg flex items-center justify-center">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      }
    >
      <SuccessContent />
    </Suspense>
  );
}
