"use client";

import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  CalendarDays,
  ChevronDown,
  MoreVertical,
  Search,
  SlidersHorizontal,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import avatarImage from "@/assets/images/avatar.jpeg";

type PayStatus = "Completed" | "Process";

type ShippingLabelRow = {
  id: string;
  name: string;
  orderId: string;
  packageQuantity: number;
  totalProduct: number;
  service: string;
  payStatus: PayStatus;
};

const SHIPPING_LABEL_ROWS: ShippingLabelRow[] = [
  {
    id: "1",
    name: "Janet Adebayo",
    orderId: "#123d22",
    packageQuantity: 8,
    totalProduct: 120,
    service: "USPS First Class",
    payStatus: "Completed",
  },
  {
    id: "2",
    name: "Victor James",
    orderId: "#321531",
    packageQuantity: 3,
    totalProduct: 20,
    service: "DHL Express",
    payStatus: "Completed",
  },
  {
    id: "3",
    name: "Jhon Ronan",
    orderId: "#354814",
    packageQuantity: 6,
    totalProduct: 57,
    service: "USPS",
    payStatus: "Process",
  },
  {
    id: "4",
    name: "Sharp Camela",
    orderId: "#894616",
    packageQuantity: 5,
    totalProduct: 30,
    service: "DHL Express",
    payStatus: "Completed",
  },
  {
    id: "5",
    name: "David Rock",
    orderId: "#354814",
    packageQuantity: 1,
    totalProduct: 3,
    service: "UPS",
    payStatus: "Process",
  },
  {
    id: "6",
    name: "Michael Jorden",
    orderId: "#512903",
    packageQuantity: 4,
    totalProduct: 45,
    service: "USPS First Class",
    payStatus: "Completed",
  },
  {
    id: "7",
    name: "Angela Carter",
    orderId: "#772104",
    packageQuantity: 2,
    totalProduct: 9,
    service: "DHL Express",
    payStatus: "Process",
  },
  {
    id: "8",
    name: "James Labron",
    orderId: "#110045",
    packageQuantity: 10,
    totalProduct: 200,
    service: "UPS",
    payStatus: "Completed",
  },
  {
    id: "9",
    name: "Sarah Smith",
    orderId: "#998201",
    packageQuantity: 7,
    totalProduct: 64,
    service: "USPS",
    payStatus: "Completed",
  },
  {
    id: "10",
    name: "Luis Garcia",
    orderId: "#445120",
    packageQuantity: 3,
    totalProduct: 12,
    service: "DHL Express",
    payStatus: "Process",
  },
];

const PAGE_SIZE = 5;

function StatusPill({ status }: { status: PayStatus }) {
  const isDone = status === "Completed";
  return (
    <button
      type="button"
      className={
        isDone
          ? "inline-flex h-7 max-w-full items-center gap-1 rounded-full border border-[#12B76A] bg-white px-2.5 text-left text-xs font-medium text-[#12B76A] hover:bg-[#ECFDF3]"
          : "inline-flex h-7 max-w-full items-center gap-1 rounded-full border border-[#F04438] bg-white px-2.5 text-left text-xs font-medium text-[#F04438] hover:bg-[#FEF3F2]"
      }
    >
      {status}
      <ChevronDown className="size-3 shrink-0 opacity-80" aria-hidden />
    </button>
  );
}

export default function ShippingLabelsPage() {
  const { app } = useParams<{ app: string }>();
  const [search, setSearch] = useState("");
  const [pageIndex, setPageIndex] = useState(0);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return SHIPPING_LABEL_ROWS;
    return SHIPPING_LABEL_ROWS.filter((row) =>
      [
        row.name,
        row.orderId,
        row.service,
        row.payStatus,
        String(row.packageQuantity),
        String(row.totalProduct),
      ].some((f) => f.toLowerCase().includes(q)),
    );
  }, [search]);

  const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const safeIndex = Math.min(pageIndex, pageCount - 1);
  const paged = useMemo(() => {
    const start = safeIndex * PAGE_SIZE;
    return filtered.slice(start, start + PAGE_SIZE);
  }, [filtered, safeIndex]);

  useEffect(() => {
    if (pageIndex > pageCount - 1) {
      setPageIndex(Math.max(0, pageCount - 1));
    }
  }, [pageIndex, pageCount]);

  return (
    <div className="min-h-0 bg-[#F3F4F6] p-2 md:p-3">
      <MainTitle title="All Shipping Labels" />

      <section className="rounded-lg border border-[#E5E7EB] bg-white p-4 shadow-sm md:p-5">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <h2 className="text-[22px] font-semibold text-[#101828] sm:text-[26px]">All Shipping Labels</h2>

          <div className="flex w-full flex-wrap items-center justify-end gap-2 md:w-auto">
            <div className="flex h-9 w-full items-center gap-1.5 rounded-md border border-[#E5E7EB] bg-white px-2 md:w-[220px]">
              <Search className="size-4 shrink-0 text-[#98A2B3]" aria-hidden />
              <Input
                type="search"
                placeholder="Search"
                className="h-full border-0 p-0 text-xs text-[#111827] placeholder:text-[#D1D5DB] focus-visible:ring-0"
                aria-label="Search shipping labels"
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPageIndex(0);
                }}
              />
            </div>

            <Button
              type="button"
              variant="outline"
              className="h-9 rounded-md border-[#E5E7EB] px-3 text-xs text-[#667085]"
            >
              <SlidersHorizontal className="mr-1.5 size-3.5" aria-hidden />
              Filters
            </Button>
            <Button
              type="button"
              variant="outline"
              className="h-9 rounded-md border-[#E5E7EB] px-3 text-xs text-[#667085]"
            >
              <CalendarDays className="mr-1.5 size-3.5" aria-hidden />
              filters
            </Button>
          </div>
        </div>

        <div className="overflow-x-auto rounded-md border border-[#E5E7EB]">
          <table className="w-full min-w-[920px]">
            <thead>
              <tr className="border-b border-[#E5E7EB] bg-white">
                <th className="w-10 px-3 py-2 text-left">
                  <input
                    type="checkbox"
                    className="size-3.5 rounded border border-[#9CA3AF]"
                    aria-label="Select all shipping label rows"
                  />
                </th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Image</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Customer Name</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Order ID</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Package Quantity</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Total Product</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Service</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Pay</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Action</th>
              </tr>
            </thead>
            <tbody>
              {paged.map((row) => (
                <tr key={row.id} className="border-b border-[#F3F4F6] last:border-b-0">
                  <td className="px-3 py-2.5">
                    <input
                      type="checkbox"
                      className="size-3.5 rounded border border-[#9CA3AF]"
                      aria-label={`Select ${row.name}`}
                    />
                  </td>
                  <td className="px-3 py-2.5">
                    <Image
                      src={avatarImage}
                      alt={row.name}
                      width={36}
                      height={36}
                      className="size-9 rounded-full object-cover"
                    />
                  </td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">
                    <Link
                      href={`/${app}/shipping-labels/${row.id}`}
                      className="font-medium text-[#111827] hover:text-[#003E6B] hover:underline"
                    >
                      {row.name}
                    </Link>
                  </td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">
                    <Link
                      href={`/${app}/shipping-labels/${row.id}`}
                      className="text-[#667085] hover:text-[#003E6B] hover:underline"
                    >
                      {row.orderId}
                    </Link>
                  </td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">{row.packageQuantity}</td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">{row.totalProduct}</td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">{row.service}</td>
                  <td className="px-3 py-2.5">
                    <StatusPill status={row.payStatus} />
                  </td>
                  <td className="px-3 py-2.5">
                    <button
                      type="button"
                      className="inline-flex items-center justify-center rounded p-1 text-[#111827] hover:bg-[#F3F4F6]"
                      aria-label={`More actions for order ${row.orderId}`}
                    >
                      <MoreVertical className="size-4" aria-hidden />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filtered.length === 0 ? (
          <p className="mt-3 text-center text-sm text-[#667085]">No shipping labels match your search.</p>
        ) : null}

        <div className="mt-3 flex items-center justify-between">
          <Button
            type="button"
            variant="outline"
            className="h-7 rounded-md border-[#E5E7EB] px-3 text-[10px] font-medium text-[#6B7280] disabled:opacity-50"
            disabled={safeIndex === 0}
            onClick={() => setPageIndex((i) => Math.max(0, i - 1))}
          >
            Previous
          </Button>
          <p className="text-[10px] text-[#9CA3AF]">
            page {safeIndex + 1} of {pageCount}
          </p>
          <Button
            type="button"
            variant="outline"
            className="h-7 rounded-md border-[#E5E7EB] px-5 text-[10px] font-medium text-[#6B7280] disabled:opacity-50"
            disabled={safeIndex >= pageCount - 1}
            onClick={() => setPageIndex((i) => Math.min(pageCount - 1, i + 1))}
          >
            Next
          </Button>
        </div>
      </section>
    </div>
  );
}
