"use client";

import { useState, useEffect } from "react";
import type { ItemReservation, PlaceReservationPayload } from "@/types";
import { useLanguage } from "@/lib/language-context";
import { getAuthHeaders } from "@/lib/auth-store";
import Link from "next/link";
import PhoneInput from "@/components/ui/PhoneInput";

interface ReservationModalProps {
  item: {
    id: number;
    name: string;
    barcode: string;
    color?: { name: string } | null;
    size?: { name: string } | null;
  };
  branchId: number;
  branchName: string;
  /** Max quantity allowed (from branch availability). Defaults to 99. */
  maxQuantity?: number;
  reservationTtlHours: number;
  onClose: () => void;
  /** Prefill when customer is logged in */
  initialName?: string;
  initialPhone?: string;
}

type ModalStep = "form" | "loading" | "success" | "error";

export default function ReservationModal({
  item,
  branchId,
  branchName,
  maxQuantity = 99,
  reservationTtlHours,
  onClose,
  initialName = "",
  initialPhone = "",
}: ReservationModalProps) {
  const { t } = useLanguage();
  const cap = Math.max(1, maxQuantity);
  const [step, setStep] = useState<ModalStep>("form");
  const [name, setName] = useState(initialName);
  const [phone, setPhone] = useState(initialPhone);
  const [quantity, setQuantity] = useState(() => Math.min(1, cap));
  const [errorMsg, setErrorMsg] = useState("");
  const [reservation, setReservation] = useState<ItemReservation | null>(null);

  // Close on Escape
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const variantLabel = [item.color?.name, item.size?.name]
    .filter(Boolean)
    .join(" / ");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setStep("loading");
    setErrorMsg("");

    const payload: PlaceReservationPayload = {
      item_id: item.id,
      branch_id: branchId,
      customer_name: name.trim(),
      customer_phone: phone.trim(),
      quantity,
    };

    try {
      const res = await fetch("/api/storefront-proxy/reservations", {
        method: "POST",
        headers: { "Content-Type": "application/json", ...getAuthHeaders() },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok) {
        setErrorMsg(data.message || t.reservation.errorGeneric);
        setStep("error");
        return;
      }

      setReservation(data.reservation);
      setStep("success");
    } catch {
      setErrorMsg(t.reservation.errorGeneric);
      setStep("error");
    }
  };

  const formatExpiry = (iso: string | null) => {
    if (!iso) return "";
    return new Date(iso).toLocaleString();
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-labelledby="reservation-modal-title"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto overflow-x-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h2 id="reservation-modal-title" className="text-base font-bold text-gray-900">
            {t.reservation.title}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition-colors"
          >
            <svg
              className="w-4 h-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        {/* Body */}
        <div className="px-6 py-5">
          {/* Item + branch summary */}
          <div className="bg-gray-50 rounded-xl p-4 mb-5 space-y-1.5">
            <p className="text-sm font-semibold text-gray-800">{item.name}</p>
            {variantLabel && (
              <p className="text-xs text-gray-500">{variantLabel}</p>
            )}
            <div className="flex items-center gap-1.5 text-xs text-gray-600">
              <svg
                className="w-3.5 h-3.5 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
                />
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
                />
              </svg>
              <span>{branchName}</span>
            </div>
            <p className="text-xs text-amber-600 font-medium">
              {t.reservation.expiresIn.replace(
                "{{hours}}",
                String(reservationTtlHours),
              )}
            </p>
          </div>

          {step === "form" && (
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">
                  {t.reservation.yourName}
                </label>
                <input
                  type="text"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder={t.reservation.namePlaceholder}
                  className="input-base"
                />
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-700 mb-1.5 uppercase tracking-wide">
                  {t.reservation.yourPhone}
                </label>
                <PhoneInput
                  value={phone}
                  onChange={setPhone}
                  placeholder={t.reservation.phonePlaceholder}
                  required
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">
                  {t.product.quantity}
                </label>
                <div className="flex items-center border border-gray-200 rounded-xl overflow-hidden w-fit">
                  <button
                    type="button"
                    onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                    className="w-10 h-10 flex items-center justify-center text-gray-500 hover:bg-gray-50 transition-colors text-lg font-light"
                  >
                    −
                  </button>
                  <span className="text-sm font-semibold w-10 text-center border-x border-gray-200">
                    {quantity}
                  </span>
                  <button
                    type="button"
                    onClick={() => setQuantity((q) => Math.min(cap, q + 1))}
                    disabled={quantity >= cap}
                    className="w-10 h-10 flex items-center justify-center text-gray-500 hover:bg-gray-50 transition-colors text-lg font-light disabled:opacity-40 disabled:cursor-not-allowed"
                  >
                    +
                  </button>
                </div>
              </div>
              <button
                type="submit"
                className="btn-primary w-full py-3.5 rounded-xl text-sm font-bold"
              >
                {t.reservation.confirmReservation.replace(
                  "{{hours}}",
                  String(reservationTtlHours),
                )}
              </button>
            </form>
          )}

          {step === "loading" && (
            <div className="flex flex-col items-center justify-center py-8 gap-3">
              <div
                className="w-10 h-10 border-3 border-gray-200 border-t-current rounded-full animate-spin"
                style={{ borderTopColor: "var(--color-primary)" }}
              />
              <p className="text-sm text-gray-500">{t.common.loading}</p>
            </div>
          )}

          {step === "success" && reservation && (
            <div className="text-center py-2">
              <div className="w-14 h-14 rounded-full bg-green-50 flex items-center justify-center mx-auto mb-4">
                <svg
                  className="w-7 h-7 text-green-500"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M5 13l4 4L19 7"
                  />
                </svg>
              </div>
              <h3 className="text-base font-bold text-gray-900 mb-1">
                {t.reservation.successTitle}
              </h3>
              <p className="text-sm text-gray-500 mb-5">
                {t.reservation.successHint}
              </p>

              {/* Reservation code */}
              <div className="bg-gray-50 rounded-xl p-4 mb-5">
                <p className="text-xs text-gray-500 mb-1">
                  {t.reservation.yourCode}
                </p>
                <p className="text-2xl font-bold tracking-widest text-gray-900 font-mono">
                  {reservation.reservation_code}
                </p>
                <p
                  className="text-xs text-gray-400 mt-2"
                  suppressHydrationWarning
                >
                  {t.reservation.expiresAt}:{" "}
                  {formatExpiry(reservation.expires_at)}
                </p>
              </div>

              <div className="flex flex-col gap-2">
                <Link
                  href="/account"
                  className="btn-primary w-full py-3 rounded-xl text-sm font-bold text-center"
                >
                  {t.reservation.viewReservation}
                </Link>
                <button
                  type="button"
                  onClick={onClose}
                  className="w-full py-3 rounded-xl text-sm font-medium text-gray-500 hover:text-gray-800 transition-colors"
                >
                  {t.reservation.close}
                </button>
              </div>
            </div>
          )}

          {step === "error" && (
            <div className="text-center py-2">
              <div className="w-14 h-14 rounded-full bg-red-50 flex items-center justify-center mx-auto mb-4">
                <svg
                  className="w-7 h-7 text-red-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
                  />
                </svg>
              </div>
              <h3 className="text-base font-bold text-gray-900 mb-1">
                {t.reservation.errorTitle}
              </h3>
              <p className="text-sm text-red-600 mb-5">{errorMsg}</p>
              <div className="flex gap-3">
                <button
                  type="button"
                  onClick={() => setStep("form")}
                  className="btn-primary flex-1 py-3 rounded-xl text-sm font-bold"
                >
                  {t.common.tryAgain}
                </button>
                <button
                  type="button"
                  onClick={onClose}
                  className="flex-1 py-3 rounded-xl text-sm font-medium border border-gray-200 text-gray-600 hover:bg-gray-50 transition-colors"
                >
                  {t.reservation.close}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
