import { useMemo, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
  ArrowRight,
  Clock,
  Eye,
  Filter,
  MoreHorizontal,
  Package,
  Plus,
  Search,
  Truck,
} from "lucide-react";

import { api } from "@/services/api";
import type { Freight } from "@edr/types";
import {
  DataTable,
  DataTableFooter,
  type ColumnDef,
  usePagination,
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Input,
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from "@edr/ui-common";

export default function MyBookings() {
  const navigate = useNavigate();
  const { pagination, setPagination } = usePagination({ pageSize: 10 });
  const [searchTerm, setSearchTerm] = useState("");

  const { data, isLoading, isError } = useQuery(
    api.bookings.list.queryOptions(),
  );

  const bookings = data?.items ?? [];

  const filteredData = useMemo(() => {
    return bookings.filter((b) => {
      const term = searchTerm.toLowerCase();
      return (
        b.reference.toLowerCase().includes(term) ||
        (b.originYard?.label ?? b.originYard?.code ?? "").toLowerCase().includes(term) ||
        (b.destinationYard?.label ?? b.destinationYard?.code ?? "").toLowerCase().includes(term) ||
        b.status.toLowerCase().includes(term)
      );
    });
  }, [bookings, searchTerm]);

  const total = filteredData.length;
  const pageCount = Math.ceil(total / pagination.pageSize);
  const start = pagination.pageIndex * pagination.pageSize;
  const end = Math.min(start + pagination.pageSize, total);

  const paginatedData = useMemo(() => filteredData.slice(start, end), [filteredData, start, end]);

  const activeCount = useMemo(() => {
    return bookings.filter(
      (b) => b.status === "CONFIRMED" || b.status === "IN_TRANSIT",
    ).length;
  }, [bookings]);

  const pendingCount = useMemo(() => {
    return bookings.filter((b) => b.status === "DRAFT").length;
  }, [bookings]);

  const columns: ColumnDef<Freight.IBooking>[] = [
    {
      accessorKey: "reference",
      header: "Reference",
      cell: ({ row }) => {
        const booking = row.original;
        return (
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary text-primary-foreground">
              <Package className="h-5 w-5" />
            </div>
            <div>
              <p className="font-medium text-foreground">{booking.reference}</p>
              <p className="text-sm text-muted-foreground">{booking.scheduledDate ?? booking.createdAt}</p>
            </div>
          </div>
        );
      },
    },
    {
      id: "route",
      header: "Route",
      cell: ({ row }) => (
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <span>{row.original.originYard?.label ?? row.original.originYard?.code ?? "—"}</span>
          <ArrowRight className="text-muted-foreground" />
          <span>{row.original.destinationYard?.label ?? row.original.destinationYard?.code ?? "—"}</span>
        </div>
      ),
    },
    {
      id: "cargo",
      header: "Cargo",
      cell: ({ row }) => {
        const b = row.original;
        const containerCount = b.containers?.reduce((sum, c) => sum + c.qty, 0) ?? 0;
        const containerType = b.containers?.[0]?.type ?? null;
        return (
          <div className="text-sm text-muted-foreground">
            <p>{b.freightType === "BULK" ? "Bulk" : "Break Bulk"}</p>
            <p className="text-xs text-muted-foreground">
              {containerType && containerCount > 0 ? `${containerCount} × ${containerType} · ` : ""}{b.cargoTotalWeightVgm}t
            </p>
          </div>
        );
      },
    },
    {
      id: "transportMode",
      header: "Transport",
      cell: ({ row }) => (
        <span className="text-sm text-muted-foreground">
          {row.original.serviceType === "RAIL_AND_FORWARDING" ? "Rail & Forwarding" : "Rail"}
        </span>
      ),
    },
    {
      accessorKey: "status",
      header: "Status",
      cell: ({ row }) => <StatusBadge status={row.original.status} />,
    },
    {
      id: "actions",
      size: 40,
      cell: ({ row }) => {
        const booking = row.original;
        return (
          <div
            className="flex justify-end"
            onClick={(e) => e.stopPropagation()}
          >
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="icon">
                  <MoreHorizontal />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onClick={() => navigate(`/bookings/${booking.id}`)}
                >
                  <Eye />
                  View
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        );
      },
    },
  ];

  const dataTableStatus = isLoading ? "loading" : isError ? "error" : "success";

  return (
    <div className="min-h-screen p-6">
      <div className="space-y-6">
        <Card className="p-6 flex-row justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-foreground">
              My Bookings
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              View and manage your freight booking requests.
            </p>
          </div>

          <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center">
            <div className="relative w-full sm:w-80">
              <Search className="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
              <Input
                type="search"
                placeholder="Search bookings..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-8!"
              />
            </div>

            <Link to="/bookings/new">
              <Button>
                <Plus />
                New Booking
              </Button>
            </Link>
          </div>
        </Card>

        <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardContent className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Total Bookings</p>
                <h3 className="mt-2 text-3xl font-bold text-foreground">
                  {bookings.length}
                </h3>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <Package />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Active Bookings</p>
                <h3 className="mt-2 text-3xl font-bold text-foreground">
                  {activeCount}
                </h3>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <Truck />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Pending Approval</p>
                <h3 className="mt-2 text-3xl font-bold text-foreground">
                  {pendingCount}
                </h3>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <Clock />
              </div>
            </CardContent>
          </Card>
        </div>

        <Card className="gap-0">
          <CardHeader className="flex flex-row items-center justify-between border-b">
            <div>
              <CardTitle>Recent Requests</CardTitle>
              <CardDescription>
                A list of your recent freight bookings and their statuses.
              </CardDescription>
            </div>

            <Button variant="secondary" size="sm">
              <Filter />
              Filter
            </Button>
          </CardHeader>

          <CardContent className="px-0">
            {total === 0 && dataTableStatus === "success" ? (
              <div className="flex flex-col items-center justify-center py-12 px-6 text-center">
                <Package className="h-12 w-12 text-muted-foreground mb-4" />
                <h3 className="text-sm font-semibold text-foreground">No bookings found</h3>
                <p className="text-xs text-muted-foreground mt-1 max-w-sm">
                  {searchTerm ? "No bookings match your current search filter." : "You haven't requested any bookings yet."}
                </p>
              </div>
            ) : (
              <DataTable
                columns={columns}
                data={paginatedData}
                status={dataTableStatus}
                onRowClick={(row) => navigate(`/bookings/${(row as Freight.IBooking).id}`)}
                pagination={{
                  pageIndex: pagination.pageIndex,
                  pageSize: pagination.pageSize,
                  pageCount: pageCount,
                  totalCount: total,
                }}
                tableOptions={{
                  state: { pagination },
                  onPaginationChange: setPagination,
                }}
                containerClassName="border-b shadow-none"
                footer={DataTableFooter}
              />
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const styles: Record<string, string> = {
    DRAFT: "bg-amber-100 text-amber-700",
    CONFIRMED: "bg-primary/10 text-primary",
    IN_TRANSIT: "bg-muted text-foreground",
    DELIVERED: "bg-primary/10 text-primary",
    CANCELLED: "bg-destructive/10 text-destructive",
  };

  return (
    <span
      className={`inline-flex rounded-full px-3 py-1 text-xs font-medium ${styles[status] ?? "bg-muted text-muted-foreground"}`}
    >
      {status.replace(/_/g, ' ')}
    </span>
  );
}
