'use client';

import { useState } from 'react';
import { api } from '@/lib/api';

export default function DebugApiPage() {
  const [slug, setSlug] = useState('');
  const [response, setResponse] = useState<Record<string, unknown> | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const testApi = async () => {
    if (!slug) return;
    
    setLoading(true);
    setError(null);
    setResponse(null);

    try {
      console.log('Testing API call to:', `/products/${slug}`);
      const result = await api.get(`/products/${slug}`);
      console.log('Raw API response:', result);
      setResponse(result as Record<string, unknown>);
    } catch (err) {
      console.error('API Error:', err);
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-2xl font-bold mb-6">API Debug Tool</h1>
      
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-2">Product Slug:</label>
          <input
            type="text"
            value={slug}
            onChange={(e) => setSlug(e.target.value)}
            className="border border-gray-300 rounded px-3 py-2 w-full max-w-md"
            placeholder="Enter product slug"
          />
        </div>
        
        <button
          onClick={testApi}
          disabled={loading || !slug}
          className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
        >
          {loading ? 'Testing...' : 'Test API Call'}
        </button>
      </div>

      {error && (
        <div className="mt-6 p-4 bg-red-100 border border-red-400 rounded">
          <h3 className="font-bold text-red-800">Error:</h3>
          <p className="text-red-700">{error}</p>
        </div>
      )}

      {response && (
        <div className="mt-6">
          <h3 className="font-bold mb-2">API Response:</h3>
          <pre className="bg-gray-100 p-4 rounded overflow-auto text-sm">
            {JSON.stringify(response, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}