import { useMemo, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { format } from "date-fns";
import { useQuery } from "@tanstack/react-query";
import {
  ArrowRight,
  Building2,
  CheckCircle2,
  Clock,
  DollarSign,
  Eye,
  LoaderCircle,
  Mail,
  MapPin,
  Package,
  Phone,
  Plus,
  Receipt,
  Truck,
  UploadCloud,
  X,
} from "lucide-react";

import {
  getCurrentCustomer,
  getMyInvoices,
  getMyShipments,
} from "@/lib/currentCustomer";
import { formatCurrency } from "@/pages/billing/invoices.mock";
import type { ShipmentStatus } from "@/pages/tracking/shipments.mock";
import type { InvoiceStatus } from "@/pages/billing/invoices.mock";
import {
  Button,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@edr/ui-common";
import { api } from "@/services/api";

const ACTIVE_STATUSES = [
  "DRAFT",
  "SUBMITTED",
  "PENDING_APPROVAL",
  "IN_TRANSIT",
];

export default function MyPortalPage() {
  const me = useMemo(() => getCurrentCustomer(), []);
  const myShipments = useMemo(() => getMyShipments(), []);
  const myInvoices = useMemo(() => getMyInvoices(), []);

  const navigate = useNavigate();

  const bookingsQuery = useQuery(
    api.bookings.list.queryOptions({
      input: { sortBy: "createdAt", sortOrder: "DESC" },
    }),
  );

  const myBookings = useMemo(
    () =>
      (bookingsQuery.data?.items ?? []).filter((b) =>
        ACTIVE_STATUSES.includes(b.status),
      ),
    [bookingsQuery.data],
  );

  const activeShipments = myShipments.filter((s) => s.status === "In Transit");
  const outstandingInvoices = myInvoices.filter(
    (inv) => inv.status === "Sent" || inv.status === "Overdue",
  );
  const [dismissed, setDismissed] = useState(false);
  const totalOutstanding = outstandingInvoices
    .filter((inv) => inv.currency === "USD")
    .reduce((sum, inv) => sum + inv.amount, 0);
  const totalSpent = myInvoices
    .filter((inv) => inv.status === "Paid" && inv.currency === "USD")
    .reduce((sum, inv) => sum + inv.amount, 0);

  const recentBookings = myBookings.slice(0, 5);
  const recentInvoices = [...myInvoices].slice(0, 4);

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="mx-auto max-w-7xl space-y-6">
        {/* Documents banner */}
        {!me.documentsComplete && !dismissed && (
          <div className="flex items-start gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
            <UploadCloud className="mt-0.5 h-5 w-5 shrink-0 text-amber-500" />
            <div className="flex-1">
              <p className="font-semibold">Upload your documents</p>
              <p className="mt-0.5 text-amber-700">
                To enable all account features, please upload your Business
                License, TIN Certificate, and National ID / Passport.
              </p>
              <Link
                to="/settings?tab=documents"
                className="mt-2 inline-flex items-center gap-1 font-medium text-amber-900 underline underline-offset-2 transition hover:text-amber-700"
              >
                Upload now
              </Link>
            </div>
            <button
              type="button"
              onClick={() => setDismissed(true)}
              className="shrink-0 rounded-lg p-1 text-amber-400 transition hover:bg-amber-100 hover:text-amber-600"
              aria-label="Dismiss"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        )}

        {/* Welcome banner */}
        <div className="overflow-hidden rounded-3xl bg-gradient-to-r from-[#059669] to-[#10B981] p-6 text-white shadow-sm">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div className="flex items-center gap-4">
              <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-white/15 text-2xl font-bold backdrop-blur">
                {me.company.charAt(0)}
              </div>
              <div>
                <p className="text-sm text-white/80">Welcome back</p>
                <h1 className="text-3xl font-bold tracking-tight">{me.name}</h1>
                <p className="mt-1 flex items-center gap-2 text-sm text-white/80">
                  <Building2 className="h-4 w-4" />
                  {me.company}
                  <span className="text-white/40">·</span>
                  <span className="rounded-full bg-white/15 px-2 py-0.5 text-xs">
                    {me.customerType}
                  </span>
                </p>
              </div>
            </div>

            <div className="flex flex-wrap items-center gap-2">
              <Link to="/bookings/new">
                <Button
                  variant="secondary"
                  className="bg-white text-[#10B981] hover:bg-muted"
                >
                  <Plus className="h-4 w-4" />
                  New Booking
                </Button>
              </Link>
              <Link to="/tracking">
                <Button
                  variant="outline"
                  className="border-white/40 text-white hover:bg-white/10"
                >
                  <Truck className="h-4 w-4" />
                  Track Shipment
                </Button>
              </Link>
            </div>
          </div>
        </div>

        {/* Active Shipments */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Active Shipments</CardTitle>
              <CardDescription>
                Live tracking for your in-flight cargo
              </CardDescription>
            </div>
            <Link
              to="/tracking"
              className="inline-flex items-center gap-1 text-sm font-medium text-primary transition hover:underline"
            >
              View all
              <ArrowRight className="h-4 w-4" />
            </Link>
          </CardHeader>

          <CardContent>
            {activeShipments.length === 0 ? (
              <p className="rounded-2xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                No shipments currently in transit.
              </p>
            ) : (
              <div className="grid gap-3 md:grid-cols-2">
                {activeShipments.slice(0, 4).map((shipment) => (
                  <div
                    key={shipment.id}
                    className="rounded-2xl border border-border p-4 transition hover:border-primary/20 hover:bg-primary/5"
                  >
                    <div className="flex items-center justify-between">
                      <span className="font-semibold text-foreground">
                        {shipment.reference}
                      </span>
                      <ShipmentBadge status={shipment.status} />
                    </div>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {shipment.originStation}
                      <ArrowRight className="mx-2 inline h-3 w-3 text-slate-400" />
                      {shipment.destinationStation}
                    </p>
                    <div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
                      <span className="flex items-center gap-1">
                        <MapPin className="h-3 w-3 text-primary" />
                        {shipment.currentLocation}
                      </span>
                      <span>ETA {shipment.eta}</span>
                    </div>
                    <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted">
                      <div
                        className="h-full rounded-full bg-primary transition-all"
                        style={{ width: `${shipment.progress}%` }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent bookings */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Recent Bookings</CardTitle>
              <CardDescription>Your latest freight requests</CardDescription>
            </div>
            <Link
              to="/bookings"
              className="inline-flex items-center gap-1 text-sm font-medium text-primary transition hover:underline"
            >
              View all
              <ArrowRight className="h-4 w-4" />
            </Link>
          </CardHeader>

          <CardContent className="px-0">
            {recentBookings.length === 0 ? (
              <p className="rounded-2xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                You haven't booked any freight yet.
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[600px] whitespace-nowrap text-left text-sm">
                  <thead className="text-xs text-muted-foreground">
                    <tr>
                      <th className="px-6 py-2 font-medium">Reference</th>
                      <th className="py-2 font-medium">Route</th>
                      <th className="py-2 font-medium">Cargo</th>
                      <th className="py-2 font-medium">Date</th>
                      <th className="py-2 font-medium">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recentBookings.map((booking) => (
                      <tr
                        key={booking.id}
                        className="border-t border-border transition hover:bg-primary/5 cursor-pointer"
                        onClick={() => navigate(`/bookings/${booking.id}`)}
                      >
                        <td className="px-6 py-3 font-medium text-foreground">
                          {booking.reference}
                        </td>
                        <td className="py-3 text-muted-foreground">
                          {booking.originYard?.label ?? booking.originYard?.code ?? "—"} → {booking.destinationYard?.label ?? booking.destinationYard?.code ?? "—"}
                        </td>
                        <td className="py-3 text-muted-foreground">
                          {booking.freightType === "CONTAINER" ? "Container" : booking.freightType}
                        </td>
                        <td className="py-3 text-muted-foreground">
                          {format(new Date(booking.createdAt), "MMM d, yyyy HH:mm")}
                        </td>
                        <td className="py-3">
                          <BookingBadge status={booking.status} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Invoices */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Recent Invoices</CardTitle>
              <CardDescription>
                {outstandingInvoices.length} outstanding · {myInvoices.length}{" "}
                total
              </CardDescription>
            </div>
            <Link
              to="/billing"
              className="inline-flex items-center gap-1 text-sm font-medium text-primary transition hover:underline"
            >
              View all
              <ArrowRight className="h-4 w-4" />
            </Link>
          </CardHeader>

          <CardContent>
            {recentInvoices.length === 0 ? (
              <p className="rounded-2xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                No invoices yet.
              </p>
            ) : (
              <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
                {recentInvoices.map((invoice) => (
                  <div
                    key={invoice.id}
                    className="rounded-2xl border border-border p-4 transition hover:border-primary/20 hover:bg-primary/5"
                  >
                    <div className="flex items-center justify-between">
                      <Receipt className="h-4 w-4 text-primary" />
                      <InvoiceBadge status={invoice.status} />
                    </div>
                    <p className="mt-0.5 pt-2 text-lg font-bold text-foreground">
                      {formatCurrency(invoice.amount, invoice.currency)}
                    </p>
                    <p className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
                      <Clock className="h-3 w-3" />
                      Due {invoice.dueDate}
                    </p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function ProfileRow({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  return (
    <div className="flex items-start gap-3">
      <div className="mt-0.5 text-primary">{icon}</div>
      <div className="flex-1">
        <p className="text-xs font-medium text-muted-foreground">{label}</p>
        <p className="mt-0.5 text-sm text-foreground">{value}</p>
      </div>
    </div>
  );
}

function ShipmentBadge({ status }: { status: ShipmentStatus }) {
  const styles: Record<ShipmentStatus, string> = {
    "In Transit": "bg-muted text-foreground",
    Delivered: "bg-primary/10 text-primary",
    Delayed: "bg-destructive/10 text-destructive",
  };
  return (
    <span
      className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${styles[status]}`}
    >
      {status}
    </span>
  );
}

function BookingBadge({ status }: { status: string }) {
  const styles: Record<string, string> = {
    DRAFT: "bg-amber-100 text-amber-700",
    SUBMITTED: "bg-primary/10 text-primary",
    PENDING_APPROVAL: "bg-muted text-foreground",
    IN_TRANSIT: "bg-muted text-foreground",
    COMPLETED: "bg-primary/10 text-primary",
    CANCELLED: "bg-destructive/10 text-destructive",
    REJECTED: "bg-destructive/10 text-destructive",
  };
  return (
    <span
      className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${styles[status] || "bg-muted text-muted-foreground"}`}
    >
      {status.replace(/_/g, " ")}
    </span>
  );
}

function InvoiceBadge({ status }: { status: InvoiceStatus }) {
  const styles: Record<InvoiceStatus, string> = {
    Draft: "bg-muted text-muted-foreground",
    Sent: "bg-primary/10 text-primary",
    Paid: "bg-primary/10 text-primary",
    Overdue: "bg-destructive/10 text-destructive",
    Cancelled: "bg-amber-100 text-amber-700",
  };
  return (
    <span
      className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${styles[status]}`}
    >
      {status}
    </span>
  );
}
