"use client";

import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import {
  OrdersDateFilterPanel,
  type OrdersDateFilterValue,
} from "@/features/orders/orders-date-filter-panel";
import {
  applyOrderFilters,
  OrdersFilterPanel,
  type OrderFilters,
} from "@/features/orders/orders-filter-panel";
import {
  Check,
  Copy,
  MoreVertical,
  Pencil,
  Search,
  ShoppingBag,
  ShoppingCart,
} from "lucide-react";
import Link from "next/link";

type OrdersPageBodyProps = {
  app: string;
};

type OrderStatus = "completed" | "pending" | "process";

type OrderRow = {
  id: string;
  initials: string;
  customerName: string;
  orderDate: string;
  orderType: "Home Delivery" | "Pick Up";
  trackingId: string;
  orderTotal: string;
  status: OrderStatus;
};

/** Swap for API response — empty array shows empty state. */
const ORDER_ROWS: OrderRow[] = [
  {
    id: "1",
    initials: "JA",
    customerName: "Janet Adebayo",
    orderDate: "12 Aug 2022 — 12:00",
    orderType: "Home Delivery",
    trackingId: "9348fj73",
    orderTotal: "₦25,000.00",
    status: "completed",
  },
  {
    id: "2",
    initials: "SJ",
    customerName: "Samuel Johnson",
    orderDate: "12 Aug 2022 — 12:00",
    orderType: "Pick Up",
    trackingId: "9348fj73",
    orderTotal: "₦25,000.00",
    status: "pending",
  },
  {
    id: "3",
    initials: "FD",
    customerName: "Francis Doe",
    orderDate: "12 Aug 2022 — 12:00",
    orderType: "Home Delivery",
    trackingId: "9348fj73",
    orderTotal: "₦25,000.00",
    status: "process",
  },
  {
    id: "4",
    initials: "CD",
    customerName: "Christian Dior",
    orderDate: "12 Aug 2022 — 12:00",
    orderType: "Pick Up",
    trackingId: "9348fj73",
    orderTotal: "₦25,000.00",
    status: "completed",
  },
];

function PeriodSelect({ id }: { id: string }) {
  return (
    <Select defaultValue="week">
      <SelectTrigger
        id={id}
        className="h-8 w-[118px] shrink-0 border-0 bg-transparent px-0 text-[11px] font-medium text-[#ABAFB1] shadow-none hover:bg-transparent focus:ring-0 focus:ring-offset-0 [&>svg]:size-3.5 [&>svg]:opacity-70"
        aria-label="Time period"
      >
        <SelectValue placeholder="This Week" />
      </SelectTrigger>
      <SelectContent align="end">
        <SelectItem value="week">This Week</SelectItem>
        <SelectItem value="month">This Month</SelectItem>
        <SelectItem value="year">This Year</SelectItem>
      </SelectContent>
    </Select>
  );
}

const statusSelectClass: Record<OrderStatus, string> = {
  completed:
    "border-[#12B76A] text-[#12B76A] bg-[#ECFDF3] hover:bg-[#ECFDF3] focus:ring-[#12B76A]/30",
  pending:
    "border-[#F79009] text-[#F79009] bg-[#FFFAEB] hover:bg-[#FFFAEB] focus:ring-[#F79009]/30",
  process:
    "border-[#2E90FA] text-[#2E90FA] bg-[#EFF8FF] hover:bg-[#EFF8FF] focus:ring-[#2E90FA]/30",
};

function OrderStatusSelect({ initialStatus }: { initialStatus: OrderStatus }) {
  const [status, setStatus] = useState<OrderStatus>(initialStatus);
  return (
    <Select value={status} onValueChange={(v) => setStatus(v as OrderStatus)}>
      <SelectTrigger
        className={cn(
          "h-7 w-[104px] gap-0.5 rounded-full border px-2 text-[10px] font-semibold shadow-none focus:ring-1 [&>svg]:size-3 [&>svg]:opacity-80",
          statusSelectClass[status]
        )}
        aria-label="Order status"
      >
        <SelectValue />
      </SelectTrigger>
      <SelectContent align="end">
        <SelectItem value="completed">Completed</SelectItem>
        <SelectItem value="pending">Pending</SelectItem>
        <SelectItem value="process">Process</SelectItem>
      </SelectContent>
    </Select>
  );
}

export default function OrdersPageBody({ app }: OrdersPageBodyProps) {
  const hasData = ORDER_ROWS.length > 0;
  const [appliedFilters, setAppliedFilters] = useState<OrderFilters | null>(null);
  const [appliedDateFilter, setAppliedDateFilter] = useState<OrdersDateFilterValue | null>(null);
  const customerNames = useMemo(
    () => Array.from(new Set(ORDER_ROWS.map((r) => r.customerName))),
    []
  );
  const displayRows = useMemo(
    () => applyOrderFilters(ORDER_ROWS, appliedFilters),
    [appliedFilters, appliedDateFilter]
  );

  return (
    <div className="min-h-0 space-y-6 bg-[#F8F9FA] p-5 md:p-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-xl font-semibold leading-[1.35] text-[#45464E]">Order Summary</h1>
        <Button
          asChild
          className="h-9 rounded-lg bg-[#003E6B] px-5 text-xs font-semibold text-white shadow-none hover:bg-[#003256]"
        >
          <Link href={`/${app}/orders/new`}>Create New Order</Link>
        </Button>
      </div>

      <section className="grid divide-y divide-[#EEF1F4] rounded-xl border border-[#F1F3F9] bg-white shadow-[0_1px_2px_rgba(16,24,40,0.04)] lg:grid-cols-3 lg:divide-x lg:divide-y-0">
        <div className="flex flex-col gap-5 p-5 md:p-6">
          <div className="flex items-start justify-between gap-3">
            <div className="flex size-10 items-center justify-center rounded-full bg-[#EEF1F4] text-[#667085]">
              <ShoppingBag className="size-5" aria-hidden />
            </div>
            <PeriodSelect id="orders-period-1" />
          </div>
          <div className="grid grid-cols-3 gap-3 sm:gap-4">
            {hasData ? (
              <>
                {[
                  { label: "All Orders", value: "344" },
                  { label: "Pending", value: "5" },
                  { label: "Completed", value: "320" },
                ].map((m) => (
                  <div key={m.label} className="min-w-0 space-y-1">
                    <p className="text-[11px] font-medium leading-tight text-[#667085]">{m.label}</p>
                    <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">{m.value}</p>
                  </div>
                ))}
              </>
            ) : (
              ["All Orders", "Pending", "Completed"].map((label) => (
                <div key={label} className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#667085]">{label}</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">0</p>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="flex flex-col gap-5 p-5 md:p-6">
          <div className="flex items-start justify-between gap-3">
            <div className="flex size-10 items-center justify-center rounded-full bg-[#EEF1F4] text-[#667085]">
              <ShoppingBag className="size-5" aria-hidden />
            </div>
            <PeriodSelect id="orders-period-2" />
          </div>
          <div className="grid grid-cols-3 gap-3 sm:gap-4">
            {hasData ? (
              <>
                <div className="min-w-0 space-y-1">
                  <div className="flex flex-wrap items-center gap-1.5">
                    <p className="text-[11px] font-medium leading-tight text-[#667085]">Canceled</p>
                    <span className="rounded bg-[#FEE4E2] px-1.5 py-0.5 text-[9px] font-semibold text-[#D92D20]">
                      -20%
                    </span>
                  </div>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">20</p>
                </div>
                <div className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#667085]">Returned</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">20</p>
                </div>
                <div className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#667085]">Damaged</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">5</p>
                </div>
              </>
            ) : (
              ["Canceled", "Returned", "Damaged"].map((label) => (
                <div key={label} className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#667085]">{label}</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">0</p>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="flex flex-col gap-5 p-5 md:p-6">
          <div className="flex items-start justify-between gap-3">
            <div className="flex size-10 items-center justify-center rounded-full bg-[#EEF1F4] text-[#667085]">
              <ShoppingCart className="size-5" aria-hidden />
            </div>
            <PeriodSelect id="orders-period-3" />
          </div>
          <div className="grid grid-cols-2 gap-3 sm:gap-6">
            {hasData ? (
              <>
                <div className="min-w-0 space-y-1">
                  <div className="flex flex-wrap items-center gap-1.5">
                    <p className="text-[11px] font-medium leading-tight text-[#D92D20]">Abandoned Cart</p>
                    <span className="rounded bg-[#ECFDF3] px-1.5 py-0.5 text-[9px] font-semibold text-[#039855]">
                      0.00%
                    </span>
                  </div>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#D92D20]">20%</p>
                </div>
                <div className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#667085]">Customers</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">30</p>
                </div>
              </>
            ) : (
              <>
                <div className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#D92D20]">Abandoned Cart</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">0</p>
                </div>
                <div className="min-w-0 space-y-1">
                  <p className="text-[11px] font-medium leading-tight text-[#667085]">Customers</p>
                  <p className="text-xl font-bold leading-none tracking-tight text-[#1C1D22]">0</p>
                </div>
              </>
            )}
          </div>
        </div>
      </section>

      <section className="rounded-xl border border-[#F1F3F9] bg-white p-5 shadow-[0_1px_2px_rgba(16,24,40,0.04)] md:p-6">
        <div className="flex flex-col gap-4">
          <div
            className={`flex flex-col gap-4 md:flex-row md:items-center md:justify-between ${hasData ? "mb-0" : "mb-8"}`}
          >
            <h2
              className={cn("text-lg font-semibold", hasData ? "text-[#1C1D22]" : "text-[#CFD3D4]")}
            >
              Customer Orders
            </h2>
            <div className="flex flex-wrap items-center gap-2">
              <div className="flex h-10 w-full items-center gap-2 rounded-md border border-[#F1F3F9] px-3 md:w-[260px]">
                <Search className="size-4 shrink-0 text-[#ABAFB1]" aria-hidden />
                <Input
                  type="search"
                  placeholder="Search"
                  className="h-full border-0 p-0 text-[11px] text-[#45464E] placeholder:text-[#CFD3D4] focus-visible:ring-0"
                  aria-label="Search orders"
                />
              </div>
              <OrdersFilterPanel customerNames={customerNames} onApply={setAppliedFilters} />
              <OrdersDateFilterPanel
                onApply={(v) => {
                  setAppliedDateFilter(v);
                }}
              />
            </div>
          </div>

          {hasData ? (
            <Tabs defaultValue="orders" className="w-full">
              <TabsList className="mb-4 h-auto w-full min-w-0 justify-start gap-6 border-0 border-b border-[#EEF1F4] bg-transparent p-0">
                <TabsTrigger
                  value="orders"
                  className="group relative rounded-none border-0 border-b-2 border-transparent bg-transparent px-0 pb-2.5 text-[11px] font-semibold text-[#667085] shadow-none ring-offset-0 data-[state=active]:border-[#F28B20] data-[state=active]:text-[#F28B20] data-[state=active]:shadow-none"
                >
                  <span className="inline-flex items-center gap-1">
                    <Check
                      className="size-3.5 shrink-0 opacity-0 transition-opacity group-data-[state=active]:opacity-100"
                      aria-hidden
                    />
                    Orders
                  </span>
                </TabsTrigger>
                <TabsTrigger
                  value="return"
                  className="rounded-none border-0 border-b-2 border-transparent bg-transparent px-0 pb-2.5 text-[11px] font-semibold text-[#667085] shadow-none ring-offset-0 data-[state=active]:border-[#F28B20] data-[state=active]:text-[#F28B20] data-[state=active]:shadow-none"
                >
                  Return
                </TabsTrigger>
                <TabsTrigger
                  value="replacement"
                  className="rounded-none border-0 border-b-2 border-transparent bg-transparent px-0 pb-2.5 text-[11px] font-semibold text-[#667085] shadow-none ring-offset-0 data-[state=active]:border-[#F28B20] data-[state=active]:text-[#F28B20] data-[state=active]:shadow-none"
                >
                  Replacement
                </TabsTrigger>
              </TabsList>

              <TabsContent value="orders" className="mt-0">
                <div className="overflow-x-auto rounded-md border border-[#F1F3F9]">
                  <table className="w-full min-w-[980px]">
                    <thead>
                      <tr className="border-b border-[#F1F3F9] bg-white">
                        <th className="w-10 px-2 py-2.5 text-left">
                          <input type="checkbox" className="size-3 rounded border border-[#B9C0D4]" aria-label="Select all" />
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Image
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Customer Order
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Order Date
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Order Type
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Tracking ID
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Order Total
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Status
                        </th>
                        <th className="px-2 py-2.5 text-left text-[10px] font-semibold uppercase tracking-wide text-[#667085]">
                          Action
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {displayRows.map((row) => (
                        <tr key={row.id} className="border-b border-[#F7F8FB]">
                          <td className="px-2 py-2">
                            <input type="checkbox" className="size-3 rounded border border-[#B9C0D4]" aria-label={`Select ${row.customerName}`} />
                          </td>
                          <td className="px-2 py-2">
                            <div className="flex size-8 items-center justify-center rounded-full bg-[#EEF1F4] text-[10px] font-semibold text-[#667085]">
                              {row.initials}
                            </div>
                          </td>
                          <td className="px-2 py-2 text-[11px] font-medium text-[#1C1D22]">{row.customerName}</td>
                          <td className="px-2 py-2 text-[11px] text-[#667085]">{row.orderDate}</td>
                          <td className="px-2 py-2 text-[11px] text-[#1C1D22]">{row.orderType}</td>
                          <td className="px-2 py-2">
                            <div className="flex items-center gap-1.5">
                              <span className="font-mono text-[11px] text-[#1C1D22]">{row.trackingId}</span>
                              <button
                                type="button"
                                className="rounded p-0.5 text-[#ABAFB1] hover:bg-[#F5F7FA] hover:text-[#667085]"
                                aria-label="Edit tracking ID"
                              >
                                <Pencil className="size-3" aria-hidden />
                              </button>
                              <button
                                type="button"
                                className="rounded p-0.5 text-[#ABAFB1] hover:bg-[#F5F7FA] hover:text-[#667085]"
                                aria-label="Copy tracking ID"
                              >
                                <Copy className="size-3" aria-hidden />
                              </button>
                            </div>
                          </td>
                          <td className="px-2 py-2 text-[11px] font-medium text-[#1C1D22]">{row.orderTotal}</td>
                          <td className="px-2 py-2">
                            <OrderStatusSelect initialStatus={row.status} />
                          </td>
                          <td className="px-2 py-2">
                            <button
                              type="button"
                              className="inline-flex items-center justify-center rounded p-1 text-[#1C1D22] hover:bg-[#F5F7FA]"
                              aria-label="More actions"
                            >
                              <MoreVertical className="size-3.5" aria-hidden />
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="mt-3 flex items-center justify-between">
                  <Button
                    type="button"
                    variant="outline"
                    className="h-8 rounded-md border-[#E5E7EB] px-4 text-[10px] font-medium text-[#8B8D97]"
                  >
                    Previous
                  </Button>
                  <p className="text-[10px] text-[#CFD3D4]">page 1 of 10</p>
                  <Button
                    type="button"
                    variant="outline"
                    className="h-8 rounded-md border-[#E5E7EB] px-4 text-[10px] font-medium text-[#8B8D97]"
                  >
                    Next
                  </Button>
                </div>
              </TabsContent>

              <TabsContent value="return" className="mt-0">
                <p className="rounded-md border border-dashed border-[#E1E2E9] bg-[#FAFBFC] py-10 text-center text-[11px] text-[#8B8D97]">
                  No return orders in this view.
                </p>
              </TabsContent>

              <TabsContent value="replacement" className="mt-0">
                <p className="rounded-md border border-dashed border-[#E1E2E9] bg-[#FAFBFC] py-10 text-center text-[11px] text-[#8B8D97]">
                  No replacement orders in this view.
                </p>
              </TabsContent>
            </Tabs>
          ) : (
            <div className="flex min-h-[360px] flex-col items-center justify-center gap-5 py-10">
              <div className="flex size-[112px] items-center justify-center rounded-full border border-[#E1E2E9] bg-[#F4F5FA]">
                <ShoppingBag className="size-10 text-[#BEC0CA]" strokeWidth={1.35} aria-hidden />
              </div>
              <div className="max-w-md space-y-1.5 text-center">
                <p className="text-[22px] font-bold leading-[1.35] text-[#1C1D22]">No Orders Yet?</p>
                <p className="text-sm font-normal leading-relaxed text-[#8B8D97]">
                  Add Products To Your Store And Start Selling To See Orders Here.
                </p>
              </div>
              <Button
                asChild
                className="h-11 rounded-lg bg-[#003E6B] px-8 text-xs font-semibold text-white shadow-none hover:bg-[#003256]"
              >
                <Link href={`/${app}/orders/new`}>Add New Order</Link>
              </Button>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
