"use client";

import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { CalendarDays, Clock3, Minus, Plus, Search, ShoppingBag } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useRef, useState } from "react";

type CreateNewOrderPageBodyProps = {
  app: string;
};

type LineItem = {
  id: string;
  name: string;
  unitPrice: number;
  soldPrice: number;
  qty: number;
  stock: number;
  thumb: string;
};

const fieldWrap = "space-y-1.5";
const labelClass = "text-[11px] font-medium text-[#667085]";
const controlClass =
  "h-10 w-full rounded-md border-0 bg-[#F3F4F6] px-3 text-[13px] text-[#1C1D22] shadow-none ring-offset-0 focus-visible:ring-1 focus-visible:ring-[#003E6B]/25";

function QtyStep({ value, onChange }: { value: number; onChange: (n: number) => void }) {
  return (
    <div className="inline-flex items-center rounded-md border border-[#E4E7EC] bg-white">
      <button
        type="button"
        className="grid size-8 place-items-center text-[#667085] hover:bg-[#F9FAFB]"
        onClick={() => onChange(Math.max(1, value - 1))}
        aria-label="Decrease quantity"
      >
        <Minus className="size-3.5" />
      </button>
      <span className="min-w-[2rem] text-center text-[12px] font-semibold text-[#1C1D22]">{value}</span>
      <button
        type="button"
        className="grid size-8 place-items-center text-[#667085] hover:bg-[#F9FAFB]"
        onClick={() => onChange(value + 1)}
        aria-label="Increase quantity"
      >
        <Plus className="size-3.5" />
      </button>
    </div>
  );
}

function formatMoney(n: number) {
  return `$ ${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

export default function CreateNewOrderPageBody({ app }: CreateNewOrderPageBodyProps) {
  const router = useRouter();
  const [newCustomer, setNewCustomer] = useState(true);
  const [orderNote, setOrderNote] = useState(
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  );
  const [itemSearch, setItemSearch] = useState("");
  const [items, setItems] = useState<LineItem[]>([
    { id: "1", name: "Lorem Ipsum", unitPrice: 1000, soldPrice: 1000, qty: 1, stock: 30, thumb: "📦" },
    { id: "2", name: "Lorem Ipsum", unitPrice: 1500, soldPrice: 1500, qty: 1, stock: 24, thumb: "📦" },
  ]);
  const setNewCustomerMode = (v: boolean) => {
    setNewCustomer(v);
    if (!v) {
      setItems([{ id: "sp-1", name: "Smart Phone", unitPrice: 1000, soldPrice: 1000, qty: 1, stock: 30, thumb: "📱" }]);
    } else {
      setItems([
        { id: "1", name: "Lorem Ipsum", unitPrice: 1000, soldPrice: 1000, qty: 1, stock: 30, thumb: "📦" },
        { id: "2", name: "Lorem Ipsum", unitPrice: 1500, soldPrice: 1500, qty: 1, stock: 24, thumb: "📦" },
      ]);
    }
  };
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [fileName, setFileName] = useState<string | null>(null);

  const [custName, setCustName] = useState("Michael Joseph");
  const [custEmail, setCustEmail] = useState("michael@gamil.com");
  const [custPhone, setCustPhone] = useState("802 345 6789");
  const [custAddress, setCustAddress] = useState("123 Main Street, Apt 4B");
  const [custCity, setCustCity] = useState("New York");

  const subtotal = useMemo(
    () => items.reduce((s, it) => s + it.soldPrice * it.qty, 0),
    [items]
  );
  const shippingCost = 20;
  const platformFees = 10;
  const costPrice = 2000;
  const profitMargin = 500;
  const orderTotal = subtotal + shippingCost + platformFees;

  const addSmartPhoneRow = () => {
    const id = `row-${Date.now()}`;
    setItems((prev) => [
      ...prev,
      {
        id,
        name: "Smart Phone",
        unitPrice: 1000,
        soldPrice: 1000,
        qty: 1,
        stock: 30,
        thumb: "📱",
      },
    ]);
    setItemSearch("");
  };

  const updateLine = (id: string, patch: Partial<LineItem>) => {
    setItems((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r)));
  };

  const removeLine = (id: string) => {
    setItems((rows) => rows.filter((r) => r.id !== id));
  };

  return (
    <div className="min-h-0 space-y-5 bg-[#F8F9FA] p-4 md:p-6">
      <MainTitle title="Create New Order" goBack />

      <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_min(100%,420px)] lg:items-start">
        <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="mb-5 flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-base font-semibold text-[#1C1D22]">Order Details</h2>
            <div className="flex items-center gap-2">
              <Label htmlFor="new-customer" className="cursor-pointer text-[12px] font-medium text-[#344054]">
                New Customer
              </Label>
              <Switch
                id="new-customer"
                checked={newCustomer}
                onCheckedChange={setNewCustomerMode}
                className="data-[state=checked]:bg-[#003E6B]"
              />
            </div>
          </div>

          <div className="space-y-4">
            {!newCustomer ? (
              <div className={fieldWrap}>
                <Label className={labelClass}>Select Customer</Label>
                <Select>
                  <SelectTrigger className={controlClass}>
                    <SelectValue placeholder="Select customer" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="janet">Janet Adebayo</SelectItem>
                    <SelectItem value="samuel">Samuel Johnson</SelectItem>
                    <SelectItem value="francis">Francis Doe</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            ) : (
              <>
                <div className={fieldWrap}>
                  <Label className={labelClass}>Customer Name</Label>
                  <Input value={custName} onChange={(e) => setCustName(e.target.value)} className={controlClass} placeholder="Michael Joseph" />
                </div>
                <div className={fieldWrap}>
                  <Label className={labelClass}>Email</Label>
                  <Input
                    type="email"
                    value={custEmail}
                    onChange={(e) => setCustEmail(e.target.value)}
                    className={controlClass}
                    placeholder="michael@gamil.com"
                  />
                </div>
                <div className={fieldWrap}>
                  <Label className={labelClass}>Phone Number</Label>
                  <div className="grid grid-cols-[100px_1fr] gap-2">
                    <Select defaultValue="us">
                      <SelectTrigger className={controlClass}>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="us">🇺🇸 +1</SelectItem>
                        <SelectItem value="ng">🇳🇬 +234</SelectItem>
                      </SelectContent>
                    </Select>
                    <Input value={custPhone} onChange={(e) => setCustPhone(e.target.value)} className={controlClass} placeholder="802 345 6789" />
                  </div>
                </div>
                <div className={fieldWrap}>
                  <Label className={labelClass}>Address</Label>
                  <Textarea
                    value={custAddress}
                    onChange={(e) => setCustAddress(e.target.value)}
                    rows={3}
                    className="resize-none rounded-md border-0 bg-[#F3F4F6] px-3 py-2.5 text-[13px] focus-visible:ring-1 focus-visible:ring-[#003E6B]/25"
                  />
                </div>
                <div className={fieldWrap}>
                  <Label className={labelClass}>City</Label>
                  <Input value={custCity} onChange={(e) => setCustCity(e.target.value)} className={controlClass} placeholder="New York" />
                </div>
                <div className="grid gap-3 sm:grid-cols-2">
                  <div className={fieldWrap}>
                    <Label className={labelClass}>State</Label>
                    <Select defaultValue="ny">
                      <SelectTrigger className={controlClass}>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ny">New York</SelectItem>
                        <SelectItem value="ca">California</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className={fieldWrap}>
                    <Label className={labelClass}>Zip Code</Label>
                    <Select defaultValue="12000">
                      <SelectTrigger className={controlClass}>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="12000">12000</SelectItem>
                        <SelectItem value="90210">90210</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className={fieldWrap}>
                  <Label className={labelClass}>Country</Label>
                  <Select defaultValue="us">
                    <SelectTrigger className={controlClass}>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="us">United States</SelectItem>
                      <SelectItem value="ng">Nigeria</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </>
            )}

            <div className={fieldWrap}>
              <Label className={labelClass}>{newCustomer ? "Store" : "Enter Store"}</Label>
              {newCustomer ? (
                <Select defaultValue="app">
                  <SelectTrigger className={controlClass}>
                    <SelectValue placeholder="Select store" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="app">App Store</SelectItem>
                    <SelectItem value="main">Main Store</SelectItem>
                    <SelectItem value="branch">Branch Outlet</SelectItem>
                  </SelectContent>
                </Select>
              ) : (
                <Select>
                  <SelectTrigger className={controlClass}>
                    <SelectValue placeholder="Select store" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="main">Main Store</SelectItem>
                    <SelectItem value="branch">Branch Outlet</SelectItem>
                    <SelectItem value="app">App Store</SelectItem>
                  </SelectContent>
                </Select>
              )}
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <div className={fieldWrap}>
                <Label className={labelClass}>Payment Type</Label>
                <Select defaultValue="master">
                  <SelectTrigger className={controlClass}>
                    <SelectValue placeholder="Payment type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="master">Master Card</SelectItem>
                    <SelectItem value="visa">Visa</SelectItem>
                    <SelectItem value="cash">Cash</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className={fieldWrap}>
                <Label className={labelClass}>Order Type</Label>
                <Select defaultValue="home">
                  <SelectTrigger className={controlClass}>
                    <SelectValue placeholder="Order type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="home">Home Delivery</SelectItem>
                    <SelectItem value="pickup">Pick Up</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className={fieldWrap}>
              <Label className={labelClass}>Date &amp; Time</Label>
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="relative">
                  <CalendarDays className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[#98A2B3]" aria-hidden />
                  <Input type="date" defaultValue="2024-01-06" className={`${controlClass} pr-10`} />
                </div>
                <div className="relative">
                  <Clock3 className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[#98A2B3]" aria-hidden />
                  <Input type="time" defaultValue="14:38" className={`${controlClass} pr-10`} />
                </div>
              </div>
            </div>

            <div className={fieldWrap}>
              <Label className={labelClass}>Order Status</Label>
              <Select defaultValue="pending">
                <SelectTrigger className={controlClass}>
                  <SelectValue placeholder="Order status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="process">Process</SelectItem>
                  <SelectItem value="completed">Completed</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className={fieldWrap}>
              <Label className={labelClass}>Order Note</Label>
              <Textarea
                value={orderNote}
                onChange={(e) => setOrderNote(e.target.value)}
                rows={5}
                className="min-h-[120px] resize-none rounded-md border-0 bg-[#F3F4F6] px-3 py-2.5 text-[13px] text-[#1C1D22] placeholder:text-[#98A2B3] focus-visible:ring-1 focus-visible:ring-[#003E6B]/25"
              />
            </div>

            <button
              type="button"
              onClick={() => router.push(`/${app}/orders/new/shipping-label`)}
              className="flex w-full items-center justify-between gap-3 rounded-lg border border-dashed border-[#C5CED8] bg-[#FAFBFC] px-4 py-3.5 text-left transition-colors hover:border-[#8DA9C4] hover:bg-[#F4F7FA]"
            >
              <span className="text-[13px] font-medium text-[#475467]">Create Shipping Label</span>
              <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-[#E8F1FF] text-[#2E90FA]">
                <Plus className="size-4" strokeWidth={2.5} aria-hidden />
              </span>
            </button>
          </div>

          <div className="mt-6 flex flex-wrap justify-end gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={() => router.back()}
              className="h-10 min-w-[120px] rounded-md border-0 bg-[#F3B07C] px-6 text-[13px] font-semibold text-white shadow-none hover:bg-[#e59d68]"
            >
              Cancel
            </Button>
            <Button
              type="button"
              className="h-10 min-w-[140px] rounded-md border-0 bg-[#003E6B] px-6 text-[13px] font-semibold text-white shadow-none hover:bg-[#003256]"
              onClick={() => router.push(`/${app}/orders`)}
            >
              Create Order
            </Button>
          </div>
        </section>

        <div className="flex flex-col gap-5">
          <section className="rounded-xl border border-[#F1F3F9] bg-white p-5 shadow-[0_1px_2px_rgba(16,24,40,0.04)] md:p-6">
            <h2 className="mb-4 text-base font-semibold text-[#1C1D22]">Items</h2>
            <div className="mb-4 flex h-10 w-full items-center gap-2 rounded-md border border-[#E4E7EC] bg-white px-3">
              <Search className="size-4 shrink-0 text-[#98A2B3]" aria-hidden />
              <Input
                type="search"
                value={itemSearch}
                onChange={(e) => setItemSearch(e.target.value)}
                placeholder="Smart|phone"
                className="h-full border-0 bg-transparent p-0 text-[13px] text-[#1C1D22] placeholder:text-[#98A2B3] focus-visible:ring-0"
                aria-label="Search products"
              />
            </div>

            {items.length === 0 ? (
              <div className="flex flex-col items-center gap-4 py-6">
                <div className="flex size-[100px] items-center justify-center rounded-full border border-[#E4E7EC] bg-[#F4F5FA]">
                  <ShoppingBag className="size-9 text-[#BEC0CA]" strokeWidth={1.35} aria-hidden />
                </div>
                <div className="space-y-1 text-center">
                  <p className="text-[17px] font-bold text-[#1C1D22]">Add Products To Your Orders?</p>
                  <p className="max-w-[260px] text-[12px] leading-relaxed text-[#667085]">Search and add product to this orders</p>
                </div>
                <Button
                  type="button"
                  onClick={addSmartPhoneRow}
                  className="h-10 rounded-md bg-[#003E6B] px-6 text-[12px] font-semibold text-white hover:bg-[#003256]"
                >
                  Add Item
                </Button>
              </div>
            ) : (
              <>
                <div className="space-y-4">
                  {items.map((row) => (
                    <div key={row.id} className="border-b border-[#F1F3F9] pb-4 last:border-0 last:pb-0">
                      <div className="flex gap-3">
                        <div className="grid size-12 shrink-0 place-items-center rounded-md bg-[#F4F5FA] text-lg">{row.thumb}</div>
                        <div className="min-w-0 flex-1">
                          {newCustomer ? (
                            <>
                              <div className="flex flex-wrap items-start justify-between gap-2">
                                <div>
                                  <p className="text-[13px] font-semibold text-[#1C1D22]">{row.name}</p>
                                  <p className="text-[12px] font-medium text-[#475467]">{formatMoney(row.unitPrice)}</p>
                                </div>
                                <div className="flex flex-wrap items-center gap-2">
                                  <QtyStep value={row.qty} onChange={(n) => updateLine(row.id, { qty: n })} />
                                  <button
                                    type="button"
                                    onClick={() => removeLine(row.id)}
                                    className="text-[11px] font-semibold text-[#D92D20] hover:underline"
                                  >
                                    Remove
                                  </button>
                                </div>
                              </div>
                              <p className="mt-2 text-[11px] text-[#667085]">
                                Sold Price{" "}
                                <span className="font-semibold text-[#1C1D22]">{formatMoney(row.soldPrice)}</span>
                              </p>
                            </>
                          ) : (
                            <div className="flex flex-wrap items-start justify-between gap-3">
                              <div>
                                <p className="text-[13px] font-semibold text-[#1C1D22]">{row.name}</p>
                                <p className="mt-0.5 text-[12px] font-medium text-[#475467]">{formatMoney(row.unitPrice)}</p>
                              </div>
                              <div className="flex flex-col items-end gap-2">
                                <span className="rounded-full bg-[#E8F4FF] px-2.5 py-0.5 text-[10px] font-semibold text-[#1570EF]">
                                  In Stock: {row.stock}
                                </span>
                                <button
                                  type="button"
                                  onClick={() => addSmartPhoneRow()}
                                  className="text-[11px] font-semibold text-[#1570EF] hover:underline"
                                >
                                  Add Item
                                </button>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="mt-4 flex justify-center border-t border-[#F1F3F9] pt-3">
                  <button
                    type="button"
                    onClick={() => {
                      if (newCustomer) {
                        const nextId = `row-${Date.now()}`;
                        setItems((prev) => [
                          ...prev,
                          {
                            id: nextId,
                            name: "Lorem Ipsum",
                            unitPrice: 1500,
                            soldPrice: 1500,
                            qty: 1,
                            stock: 20,
                            thumb: "📦",
                          },
                        ]);
                      } else {
                        addSmartPhoneRow();
                      }
                    }}
                    className="text-[12px] font-semibold text-[#1570EF] hover:underline"
                  >
                    Add Item
                  </button>
                </div>

                {newCustomer ? (
                  <div className="mt-5 space-y-2 border-t border-[#F1F3F9] pt-4 text-[12px]">
                    <div className="flex justify-between text-[#667085]">
                      <span>Shipping Cost</span>
                      <span className="font-medium text-[#1C1D22]">{formatMoney(shippingCost)}</span>
                    </div>
                    <div className="flex justify-between text-[#667085]">
                      <span>Platform Fees (optional)</span>
                      <span className="font-medium text-[#1C1D22]">{formatMoney(platformFees)}</span>
                    </div>
                    <div className="flex justify-between text-[#667085]">
                      <span>Cost Price</span>
                      <span className="font-medium text-[#1C1D22]">{formatMoney(costPrice)}</span>
                    </div>
                    <div className="flex justify-between text-[#667085]">
                      <span>Profit Margin</span>
                      <span className="font-medium text-[#1C1D22]">{formatMoney(profitMargin)}</span>
                    </div>
                    <div className="flex justify-between border-t border-dashed border-[#E4E7EC] pt-2 font-medium text-[#344054]">
                      <span>Sub-total</span>
                      <span>{formatMoney(subtotal)}</span>
                    </div>
                    <div className="flex justify-between text-[14px] font-bold text-[#1C1D22]">
                      <span>Total</span>
                      <span>{formatMoney(orderTotal)}</span>
                    </div>
                  </div>
                ) : null}
              </>
            )}
          </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">
            <h2 className="mb-4 text-base font-semibold text-[#1C1D22]">Add Attachments</h2>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-stretch">
              <div className="flex min-h-10 flex-1 items-center rounded-md border border-[#E4E7EC] bg-[#F9FAFB] px-3 text-[12px] text-[#667085]">
                {fileName ?? "Add Attachment"}
              </div>
              <input
                ref={fileInputRef}
                type="file"
                className="sr-only"
                onChange={(e) => {
                  const f = e.target.files?.[0];
                  setFileName(f?.name ?? null);
                }}
              />
              <Button
                type="button"
                variant="outline"
                onClick={() => fileInputRef.current?.click()}
                className="h-10 shrink-0 rounded-md border-[#D1E9FF] bg-[#E8F4FF] px-4 text-[12px] font-semibold text-[#1570EF] hover:bg-[#d9ecff]"
              >
                Choose File
              </Button>
            </div>
            <div className="mt-4 flex justify-end">
              <Button
                type="button"
                className="h-10 rounded-md bg-[#003E6B] px-6 text-[12px] font-semibold text-white hover:bg-[#003256]"
              >
                Upload Attachment
              </Button>
            </div>
          </section>

          <p className="text-center text-[11px] text-[#98A2B3]">
            Need a new SKU?{" "}
            <Link href={`/${app}/products/new`} className="font-semibold text-[#1570EF] hover:underline">
              New Product
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
