"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import api from "@/lib/api";
import { getGuestToken } from "@/lib/guestToken";

import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";

import {
  ArrowLeft,
  MapPin,
  Phone,
  User,
  Mail,
  CreditCard,
  Truck,
  ShieldCheck,
} from "lucide-react";

interface CartItem {
  id: number;
  quantity: number;
  price: string;

  product?: {
    name: string;
    image?: string | null;
    unit_value?: string;
    unit_type?: string;
  };
}

export default function CheckoutPage() {
  const [items, setItems] = useState<CartItem[]>([]);

  const [loading, setLoading] = useState(true);

  const [paymentMethod, setPaymentMethod] =
    useState("cod");

  const [deliveryArea, setDeliveryArea] =
    useState("inside_dhaka");

  const [form, setForm] = useState({
    name: "",
    phone: "",
    email: "",

    address_line: "",

    city: "Dhaka",

    state: "",

    postal_code: "",

    country: "Bangladesh",

    note: "",
  });

  useEffect(() => {
    fetchCart();
  }, []);

  const fetchCart = async () => {
    try {
      setLoading(true);

      const res = await api.get("/cart", {
        params: {
          guest_token: getGuestToken(),
        },
      });

      setItems(res.data.data || []);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const subtotal = items.reduce(
    (total, item) =>
      total +
      Number(item.price) *
        Number(item.quantity),
    0
  );

  const shipping =
    subtotal > 0
      ? deliveryArea === "inside_dhaka"
        ? 80
        : 120
      : 0;

  const total = subtotal + shipping;

  const handleOrder = async () => {
    if (
      !form.name ||
      !form.phone ||
      !form.address_line ||
      !form.city
    ) {
      alert(
        "Please fill required shipping information"
      );

      return;
    }

    try {
      await api.post("/orders", {
        guest_token: getGuestToken(),

        guest_name: form.name,

        guest_phone: form.phone,

        guest_email: form.email,

        address_line: form.address_line,

        city: form.city,

        state: form.state,

        postal_code: form.postal_code,

        country: form.country,

        notes: form.note,

        payment_method: paymentMethod,

        delivery_area: deliveryArea,

        shipping_cost: shipping,

        subtotal,

        total_amount: total,
      });

      window.dispatchEvent(
        new Event("cart-updated")
      );

      alert("Order placed successfully");
    } catch (error) {
      console.error(error);

      alert(
        "Order API not ready or something went wrong"
      );
    }
  };

  return (
    <>
      <Navbar />

      <main className="min-h-screen bg-[#f7fff8]">
        <section className="max-w-7xl mx-auto px-4 py-10">
          <Link
            href="/cart"
            className="inline-flex items-center gap-2 text-green-600 font-black mb-6"
          >
            <ArrowLeft size={18} />
            Back to Cart
          </Link>

          <div className="mb-8">
            <h1 className="text-4xl md:text-5xl font-black text-slate-900">
              Checkout
            </h1>

            <p className="text-slate-500 mt-3">
              Complete your order with delivery
              and payment information.
            </p>
          </div>

          <div className="grid lg:grid-cols-[1fr_390px] gap-8">
            {/* LEFT SIDE */}
            <div className="space-y-6">
              {/* SHIPPING INFO */}
              <div className="bg-white rounded-[2rem] p-6 border border-green-100 shadow-sm">
                <h2 className="text-2xl font-black mb-6 flex items-center gap-3">
                  <User className="text-green-600" />
                  Shipping Information
                </h2>

                <div className="grid md:grid-cols-2 gap-4">
                  <Input
                    icon={<User size={18} />}
                    placeholder="Full Name *"
                    value={form.name}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        name: v,
                      })
                    }
                  />

                  <Input
                    icon={<Phone size={18} />}
                    placeholder="Phone Number *"
                    value={form.phone}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        phone: v,
                      })
                    }
                  />

                  <Input
                    icon={<Mail size={18} />}
                    placeholder="Email Address"
                    value={form.email}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        email: v,
                      })
                    }
                  />

                  <Input
                    icon={<MapPin size={18} />}
                    placeholder="City *"
                    value={form.city}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        city: v,
                      })
                    }
                  />

                  <Input
                    icon={<MapPin size={18} />}
                    placeholder="State / Area"
                    value={form.state}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        state: v,
                      })
                    }
                  />

                  <Input
                    icon={<MapPin size={18} />}
                    placeholder="Postal Code"
                    value={form.postal_code}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        postal_code: v,
                      })
                    }
                  />

                  <Input
                    icon={<MapPin size={18} />}
                    placeholder="Country"
                    value={form.country}
                    onChange={(v) =>
                      setForm({
                        ...form,
                        country: v,
                      })
                    }
                  />
                </div>

                <textarea
                  placeholder="Full Address *"
                  value={form.address_line}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      address_line:
                        e.target.value,
                    })
                  }
                  className="mt-4 w-full min-h-32 bg-slate-100 border border-slate-200 rounded-2xl px-5 py-4 outline-none focus:border-green-500"
                />

                <textarea
                  placeholder="Order Note (Optional)"
                  value={form.note}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      note: e.target.value,
                    })
                  }
                  className="mt-4 w-full min-h-24 bg-slate-100 border border-slate-200 rounded-2xl px-5 py-4 outline-none focus:border-green-500"
                />
              </div>

              {/* DELIVERY AREA */}
              <div className="bg-white rounded-[2rem] p-6 border border-green-100 shadow-sm">
                <h2 className="text-2xl font-black mb-6 flex items-center gap-3">
                  <Truck className="text-green-600" />
                  Delivery Area
                </h2>

                <div className="grid md:grid-cols-2 gap-4">
                  <button
                    onClick={() =>
                      setDeliveryArea(
                        "inside_dhaka"
                      )
                    }
                    className={`rounded-3xl p-5 border-2 text-left transition ${
                      deliveryArea ===
                      "inside_dhaka"
                        ? "border-green-600 bg-green-50"
                        : "border-slate-100 bg-slate-50"
                    }`}
                  >
                    <h3 className="font-black text-lg">
                      Inside Dhaka
                    </h3>

                    <p className="text-slate-500 text-sm mt-1">
                      Delivery charge ৳80
                    </p>
                  </button>

                  <button
                    onClick={() =>
                      setDeliveryArea(
                        "outside_dhaka"
                      )
                    }
                    className={`rounded-3xl p-5 border-2 text-left transition ${
                      deliveryArea ===
                      "outside_dhaka"
                        ? "border-green-600 bg-green-50"
                        : "border-slate-100 bg-slate-50"
                    }`}
                  >
                    <h3 className="font-black text-lg">
                      Outside Dhaka
                    </h3>

                    <p className="text-slate-500 text-sm mt-1">
                      Delivery charge ৳120
                    </p>
                  </button>
                </div>
              </div>

              {/* PAYMENT */}
              <div className="bg-white rounded-[2rem] p-6 border border-green-100 shadow-sm">
                <h2 className="text-2xl font-black mb-6 flex items-center gap-3">
                  <CreditCard className="text-green-600" />
                  Payment Method
                </h2>

                <div className="space-y-4">
                  <button
                    onClick={() =>
                      setPaymentMethod("cod")
                    }
                    className={`w-full rounded-3xl p-5 border-2 text-left transition ${
                      paymentMethod === "cod"
                        ? "border-green-600 bg-green-50"
                        : "border-slate-100 bg-slate-50"
                    }`}
                  >
                    <h3 className="font-black text-lg">
                      Cash on Delivery
                    </h3>

                    <p className="text-slate-500 text-sm mt-1">
                      Pay when you receive your
                      order.
                    </p>
                  </button>

                  <button
                    onClick={() =>
                      setPaymentMethod(
                        "sslcommerz"
                      )
                    }
                    className={`w-full rounded-3xl p-5 border-2 text-left transition ${
                      paymentMethod ===
                      "sslcommerz"
                        ? "border-green-600 bg-green-50"
                        : "border-slate-100 bg-slate-50"
                    }`}
                  >
                    <h3 className="font-black text-lg">
                      SSLCommerz
                    </h3>

                    <p className="text-slate-500 text-sm mt-1">
                      Card, bKash, Nagad,
                      Rocket payment option.
                    </p>
                  </button>
                </div>
              </div>
            </div>

            {/* RIGHT SIDE */}
            <aside>
              <div className="sticky top-28 bg-white rounded-[2rem] border border-green-100 shadow-sm p-6">
                <h2 className="text-2xl font-black mb-6">
                  Order Summary
                </h2>

                {loading ? (
                  <div className="h-56 bg-slate-100 rounded-3xl animate-pulse" />
                ) : (
                  <>
                    <div className="space-y-4 max-h-72 overflow-y-auto pr-2">
                      {items.map((item) => (
                        <div
                          key={item.id}
                          className="flex gap-3"
                        >
                          <img
                            src={
                              item.product
                                ?.image ||
                              "https://via.placeholder.com/200"
                            }
                            alt={
                              item.product
                                ?.name ||
                              "Product"
                            }
                            className="w-16 h-16 rounded-2xl object-cover bg-slate-100"
                          />

                          <div className="flex-1">
                            <h4 className="font-black text-sm line-clamp-2">
                              {
                                item.product
                                  ?.name
                              }
                            </h4>

                            <p className="text-xs text-slate-500">
                              Qty:{" "}
                              {Number(
                                item.quantity
                              )}
                            </p>
                          </div>

                          <p className="font-black">
                            ৳
                            {Number(
                              item.price
                            ) *
                              Number(
                                item.quantity
                              )}
                          </p>
                        </div>
                      ))}
                    </div>

                    <div className="border-t border-slate-100 mt-6 pt-5 space-y-4">
                      <Row
                        label="Subtotal"
                        value={`৳${subtotal}`}
                      />

                      <Row
                        label="Delivery Charge"
                        value={`৳${shipping}`}
                      />

                      <div className="flex justify-between text-xl border-t border-slate-100 pt-4">
                        <span className="font-black">
                          Total
                        </span>

                        <span className="font-black text-green-600">
                          ৳{total}
                        </span>
                      </div>
                    </div>

                    <button
                      onClick={handleOrder}
                      disabled={
                        items.length === 0
                      }
                      className="cursor-pointer mt-7 w-full bg-green-600 hover:bg-green-700 disabled:bg-slate-300 text-white rounded-2xl py-4 font-black transition"
                    >
                      Place Order
                    </button>

                    <div className="mt-5 flex items-center justify-center gap-2 text-xs text-slate-400">
                      <ShieldCheck
                        size={16}
                      />
                      Secure checkout without
                      login
                    </div>
                  </>
                )}
              </div>
            </aside>
          </div>
        </section>
      </main>

      <Footer />
    </>
  );
}

function Input({
  icon,
  placeholder,
  value,
  onChange,
}: {
  icon: React.ReactNode;
  placeholder: string;
  value: string;
  onChange: (value: string) => void;
}) {
  return (
    <div className="relative">
      <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
        {icon}
      </div>

      <input
        value={value}
        onChange={(e) =>
          onChange(e.target.value)
        }
        placeholder={placeholder}
        className="w-full bg-slate-100 border border-slate-200 rounded-2xl py-4 pl-12 pr-4 outline-none focus:border-green-500"
      />
    </div>
  );
}

function Row({
  label,
  value,
}: {
  label: string;
  value: string;
}) {
  return (
    <div className="flex justify-between text-sm">
      <span className="text-slate-500 font-bold">
        {label}
      </span>

      <span className="font-black">
        {value}
      </span>
    </div>
  );
}