"use client";

import { useEffect, useMemo, useState } from "react";
import { algerianWilayas } from "@/lib/constants";

type DeliveryOption = "HOME" | "DESK";

type PatientLike = {
  id: string;
  name: string;
  firstName?: string | null;
};

const BASE_PRICE_DZD = 2900;

const wilayaTariff: Record<string, number> = {
  "El Tarf": 400,
  Annaba: 400,
  Algiers: 600,
  "Bordj Bou Arreridj": 500,
};

function getWilayaShippingFee(wilaya: string): number {
  if (wilaya === "El Tarf" || wilaya === "Annaba") return 400;
  if (wilayaTariff[wilaya] != null) return wilayaTariff[wilaya];
  return 700;
}

function clampMin(value: number, min: number) {
  return Math.max(min, value);
}

function NeonBadgeIcon() {
  return (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
    >
      <path
        d="M12 2l2.2 6.7H21l-5.6 4 2.1 7L12 15.9 6.5 19.7l2.1-7L3 8.7h6.8L12 2z"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      width="56"
      height="56"
      viewBox="0 0 56 56"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
    >
      <path
        d="M28 4.5c13 0 23.5 10.5 23.5 23.5S41 51.5 28 51.5 4.5 41 4.5 28 15 4.5 28 4.5z"
        stroke="currentColor"
        strokeWidth="2"
        opacity="0.25"
      />
      <path
        d="M16 28.2l7.2 7.3L40.2 18.6"
        stroke="currentColor"
        strokeWidth="3"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SparkMockup() {
  return (
    <div className="relative">
      <div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-fuchsia-500/20 via-purple-500/10 to-cyan-500/10 blur-[30px]" />
      <div className="relative overflow-hidden rounded-2xl border border-white/10 bg-white/[0.04] backdrop-blur-md">
        <div className="p-5">
          <div className="flex items-center justify-between">
            <div className="rounded-lg border border-white/10 bg-black/30 px-2.5 py-1 text-xs text-zinc-200">
              QR EDITION
            </div>
            <div className="text-xs font-semibold text-purple-300 drop-shadow-[0_0_16px_rgba(168,85,247,0.6)]">
              2,900 DA
            </div>
          </div>

          <div className="mt-4 grid place-items-center">
            <div className="relative h-[190px] w-[240px] rounded-2xl border border-white/10 bg-gradient-to-b from-zinc-950/40 to-zinc-900/60">
              <div className="absolute left-1/2 top-4 h-2 w-24 -translate-x-1/2 rounded-full bg-purple-400/20 blur-md" />
              <div className="absolute left-1/2 top-5 h-2 w-20 -translate-x-1/2 rounded-full bg-purple-400/60 blur" />

              <div className="absolute inset-3 rounded-xl border border-white/10 bg-white/[0.04]" />

              <div className="absolute inset-x-6 top-10 flex flex-col items-center gap-2">
                <div className="h-10 w-full rounded-lg border border-white/10 bg-black/30" />
                <div className="grid h-[76px] w-full grid-cols-8 gap-1 rounded-lg border border-white/10 bg-zinc-950/40 p-2">
                  {Array.from({ length: 64 }).map((_, i) => (
                    <div
                      // eslint-disable-next-line react/no-array-index-key
                      key={i}
                      className={`h-2 rounded-[2px] ${
                        i % 7 === 0 || i % 13 === 0
                          ? "bg-fuchsia-400/70"
                          : i % 9 === 0
                          ? "bg-purple-400/60"
                          : "bg-white/10"
                      }`}
                    />
                  ))}
                </div>
              </div>

              <div className="absolute bottom-4 left-1/2 w-[120px] -translate-x-1/2 rounded-full border border-white/10 bg-black/30 px-4 py-2 text-center text-xs text-zinc-200">
                Scan → Patient Profile
              </div>

              {/* mock band */}
              <div className="absolute -bottom-8 left-6 h-20 w-[210px] -rotate-1 rounded-full border border-white/10 bg-gradient-to-r from-purple-500/10 via-fuchsia-500/10 to-cyan-500/10" />
            </div>
          </div>

          <div className="mt-4 grid grid-cols-3 gap-2">
            {["Cloud Sync", "GPS Alternative", "Water Resistant"].map(
              (t, idx) => (
                <div
                  key={t}
                  className={`col-span-1 rounded-xl border border-white/10 bg-white/[0.04] p-3 text-xs text-zinc-200 ${
                    idx === 0
                      ? "shadow-[0_0_26px_rgba(168,85,247,0.25)]"
                      : idx === 1
                      ? "shadow-[0_0_26px_rgba(236,72,153,0.18)]"
                      : "shadow-[0_0_26px_rgba(34,211,238,0.12)]"
                  }`}
                >
                  {t}
                </div>
              )
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default function FamilyStore() {
  const [patients, setPatients] = useState<PatientLike[]>([]);

  const [patientsLoading, setPatientsLoading] = useState(true);

  const [patientId, setPatientId] = useState("");
  const [wilaya, setWilaya] = useState("");
  const [quantity, setQuantity] = useState(1);
  const [address, setAddress] = useState("");
  const [deliveryOption, setDeliveryOption] = useState<DeliveryOption>(
    "HOME"
  );

  const [submitState, setSubmitState] = useState<
    "idle" | "submitting" | "success"
  >("idle");

  // Caregiver/order email request state is driven by submitState
  const [submitError, setSubmitError] = useState<string>("");

  useEffect(() => {
    let cancelled = false;

    async function loadPatients() {
      setPatientsLoading(true);
      setSubmitError("");

      try {
        const res = await fetch("/api/family/patients");
        if (!res.ok) throw new Error("Failed to load patients");
        const data = (await res.json()) as { patients: PatientLike[] };
        if (!cancelled) setPatients(data.patients ?? []);
      } catch {
        // Fallback: keep empty list; select will remain invalid.
        if (!cancelled) setPatients([]);
      } finally {
        if (!cancelled) setPatientsLoading(false);
      }
    }

    loadPatients();
    return () => {
      cancelled = true;
    };
  }, []);

  const baseSubtotal = useMemo(
    () => BASE_PRICE_DZD * quantity,
    [quantity]
  );

  const shippingFee = useMemo(() => {
    if (!wilaya) return 0;
    return getWilayaShippingFee(wilaya);
  }, [wilaya]);

  const grandTotal = useMemo(() => {
    if (!wilaya) return 0;
    return baseSubtotal + shippingFee;
  }, [baseSubtotal, shippingFee, wilaya]);

  function handleQtyDelta(delta: number) {
    setQuantity((q) => clampMin(q + delta, 1));
  }

  function validate(): string | null {
    if (!patientId) return "Patient is required.";
    if (!wilaya) return "Wilaya is required.";
    if (!address.trim()) return "Detailed address is required.";
    return null;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitError("");

    const err = validate();
    if (err) {
      setSubmitError(err);
      return;
    }

    setSubmitState("submitting");

    const selectedPatient = patients.find((p) => p.id === patientId);

    const payload = {
      patient: {
        id: patientId,
        name:
          selectedPatient?.name && selectedPatient?.firstName
            ? `${selectedPatient.name} ${selectedPatient.firstName ?? ""}`.trim()
            : selectedPatient?.firstName
            ? `${selectedPatient.name} ${selectedPatient.firstName}`.trim()
            : selectedPatient?.name ?? "",
      },
      shipping: {
        wilaya,
        fullDeliveryAddress: address,
        shippingMethod: deliveryOption,
      },
      financial: {
        quantityOrdered: quantity,
        dynamicShippingFee: shippingFee,
        grandTotalAmountDA: grandTotal,
      },
      computed: {
        basePricePerBandDA: BASE_PRICE_DZD,
        baseSubtotalDA: baseSubtotal,
      },
    };

    try {
      const res = await fetch("/api/order/send-email", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const maybe = await res.json().catch(() => null);
        const msg =
          maybe?.error ??
          "Failed to send the order email notification.";
        throw new Error(msg);
      }

      setSubmitState("success");
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setSubmitError(message);
      setSubmitState("idle");
    }
  }

  if (submitState === "success") {
    return (
      <section aria-live="polite" className="rounded-2xl border border-white/10 bg-white/[0.05] p-6 backdrop-blur-md">
        <div className="flex flex-col items-center text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-emerald-500/10 text-emerald-300 shadow-[0_0_42px_rgba(52,211,153,0.25)]">
            <CheckIcon />
          </div>
          <h2 className="mt-4 text-2xl font-bold text-zinc-50">
            تم تسجيل طلبكِ بنجاح!
          </h2>
          <p className="mt-2 max-w-md text-sm text-zinc-300">
            سيقوم أحد الوكلاء بالاتصال بكِ خلال 24 ساعة لتأكيد بيانات
            برمجة السوار.
          </p>

          <div className="mt-6 grid w-full max-w-xl gap-3 rounded-2xl border border-white/10 bg-zinc-950/30 p-4">
            <div className="rounded-xl border border-white/10 bg-white/[0.05] p-3">
              <p className="text-xs font-semibold text-indigo-300">
                Next step
              </p>
              <p className="mt-1 text-sm text-zinc-200">
                Verify programming details and delivery address.
              </p>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section>
      <div className="grid grid-cols-1 gap-8 lg:grid-cols-12">
        {/* LEFT: product showcase */}
        <div className="lg:col-span-5">
          <div className="rounded-2xl border border-white/10 bg-white/[0.05] p-5 shadow-[0_0_0_1px_rgba(255,255,255,0.03)] backdrop-blur-md">
            <div className="flex items-center justify-between gap-4">
              <div>
                <h2 className="text-xl font-bold text-zinc-50">
                  RememberMe Smart Band
                </h2>
                <p className="mt-1 text-sm text-zinc-300">
                  QR Edition — quick-load patient profile view.
                </p>
              </div>
              <div className="relative flex items-center gap-2">
                <div className="animate-pulse rounded-full bg-fuchsia-500/20 p-2 text-fuchsia-300 shadow-[0_0_34px_rgba(236,72,153,0.35)]">
                  <NeonBadgeIcon />
                </div>
                <div className="rounded-full border border-fuchsia-300/20 bg-fuchsia-500/10 px-3 py-1 text-xs font-semibold text-fuchsia-200 shadow-[0_0_24px_rgba(236,72,153,0.25)]">
                  <span className="block leading-none">
                    جاهز للبرمجة
                  </span>
                  <span className="block text-[11px] text-fuchsia-100">
                    Ready to Program
                  </span>
                </div>
              </div>
            </div>

            <div className="mt-5">
              <SparkMockup />
            </div>

            <div className="mt-5 grid gap-3 sm:grid-cols-3">
              {["Cloud Sync", "GPS-Alternative", "Water Resistant"].map(
                (item, idx) => (
                  <div
                    key={item}
                    className={`flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-3 ${
                      idx === 0
                        ? "shadow-[0_0_36px_rgba(168,85,247,0.20)]"
                        : idx === 1
                        ? "shadow-[0_0_36px_rgba(236,72,153,0.16)]"
                        : "shadow-[0_0_36px_rgba(34,211,238,0.10)]"
                    }`}
                  >
                    <span className="h-2.5 w-2.5 rounded-full bg-fuchsia-400/80 shadow-[0_0_18px_rgba(236,72,153,0.6)]" />
                    <span className="text-sm text-zinc-200">{item}</span>
                  </div>
                )
              )}
            </div>

            <div className="mt-5 rounded-xl border border-white/10 bg-zinc-950/30 p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-zinc-300">Base price</span>
                <span className="font-mono text-lg font-semibold text-indigo-200">
                  {BASE_PRICE_DZD.toLocaleString("fr-FR")} DA
                </span>
              </div>
              <div className="mt-1 text-xs text-zinc-500">
                Fixed price (per band) — shipping calculated below.
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT: shipping & billing */}
        <div className="lg:col-span-7">
          <div className="rounded-2xl border border-white/10 bg-white/[0.05] p-5 backdrop-blur-md">
            <form onSubmit={handleSubmit} className="space-y-5">
              {/* Patient + Wilaya */}
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <label
                    htmlFor="patientId"
                    className="text-sm font-medium text-zinc-200"
                  >
                    المريض (Patient) <span className="text-fuchsia-300">*</span>
                  </label>
                  <select
                    id="patientId"
                    required
                    value={patientId}
                    onChange={(e) => setPatientId(e.target.value)}
                    disabled={patientsLoading || submitState === "submitting"}
                    className="w-full appearance-none rounded-lg border border-white/10 bg-zinc-950/40 px-3 py-2.5 text-sm text-zinc-100 outline-none transition-colors focus:border-fuchsia-300/40 focus:ring-1 focus:ring-fuchsia-300/30 disabled:opacity-60"
                  >
                    <option value="" disabled>
                      {patientsLoading
                        ? "Loading patients..."
                        : "Select a patient"}
                    </option>
                    {patients.map((p) => (
                      <option key={p.id} value={p.id}>
                        {p.name} {p.firstName ?? ""}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <label
                    htmlFor="wilaya"
                    className="text-sm font-medium text-zinc-200"
                  >
                    58 Wilayas / الولاية <span className="text-fuchsia-300">*</span>
                  </label>
                  <select
                    id="wilaya"
                    required
                    value={wilaya}
                    onChange={(e) => setWilaya(e.target.value)}
                    disabled={submitState === "submitting"}
                    className="w-full appearance-none rounded-lg border border-white/10 bg-zinc-950/40 px-3 py-2.5 text-sm text-zinc-100 outline-none transition-colors focus:border-fuchsia-300/40 focus:ring-1 focus:ring-fuchsia-300/30 disabled:opacity-60"
                  >
                    <option value="" disabled>
                      Select a wilaya
                    </option>
                    {algerianWilayas.map((w) => (
                      <option key={w} value={w}>
                        {w}
                      </option>
                    ))}
                  </select>

                  {wilaya ? (
                    <p className="text-xs text-zinc-500">
                      Shipping fee: {getWilayaShippingFee(wilaya)} DA
                    </p>
                  ) : null}
                </div>
              </div>

              {/* Quantity + Address */}
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <label className="text-sm font-medium text-zinc-200">
                    Quantity
                  </label>
                  <div className="flex items-center gap-3 rounded-xl border border-white/10 bg-zinc-950/40 p-3">
                    <button
                      type="button"
                      onClick={() => handleQtyDelta(-1)}
                      aria-label="Decrease quantity"
                      disabled={quantity <= 1 || submitState === "submitting"}
                      className="flex h-10 w-10 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-zinc-200 transition hover:border-fuchsia-300/30 hover:text-fuchsia-200 disabled:opacity-50"
                    >
                      <span className="text-lg font-bold">-</span>
                    </button>

                    <div className="flex-1 text-center">
                      <div className="text-xs text-zinc-500">Min 1</div>
                      <div className="font-mono text-lg font-semibold text-zinc-100">
                        {quantity}
                      </div>
                    </div>

                    <button
                      type="button"
                      onClick={() => handleQtyDelta(1)}
                      aria-label="Increase quantity"
                      disabled={submitState === "submitting"}
                      className="flex h-10 w-10 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-zinc-200 transition hover:border-fuchsia-300/30 hover:text-fuchsia-200 disabled:opacity-60"
                    >
                      <span className="text-lg font-bold">+</span>
                    </button>
                  </div>
                </div>

                <div className="space-y-2">
                  <label
                    htmlFor="deliveryOption"
                    className="text-sm font-medium text-zinc-200"
                  >
                    Delivery Option
                  </label>
                  <fieldset id="deliveryOption" className="space-y-2">
                    <div className="grid grid-cols-2 gap-2">
                      <label className="cursor-pointer">
                        <input
                          type="radio"
                          name="deliveryOption"
                          value="HOME"
                          checked={deliveryOption === "HOME"}
                          onChange={() => setDeliveryOption("HOME")}
                          disabled={submitState === "submitting"}
                          className="sr-only"
                        />
                        <span
                          className={`block rounded-xl border px-3 py-2 text-center text-sm transition-all ${
                            deliveryOption === "HOME"
                              ? "border-purple-300/40 bg-purple-500/15 text-purple-200 shadow-[0_0_30px_rgba(168,85,247,0.25)]"
                              : "border-white/10 bg-white/[0.04] text-zinc-200 hover:border-fuchsia-300/20"
                          }`}
                        >
                          Home Delivery
                          <span className="block text-[11px] text-zinc-500">
                            (Yalidine Home)
                          </span>
                        </span>
                      </label>

                      <label className="cursor-pointer">
                        <input
                          type="radio"
                          name="deliveryOption"
                          value="DESK"
                          checked={deliveryOption === "DESK"}
                          onChange={() => setDeliveryOption("DESK")}
                          disabled={submitState === "submitting"}
                          className="sr-only"
                        />
                        <span
                          className={`block rounded-xl border px-3 py-2 text-center text-sm transition-all ${
                            deliveryOption === "DESK"
                              ? "border-pink-300/40 bg-fuchsia-500/15 text-fuchsia-200 shadow-[0_0_30px_rgba(236,72,153,0.20)]"
                              : "border-white/10 bg-white/[0.04] text-zinc-200 hover:border-fuchsia-300/20"
                          }`}
                        >
                          Desk Pickup
                          <span className="block text-[11px] text-zinc-500">
                            (Yalidine Desk)
                          </span>
                        </span>
                      </label>
                    </div>
                  </fieldset>
                </div>
              </div>

              <div className="space-y-2">
                <label
                  htmlFor="address"
                  className="text-sm font-medium text-zinc-200"
                >
                  Detailed Address / العنوان بالتفصيل <span className="text-fuchsia-300">*</span>
                </label>
                <textarea
                  id="address"
                  required
                  value={address}
                  onChange={(e) => setAddress(e.target.value)}
                  disabled={submitState === "submitting"}
                  placeholder="Street, district, building number, etc."
                  rows={4}
                  className="w-full resize-none rounded-xl border border-white/10 bg-zinc-950/40 px-3 py-2.5 text-sm text-zinc-100 outline-none transition-colors focus:border-fuchsia-300/40 focus:ring-1 focus:ring-fuchsia-300/30 disabled:opacity-60"
                />
              </div>

              {/* Invoice */}
              <div className="rounded-2xl border border-white/10 bg-zinc-950/30 p-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-sm font-semibold text-zinc-200">
                    Invoice Preview
                  </h3>
                  <span className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs text-zinc-400">
                    Monospace breakdown
                  </span>
                </div>

                <div className="mt-3 rounded-xl border border-white/10 bg-white/[0.03] p-3">
                  <div className="font-mono text-xs text-zinc-200">
                    <div className="flex items-center justify-between">
                      <span>Subtotal</span>
                      <span>
                        {BASE_PRICE_DZD.toLocaleString("fr-FR")} × {quantity}
                      </span>
                    </div>
                    <div className="mt-1 flex items-center justify-between text-zinc-300">
                      <span>
                        Subtotal (Base Price * Quantity)
                      </span>
                      <span>{baseSubtotal.toLocaleString("fr-FR")} DA</span>
                    </div>

                    <div className="mt-2 flex items-center justify-between">
                      <span>Wilaya Shipping Fee</span>
                      <span className="text-zinc-100">
                        {wilaya ? shippingFee.toLocaleString("fr-FR") : "—"} DA
                      </span>
                    </div>

                    <div className="mt-3 border-t border-white/10 pt-3">
                      <div className="flex items-center justify-between">
                        <span className="text-zinc-300">
                          Grand Total Amount
                        </span>
                        <span className="text-lg font-semibold text-indigo-200">
                          {wilaya ? grandTotal.toLocaleString("fr-FR") : "—"} DA
                        </span>
                      </div>
                      <div className="mt-1 text-[11px] text-zinc-500">
                        Pay on delivery.
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {submitError ? (
                <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200">
                  {submitError}
                </div>
              ) : null}

              {/* Action */}
              <button
                type="submit"
                disabled={submitState === "submitting"}
                className="w-full rounded-xl bg-gradient-to-r from-purple-600 to-fuchsia-600 px-5 py-3.5 text-sm font-semibold text-white shadow-[0_0_0_1px_rgba(255,255,255,0.08)] transition-all hover:shadow-[0_0_36px_rgba(236,72,153,0.35)] hover:brightness-110 disabled:opacity-60"
              >
                {submitState === "submitting"
                  ? "جاري إرسال الطلب..."
                  : "تأكيد شراء السوار والدفع عند الاستلام / Confirm Purchase"}
              </button>
            </form>
          </div>

          <div className="mt-4 text-xs text-zinc-500">
            Note: Shipping fee is calculated using Yalidine tariffs.
          </div>
        </div>
      </div>

      {/* Small local API placeholder note */}
      <div className="hidden">
        <p>
          This component expects a GET /api/family/patients endpoint returning
          {"{ patients: PatientLike[] }"}.
        </p>
      </div>
    </section>
  );
}

