"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useConfirm } from "@/components/shared/use-confirm";

interface StoreItem {
  id: number;
  title: string;
  description: string | null;
  type: string;
  thumbnail: string | null;
  price_credits: number;
  seller_id: number;
  seller_name: string | null;
  seller_photo: string | null;
}

export default function StoreClient({
  item,
  isAuthenticated,
}: {
  item: StoreItem;
  isAuthenticated: boolean;
}) {
  const router = useRouter();
  const [buying, setBuying] = useState(false);
  const [purchased, setPurchased] = useState(false);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  const handleBuy = async () => {
    if (!isAuthenticated) {
      router.push("/login");
      return;
    }

    if (!(await askConfirm({ title: "Confirm purchase", message: `Purchase "${item.title}" for ${item.price_credits} credits?` }))) return;

    setBuying(true);
    try {
      const res = await fetch("/api/store/purchase", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ item_id: item.id }),
      });

      if (res.ok) {
        setPurchased(true);
      } else {
        const json = await res.json();
        alert(json.error || "Purchase failed");
      }
    } catch {
      alert("Purchase failed. Please try again.");
    } finally {
      setBuying(false);
    }
  };

  return (
    <div className="bg-surface rounded-xl overflow-hidden border border-white/5 hover:border-gold/30 transition-all group">
      {confirmDialog}
      {/* Thumbnail */}
      <div className="aspect-video bg-surface-light relative flex items-center justify-center">
        {item.thumbnail ? (
          <img
            src={item.thumbnail}
            alt={item.title}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform"
          />
        ) : (
          <svg
            className="w-12 h-12 text-text-muted"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            {item.type === "video" ? (
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1.5}
                d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664zM21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            ) : (
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1.5}
                d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            )}
          </svg>
        )}

        {/* Type badge */}
        <span className="absolute top-2 left-2 bg-black/60 text-white text-xs font-bold px-2 py-0.5 rounded uppercase">
          {item.type}
        </span>

        {/* Price badge */}
        <span className="absolute top-2 right-2 bg-gold/90 text-black text-xs font-bold px-2 py-1 rounded-lg backdrop-blur-sm">
          {item.price_credits} credits
        </span>
      </div>

      {/* Info */}
      <div className="p-3 space-y-2">
        <p className="font-semibold text-white truncate group-hover:text-gold transition-colors">
          {item.title}
        </p>

        {item.description && (
          <p className="text-text-muted text-xs line-clamp-2">{item.description}</p>
        )}

        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            {item.seller_photo ? (
              <img
                src={item.seller_photo}
                alt={item.seller_name || ""}
                className="w-5 h-5 rounded-full object-cover"
              />
            ) : (
              <div className="w-5 h-5 rounded-full bg-surface-light" />
            )}
            <span className="text-text-muted text-xs truncate">
              {item.seller_name || "Creator"}
            </span>
          </div>
        </div>

        <button
          onClick={handleBuy}
          disabled={buying || purchased}
          className={`w-full py-2 rounded-lg font-semibold text-sm transition-all ${
            purchased
              ? "bg-green-600/20 text-green-400 border border-green-600/30"
              : "bg-gold/20 hover:bg-gold/30 text-gold border border-gold/30"
          } disabled:opacity-50`}
        >
          {purchased ? "Purchased" : buying ? "Processing..." : "Buy Now"}
        </button>
      </div>
    </div>
  );
}
