'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { v4 as uuid } from 'uuid';
import { useCart } from '@/lib/cartStore';
import type { ProofDTO } from '@/lib/types';

export default function ApproveSection({ proof }: { proof: ProofDTO }) {
  const [status, setStatus] = useState<ProofDTO['status']>(proof.status);
  const [loading, setLoading] = useState(false);
  const addItem = useCart((s) => s.addItem);
  const router = useRouter();

  const approve = async () => {
    setLoading(true);
    try {
      await fetch(`/api/proofs/${proof.id}/approve`, { method: 'POST' });
      addItem({
        cartItemId: uuid(),
        productId: proof.productId,
        slug: proof.productSlug,
        name: proof.productName,
        mockup: '',
        color: proof.color,
        size: null,
        quantity: proof.quantity,
        unitPrice: proof.unitPrice,
        designJson: { front: [], back: [] },
        designPreviewUrl: proof.imageDataUrl,
        designPreviewUrlBack: null,
        placementPreviewUrl: proof.imageDataUrl,
        placementPreviewUrlBack: null,
      });
      setStatus('APPROVED');
      router.push('/cart');
    } finally {
      setLoading(false);
    }
  };

  if (status === 'APPROVED') {
    return (
      <div className="border border-splash-blue bg-splash-blue/5 p-4 text-sm text-ink">
        Approved — this design is in your cart.
      </div>
    );
  }

  return (
    <button
      onClick={approve}
      disabled={loading}
      className="w-full bg-clay px-6 py-3 text-sm font-medium text-paper transition-colors hover:bg-clay-dark disabled:opacity-60"
    >
      {loading ? 'Adding to cart…' : 'Approve & add to bag'}
    </button>
  );
}
