"use client";

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

type OrderRow = {
  id: string;
  product: string;
  imageClass: string;
  unitCost: string;
  stock: string;
  defaultQty: number;
  total: string;
};

const ORDER_ROWS: OrderRow[] = [
  {
    id: "1",
    product: "Phone",
    imageClass: "from-[#6B7280] to-[#374151]",
    unitCost: "$510.00",
    stock: "120",
    defaultQty: 1,
    total: "$ 512.00",
  },
  {
    id: "2",
    product: "Joystick",
    imageClass: "from-[#7C3AED] to-[#4C1D95]",
    unitCost: "$100.00",
    stock: "100",
    defaultQty: 2,
    total: "$ 200.00",
  },
  {
    id: "3",
    product: "MacBook",
    imageClass: "from-[#9CA3AF] to-[#1F2937]",
    unitCost: "$120",
    stock: "120",
    defaultQty: 1,
    total: "$ 120.00",
  },
];

function QuantityStepper({
  value,
  onChange,
  min = 1,
}: {
  value: number;
  onChange: (n: number) => void;
  min?: number;
}) {
  return (
    <div className="inline-flex h-8 items-stretch overflow-hidden rounded-md border border-[#E5E7EB] bg-white">
      <input
        type="number"
        min={min}
        value={value}
        onChange={(e) => {
          const n = Number.parseInt(e.target.value, 10);
          if (!Number.isNaN(n) && n >= min) onChange(n);
        }}
        className="w-10 border-0 bg-transparent px-1 text-center text-[12px] text-[#111827] outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
        aria-label="Quantity"
      />
      <div className="flex flex-col border-l border-[#E5E7EB]">
        <button
          type="button"
          className="flex h-1/2 items-center justify-center px-1 text-[#667085] hover:bg-[#F3F4F6]"
          aria-label="Increase quantity"
          onClick={() => onChange(value + 1)}
        >
          <ChevronUp className="size-3" aria-hidden />
        </button>
        <button
          type="button"
          className="flex h-1/2 items-center justify-center border-t border-[#E5E7EB] px-1 text-[#667085] hover:bg-[#F3F4F6] disabled:opacity-40"
          aria-label="Decrease quantity"
          disabled={value <= min}
          onClick={() => onChange(Math.max(min, value - 1))}
        >
          <ChevronDown className="size-3" aria-hidden />
        </button>
      </div>
    </div>
  );
}

export default function SupplierDetailPage() {
  const params = useParams<{ app: string; id: string }>();
  const app = params.app ?? "";
  const supplierId = params.id ?? "";

  const displayId = useMemo(() => {
    const map: Record<string, string> = {
      "7": "743648",
      "1": "123422",
      "2": "353315",
      "3": "51fe53",
      "4": "6sdf8sd",
      "5": "13ad5f1",
      "6": "645g86",
    };
    return map[supplierId] ?? supplierId.padStart(6, "0").slice(0, 6);
  }, [supplierId]);

  const [quantities, setQuantities] = useState<Record<string, number>>(() =>
    ORDER_ROWS.reduce<Record<string, number>>((acc, r) => {
      acc[r.id] = r.defaultQty;
      return acc;
    }, {})
  );

  return (
    <div className="min-h-0 bg-[#F3F4F6] p-2 md:p-3">
      <div className="mb-4 flex min-w-0 flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <p className="text-[13px] font-medium text-[#667085]">
          ID Number <span className="text-[#101828]">#{displayId}</span>
        </p>
        <div className="flex flex-wrap items-center gap-2">
          <Button
            type="button"
            className="h-9 rounded-md bg-[#EF7D00] px-4 text-xs font-semibold text-white shadow-none hover:bg-[#D46F00]"
          >
            Delete Supplier
          </Button>
          <Button
            type="button"
            className="h-9 rounded-md bg-[#003E6B] px-4 text-xs font-semibold text-white shadow-none hover:bg-[#003256]"
          >
            Edit Supplier
          </Button>
        </div>
      </div>

      <section className="mb-3 rounded-lg border border-[#E5E7EB] bg-white p-4 md:p-6">
        <div className="flex flex-col gap-6 xl:flex-row xl:items-start">
          <div className="flex min-w-0 flex-1 flex-col gap-4 sm:flex-row sm:gap-5">
            <Image
              src={avatarImage}
              alt="Michael Jorden"
              width={80}
              height={80}
              className="size-20 shrink-0 rounded-lg object-cover"
            />
            <div className="min-w-0 flex-1 space-y-4">
              <div>
                <h1 className="text-xl font-semibold text-[#101828] md:text-[22px]">Michael Jorden</h1>
                <p className="mt-1 text-[12px] text-[#98A2B3]">Last Supply 12 Sept 2022</p>
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <p className="text-[11px] text-[#98A2B3]">Phone</p>
                  <p className="mt-0.5 text-[13px] text-[#101828]">+1 48065650633</p>
                </div>
                <div>
                  <p className="text-[11px] text-[#98A2B3]">Email</p>
                  <p className="mt-0.5 text-[13px] text-[#101828]">solit@gmail.com</p>
                </div>
              </div>
            </div>
          </div>

          <div className="min-w-0 flex-1 border-t border-[#F3F4F6] pt-6 xl:border-l xl:border-t-0 xl:px-6 xl:pt-0">
            <p className="text-[11px] text-[#98A2B3]">Address</p>
            <p className="mt-1 max-w-md text-[13px] leading-relaxed text-[#101828]">
              5 Adekunle Street, Yaba, Lagos State, USA
            </p>
          </div>

          <div className="min-w-0 shrink-0 border-t border-[#F3F4F6] pt-6 xl:w-[280px] xl:border-l xl:border-t-0 xl:pl-6 xl:pt-0">
            <div className="mb-4 flex items-start justify-between gap-2">
              <span className="inline-flex size-9 items-center justify-center rounded-full bg-[#E0F2FE] text-[#1570EF]">
                <Clock className="size-4" aria-hidden />
              </span>
              <button
                type="button"
                className="inline-flex h-8 items-center gap-1 rounded-md border border-[#E5E7EB] bg-white px-2.5 text-[11px] text-[#667085]"
              >
                All-time
                <ChevronDown className="size-3.5" aria-hidden />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <p className="text-[11px] text-[#98A2B3]">Total Supply</p>
                <p className="mt-0.5 text-lg font-semibold text-[#101828]">$ 25,000.00</p>
              </div>
              <div>
                <p className="text-[11px] text-[#98A2B3]">Total Purchase Due</p>
                <p className="mt-0.5 text-lg font-semibold text-[#101828]">$ 3,215.00</p>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="rounded-lg border border-[#E5E7EB] bg-white p-4 md:p-5">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <h2 className="text-[22px] font-semibold text-[#101828]">Order Placed</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-[200px]">
              <Search className="size-4 shrink-0 text-[#98A2B3]" aria-hidden />
              <Input
                type="search"
                placeholder="Search"
                className="h-full border-0 bg-transparent p-0 text-xs text-[#111827] placeholder:text-[#D1D5DB] focus-visible:ring-0"
                aria-label="Search orders"
              />
            </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-[900px]">
            <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" />
                </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]">Product</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Unit Cost</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Stock</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Quantity</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Total</th>
                <th className="px-3 py-2 text-left text-[12px] font-semibold text-[#111827]">Action</th>
              </tr>
            </thead>
            <tbody>
              {ORDER_ROWS.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.product}`} />
                  </td>
                  <td className="px-3 py-2.5">
                    <div className={`size-9 rounded-md bg-gradient-to-br ${row.imageClass}`} />
                  </td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">{row.product}</td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">{row.unitCost}</td>
                  <td className="px-3 py-2.5 text-[12px] text-[#111827]">{row.stock}</td>
                  <td className="px-3 py-2.5">
                    <QuantityStepper
                      value={quantities[row.id] ?? row.defaultQty}
                      onChange={(n) => setQuantities((prev) => ({ ...prev, [row.id]: n }))}
                    />
                  </td>
                  <td className="px-3 py-2.5 text-[12px] font-medium text-[#111827]">{row.total}</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={`Actions for ${row.product}`}
                    >
                      <MoreVertical className="size-4" aria-hidden />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="mt-2 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]">
            Previous
          </Button>
          <p className="text-[10px] text-[#9CA3AF]">page 1 of 10</p>
          <Button type="button" variant="outline" className="h-7 rounded-md border-[#E5E7EB] px-5 text-[10px] font-medium text-[#6B7280]">
            Next
          </Button>
        </div>

        <div className="mt-4 text-center">
          <Link href={`/${app}/suppliers`} className="text-[12px] font-medium text-[#1570EF] hover:underline">
            Back to suppliers
          </Link>
        </div>
      </section>
    </div>
  );
}
