import { useEffect, useState } from "react";
import { Link } from "@inertiajs/react";
import { CheckCircle2, Calendar, MapPin, Users, HardHat, Navigation, FileText, Mail, Loader2, ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import SeoHead from "@/components/SeoHead";
import { grossCents } from "@/lib/vat";

// Stub — tenant context isn't ported yet.
const useTenant = () => ({
  isTenantMode: false,
  subdomain: null as string | null,
  isLoading: false,
  branding: null as { company_id?: string | null } | null,
  companyName: null as string | null,
});
const useTenantHref = () => (path: string) => path;

interface OrderDetails {
  id: string;
  customer_name: string;
  customer_email: string;
  customer_phone: string | null;
  num_delegates: number;
  price_cents: number;
  start_date: string;
  status: string;
  payment_method: string;
  created_at: string;
  courses: {
    id: string;
    title: string;
    days: number;
    ppe_requirements: string | null;
    location_name: string | null;
    location_details: string | null;
    facilities: string | null;
    who_attends: string | null;
    certification: string | null;
    slug: string;
  };
  venues: {
    name: string;
    address: string | null;
    city: string | null;
    postcode: string | null;
  } | null;
  trainers: {
    first_name: string;
    last_name: string;
  } | null;
  booking_delegates: {
    id: string;
    first_name: string;
    last_name: string;
    email: string | null;
  }[];
}

const CheckoutSuccessPage = () => {
  const searchParams = new URLSearchParams(window.location.search);
  // Accept either ?order_id=xxx (single) or ?order_ids=a,b,c (multi-cart checkout).
  const idsParam = searchParams.get("order_ids");
  const singleId = searchParams.get("order_id") ?? searchParams.get("session_id");
  const orderIds = idsParam
    ? idsParam.split(",").map((s) => s.trim()).filter(Boolean)
    : (singleId ? [singleId] : []);
  const { isTenantMode: _isTenantMode } = useTenant();
  const tenantHref = useTenantHref();
  const [orders, setOrders] = useState<OrderDetails[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (orderIds.length === 0) {
      setError("No order ID provided.");
      setLoading(false);
      return;
    }
    (async () => {
      try {
        const results = await Promise.all(
          orderIds.map(async (id) => {
            const res = await fetch(`/api/marketplace/orders/${encodeURIComponent(id)}`);
            if (!res.ok) throw new Error("Order not found");
            const data = await res.json();
            if (!data) throw new Error("Order not found");
            return data as OrderDetails;
          }),
        );
        setOrders(results);
      } catch (e: any) {
        setError(e.message || "Failed to load order");
      } finally {
        setLoading(false);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [idsParam, singleId]);

  // Single-order legacy path keeps the rich layout. Multi-order renders a list.
  const order = orders[0] ?? null;

  const formatDate = (dateStr: string | null | undefined) => {
    if (!dateStr) return "Online — start anytime";
    return new Date(dateStr + "T00:00:00").toLocaleDateString("en-GB", {
      weekday: "long", day: "numeric", month: "long", year: "numeric",
    });
  };

  const formatEndDate = (startStr: string | null | undefined, days: number) => {
    if (!startStr) return "—";
    const d = new Date(startStr + "T00:00:00");
    d.setDate(d.getDate() + days - 1);
    return d.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" });
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error || !order) {
    return (
      <div className="min-h-screen bg-white">
        <SeoHead />
        <Navbar />
        <div className="container mx-auto px-4 py-24 text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-4">Order Not Found</h1>
          <p className="text-gray-500 mb-6">{error}</p>
          <Link href={tenantHref("/courses")}>
            <Button>Browse Courses</Button>
          </Link>
        </div>
        <Footer />
      </div>
    );
  }

  // Multi-order success view (cart checkout with N courses).
  if (orders.length > 1) {
    const totalPaid = orders.reduce((s, o) => s + grossCents(o.price_cents), 0);
    const totalDelegates = orders.reduce((s, o) => s + o.num_delegates, 0);
    return (
      <div className="min-h-screen bg-gray-50">
        <SeoHead />
        <Navbar />
        <div className="pt-20 pb-16">
          <div className="container mx-auto px-4 max-w-3xl">
            <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-8 mb-6 text-center">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle2 className="w-9 h-9 text-green-600" />
              </div>
              <h1 className="text-2xl font-bold text-gray-900 mb-1">{orders.length} Bookings Confirmed!</h1>
              <p className="text-gray-500 text-sm mb-4">
                Confirmation emails for each booking have been sent to{" "}
                <span className="font-medium text-gray-700">{order.customer_email}</span>
              </p>
              <div className="grid grid-cols-3 gap-3 mt-4 text-sm">
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-xs text-gray-500">Bookings</p>
                  <p className="font-bold text-gray-900">{orders.length}</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-xs text-gray-500">Delegates</p>
                  <p className="font-bold text-gray-900">{totalDelegates}</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-xs text-gray-500">Total Paid</p>
                  <p className="font-bold text-gray-900">£{(totalPaid / 100).toFixed(2)}</p>
                </div>
              </div>
            </div>

            <div className="space-y-4">
              {orders.map((o) => (
                <div key={o.id} className="bg-white rounded-2xl border border-gray-200 shadow-sm p-5">
                  <div className="flex items-start justify-between gap-3 mb-3">
                    <div className="min-w-0">
                      <h3 className="font-semibold text-gray-900 truncate">{o.courses.title}</h3>
                      <p className="text-xs text-gray-500 font-mono">
                        Ref: {o.id.slice(0, 8).toUpperCase()}
                      </p>
                    </div>
                    <Badge className="bg-green-50 text-green-700 border border-green-200 capitalize shrink-0">
                      {o.status}
                    </Badge>
                  </div>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm">
                    <div>
                      <p className="text-xs text-gray-500">Start</p>
                      <p className="font-medium text-gray-900">{formatDate(o.start_date)}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">Duration</p>
                      <p className="font-medium text-gray-900">{o.courses.days} day{o.courses.days > 1 ? "s" : ""}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">Delegates</p>
                      <p className="font-medium text-gray-900">{o.num_delegates}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">Amount (incl. VAT)</p>
                      <p className="font-medium text-gray-900">£{(grossCents(o.price_cents) / 100).toFixed(2)}</p>
                    </div>
                  </div>
                  {o.venues && (
                    <div className="mt-3 pt-3 border-t border-gray-100 flex items-center gap-2 text-xs text-gray-500">
                      <MapPin className="w-3 h-3" />
                      {o.venues.name}{o.venues.city ? `, ${o.venues.city}` : ""}
                    </div>
                  )}
                </div>
              ))}
            </div>

            <div className="bg-blue-50 border border-blue-200 rounded-2xl p-6 mt-6">
              <div className="flex items-start gap-3">
                <Mail className="w-5 h-5 text-blue-600 shrink-0 mt-0.5" />
                <div>
                  <p className="font-semibold text-blue-900 mb-1">Pre-Course Forms</p>
                  <p className="text-sm text-blue-700">
                    Each delegate has been emailed a personal link to complete their TD-02 form. PPE requirements and joining instructions are included in each booking's confirmation email.
                  </p>
                </div>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-3 mt-6">
              <Link href={tenantHref("/courses")} className="flex-1">
                <Button variant="outline" className="w-full border-gray-300 text-gray-700 hover:bg-gray-50">
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  Back to Courses
                </Button>
              </Link>
              <Link href={tenantHref("/delegate-dashboard")} className="flex-1">
                <Button className="w-full bg-primary text-primary-foreground hover:bg-primary/90">
                  <Users className="w-4 h-4 mr-2" />
                  View My Dashboard
                </Button>
              </Link>
            </div>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  const course = order.courses;
  const venue = order.venues;
  const ppeItems = (() => {
    const raw = course.ppe_requirements?.trim();
    if (!raw) return [];
    if (raw.startsWith("[")) {
      try {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) return parsed.map(String).map(s => s.trim()).filter(Boolean);
      } catch { /* fall through to delimited split */ }
    }
    return raw.split(/\n|,|;/).map(s => s.trim()).filter(Boolean);
  })();

  return (
    <div className="min-h-screen bg-gray-50">
      <SeoHead />
      <Navbar />

      <div className="pt-20 pb-16">
        <div className="container mx-auto px-4 max-w-3xl">

          {/* Success Header */}
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-8 mb-6 text-center">
            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle2 className="w-9 h-9 text-green-600" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 mb-1">Booking Confirmed!</h1>
            <p className="text-gray-500 text-sm mb-4">
              A confirmation email with your invoice has been sent to{" "}
              <span className="font-medium text-gray-700">{order.customer_email}</span>
            </p>
            <div className="inline-flex items-center gap-2 bg-green-50 border border-green-200 rounded-full px-4 py-1.5">
              <span className="w-2 h-2 bg-green-500 rounded-full" />
              <span className="text-green-700 text-sm font-medium capitalize">{order.status}</span>
            </div>
          </div>

          {/* Course & Booking Summary */}
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 mb-6">
            <h2 className="text-base font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <FileText className="w-4 h-4 text-primary" />
              Booking Summary
            </h2>
            <div className="space-y-3 text-sm">
              <div className="flex justify-between items-start">
                <span className="text-gray-500">Course</span>
                <span className="font-semibold text-gray-900 text-right max-w-xs">{course.title}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Booking Ref</span>
                <span className="font-mono text-xs text-gray-700 bg-gray-100 px-2 py-0.5 rounded">{order.id.slice(0, 8).toUpperCase()}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Start Date</span>
                <span className="font-medium text-gray-900">{formatDate(order.start_date)}</span>
              </div>
              {course.days > 1 && (
                <div className="flex justify-between">
                  <span className="text-gray-500">End Date</span>
                  <span className="font-medium text-gray-900">{formatEndDate(order.start_date, course.days)}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-gray-500">Duration</span>
                <span className="font-medium text-gray-900">{course.days} day{course.days > 1 ? "s" : ""}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Delegates</span>
                <span className="font-medium text-gray-900">{order.num_delegates}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Total Paid (incl. VAT)</span>
                <span className="font-bold text-gray-900">£{(grossCents(order.price_cents) / 100).toFixed(2)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Payment Method</span>
                <span className="font-medium text-gray-900 capitalize">{order.payment_method}</span>
              </div>
            </div>

            {/* Delegates */}
            {order.booking_delegates?.length > 0 && (
              <div className="mt-4 pt-4 border-t border-gray-100">
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Registered Delegates</p>
                <div className="space-y-1">
                  {order.booking_delegates.map((d) => (
                    <div key={d.id} className="flex items-center justify-between text-sm">
                      <span className="text-gray-800">{d.first_name} {d.last_name}</span>
                      {d.email && <span className="text-gray-400 text-xs">{d.email}</span>}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Joining Instructions */}
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 mb-6">
            <h2 className="text-base font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <Navigation className="w-4 h-4 text-primary" />
              Joining Instructions
            </h2>

            {venue ? (
              <div className="space-y-3 text-sm">
                <div className="flex items-start gap-3">
                  <MapPin className="w-4 h-4 text-gray-400 mt-0.5 shrink-0" />
                  <div>
                    <p className="font-semibold text-gray-900">{venue.name}</p>
                    {venue.address && <p className="text-gray-500">{venue.address}</p>}
                    {(venue.city || venue.postcode) && (
                      <p className="text-gray-500">
                        {[venue.city, venue.postcode].filter(Boolean).join(", ")}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            ) : course.location_name ? (
              <div className="flex items-start gap-3 text-sm">
                <MapPin className="w-4 h-4 text-gray-400 mt-0.5 shrink-0" />
                <div>
                  <p className="font-semibold text-gray-900">{course.location_name}</p>
                  {course.location_details && (
                    <p className="text-gray-500 mt-1 whitespace-pre-line">{course.location_details}</p>
                  )}
                </div>
              </div>
            ) : (
              <p className="text-sm text-gray-500 italic">
                Joining instructions will be emailed to all delegates closer to the course date.
              </p>
            )}

            {course.facilities && (
              <div className="mt-4 pt-4 border-t border-gray-100">
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Facilities & Amenities</p>
                <p className="text-sm text-gray-700 whitespace-pre-line">{course.facilities}</p>
              </div>
            )}

            {order.trainers && (
              <div className="mt-4 pt-4 border-t border-gray-100 flex items-center gap-3 text-sm">
                <Users className="w-4 h-4 text-gray-400 shrink-0" />
                <div>
                  <span className="text-gray-500">Trainer: </span>
                  <span className="font-medium text-gray-900">
                    {order.trainers.first_name} {order.trainers.last_name}
                  </span>
                </div>
              </div>
            )}

            <div className="mt-4 pt-4 border-t border-gray-100">
              <div className="flex items-start gap-3 text-sm">
                <Calendar className="w-4 h-4 text-gray-400 mt-0.5 shrink-0" />
                <div>
                  <p className="font-medium text-gray-900">Registration</p>
                  <p className="text-gray-500">Please arrive 15 minutes before the scheduled start time to complete registration.</p>
                </div>
              </div>
            </div>
          </div>

          {/* PPE Requirements */}
          {ppeItems.length > 0 && (
            <div className="bg-amber-50 border border-amber-200 rounded-2xl p-6 mb-6">
              <h2 className="text-base font-semibold text-gray-900 mb-1 flex items-center gap-2">
                <HardHat className="w-4 h-4 text-amber-600" />
                PPE Requirements
              </h2>
              <p className="text-xs text-amber-700 mb-4">
                The following PPE is required for this course. Please ensure all delegates arrive with the correct equipment.
              </p>
              <div className="flex flex-wrap gap-2">
                {ppeItems.map((item, i) => (
                  <Badge key={i} className="bg-amber-100 text-amber-800 border border-amber-300 font-medium">
                    {item}
                  </Badge>
                ))}
              </div>
            </div>
          )}

          {/* Pre-Course Form Notice */}
          <div className="bg-blue-50 border border-blue-200 rounded-2xl p-6 mb-6">
            <div className="flex items-start gap-3">
              <Mail className="w-5 h-5 text-blue-600 shrink-0 mt-0.5" />
              <div>
                <p className="font-semibold text-blue-900 mb-1">Pre-Course Medical Form</p>
                <p className="text-sm text-blue-700">
                  Each delegate has been emailed a personal link to complete their Medical Requirements &amp; Adjustments form (TD-02).
                  Please ensure all delegates complete this before the course date.
                </p>
              </div>
            </div>
          </div>

          {/* Actions */}
          <div className="flex flex-col sm:flex-row gap-3">
            <Link href={tenantHref("/courses")} className="flex-1">
              <Button variant="outline" className="w-full border-gray-300 text-gray-700 hover:bg-gray-50">
                <ArrowLeft className="w-4 h-4 mr-2" />
                Back to Courses
              </Button>
            </Link>
            <Link href={tenantHref("/delegate-dashboard")} className="flex-1">
              <Button className="w-full bg-primary text-primary-foreground hover:bg-primary/90">
                <Users className="w-4 h-4 mr-2" />
                View My Dashboard
              </Button>
            </Link>
          </div>

        </div>
      </div>

      <Footer />
    </div>
  );
};

export default CheckoutSuccessPage;
