"use client";

import { useEffect, useState } from "react";
import BoldIcon from "@/components/ui/BoldIcon";
import { btnPrimary, btnDefault } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";

type BuyerAddressSnapshot = {
  first_name?: string | null;
  last_name?: string | null;
  mobile?: string | null;
  address?: string | null;
  province?: { name?: string } | null;
  city?: { name?: string } | null;
  lat?: string | null;
  lng?: string | null;
};

type BuyerInfoModalProps = {
  isOpen: boolean;
  onClose: () => void;
  buyer?: BuyerAddressSnapshot | null;
};

export default function BuyerInfoModal({ isOpen, onClose, buyer }: BuyerInfoModalProps) {
  const { t } = useTranslation("common");
  const [coords, setCoords] = useState<[number, number] | null>(null);

  useEffect(() => {
    if (!isOpen) {
      setCoords(null);
      return;
    }
    const lat = parseFloat(buyer?.lat || "");
    const lng = parseFloat(buyer?.lng || "");
    if (!isNaN(lat) && !isNaN(lng)) {
      setCoords([lat, lng]);
    } else {
      setCoords(null);
    }
  }, [buyer, isOpen]);

  if (!isOpen) return null;

  const fullName = [buyer?.first_name, buyer?.last_name].filter(Boolean).join(" ");
  const googleMapsUrl = coords
    ? `https://www.google.com/maps/dir/?api=1&destination=${coords[0]},${coords[1]}`
    : "https://www.google.com/maps";

  return (
    <div className="glass-modal-overlay fixed inset-0 z-50 flex items-center justify-center">
      <div className="glass-modal-panel glass-modal-panel--center mx-4 max-h-[80vh] w-full max-w-md scale-95 overflow-y-auto p-6 shadow-2xl animate-fadeIn">
        <div className="mb-4 flex items-center gap-2">
          <BoldIcon name="user" size={20} tinted className="text-blue-500" />
          <h2 className="text-lg font-semibold text-gray-800 dark:text-neutral-100">
            {t("shops.buyerInfoTitle")}
          </h2>
        </div>

        <div className="mb-6 text-sm text-gray-600 dark:text-neutral-300">
          {fullName && (
            <p className="text-base font-semibold text-gray-800 dark:text-neutral-100">
              {fullName}
            </p>
          )}
          {buyer?.mobile && (
            <p className="mt-2">
              <strong className="text-gray-800 dark:text-neutral-100">
                {t("shops.buyerMobileLabel")}{" "}
              </strong>
              <span dir="ltr">{buyer.mobile}</span>
            </p>
          )}
          <p className="mt-2">
            <strong className="text-gray-800 dark:text-neutral-100">
              {t("models.location.city")}{" "}
            </strong>
            {buyer?.city?.name || t("models.location.unknown")}،{" "}
            {buyer?.province?.name || t("models.location.unknown")}
          </p>
          {buyer?.address && (
            <p className="mt-2">
              <strong className="text-gray-800 dark:text-neutral-100">
                {t("models.location.address")}{" "}
              </strong>
              {buyer.address}
            </p>
          )}
        </div>

        {coords ? (
          <div className="mb-6 overflow-hidden rounded-lg border border-gray-200">
            <iframe
              title={t("models.location.mapTitle")}
              width="100%"
              height="200"
              frameBorder="0"
              style={{ border: 0 }}
              src={`https://maps.google.com/maps?q=${coords[0]},${coords[1]}&z=15&output=embed`}
              allowFullScreen
              loading="lazy"
            ></iframe>
          </div>
        ) : (
          <p className="mb-6 text-sm text-gray-500">{t("models.location.invalidCoords")}</p>
        )}

        <div className="flex justify-end gap-3">
          <a
            href={googleMapsUrl}
            target="_blank"
            rel="noopener noreferrer"
            className={cn(btnPrimary, "px-4 py-2 text-sm font-medium")}
          >
            {t("models.location.directions")}
          </a>
          <button
            type="button"
            onClick={onClose}
            className={cn(btnDefault, "px-4 py-2 text-sm font-medium")}
          >
            {t("models.location.close")}
          </button>
        </div>
      </div>

      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: scale(0.95);
          }
          to {
            opacity: 1;
            transform: scale(1);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.3s ease-out;
        }
      `}</style>
    </div>
  );
}
