'use client';

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

export default function DebugProductPage() {
  const [slug, setSlug] = useState('sony-bravia-hp-perspiciatis-690314ec82b44');
  const [response, setResponse] = useState<Record<string, unknown> | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

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

    try {
      console.log('Testing direct 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);
    }
  };

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

    try {
      const url = `${process.env.NEXT_PUBLIC_API_URL || 'https://api.samsmy.com/api'}/products/${slug}`;
      console.log('Testing direct fetch to:', url);
      
      const fetchResponse = await fetch(url);
      const data = await fetchResponse.json();
      
      console.log('Fetch response:', data);
      setResponse(data);
    } catch (err) {
      console.error('Fetch 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">Product 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>
        
        <div className="space-x-4">
          <button
            onClick={testDirectApi}
            disabled={loading || !slug}
            className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
          >
            {loading ? 'Testing...' : 'Test API Client'}
          </button>
          
          <button
            onClick={testFetch}
            disabled={loading || !slug}
            className="bg-green-500 text-white px-4 py-2 rounded disabled:opacity-50"
          >
            {loading ? 'Testing...' : 'Test Direct Fetch'}
          </button>
        </div>
      </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 Structure:</h3>
          <div className="mb-4 p-3 bg-blue-50 rounded">
            <p><strong>Has &apos;data&apos; wrapper:</strong> {String('data' in response)}</p>
            <p><strong>Product ID:</strong> {String((response as { data?: { id?: string } }).data?.id || (response as { id?: string }).id || 'Not found')}</p>
            <p><strong>Product Name:</strong> {String((response as { data?: { name?: string } }).data?.name || (response as { name?: string }).name || 'Not found')}</p>
            <p><strong>Variants Count:</strong> {Array.isArray((response as { data?: { variants?: unknown[] } }).data?.variants) ? (response as { data?: { variants?: unknown[] } }).data?.variants?.length : Array.isArray((response as { variants?: unknown[] }).variants) ? (response as { variants?: unknown[] }).variants?.length : 0}</p>
          </div>
          
          <pre className="bg-gray-100 p-4 rounded overflow-auto text-sm max-h-96">
            {JSON.stringify(response, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}