"use client";

import { useEffect, useState } from "react";

export default function TestApiPage() {
  const [apiStatus, setApiStatus] = useState("Testing...");
  const [categoriesData, setCategoriesData] = useState<Record<string, unknown> | null>(null);
  const [productsData, setProductsData] = useState<Record<string, unknown> | null>(null);
  const [errors, setErrors] = useState<string[]>([]);

  useEffect(() => {
    const testAPI = async () => {
      const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://api.samsmy.com/api';
      console.log('API Base URL:', API_BASE);
      setErrors(prev => [...prev, `API Base URL: ${API_BASE}`]);

      // Test basic connectivity
      try {
        setApiStatus("Testing basic connectivity...");
        const response = await fetch(`${API_BASE}/categories`);
        console.log('Categories response status:', response.status);
        setErrors(prev => [...prev, `Categories response status: ${response.status}`]);
        
        if (response.ok) {
          const data = await response.json();
          console.log('Categories data:', data);
          setCategoriesData(data);
          setApiStatus("Categories loaded successfully!");
        } else {
          setApiStatus(`Categories failed: ${response.status} ${response.statusText}`);
        }
      } catch (error) {
        console.error('Categories error:', error);
        setApiStatus(`Categories error: ${error}`);
        setErrors(prev => [...prev, `Categories error: ${error}`]);
      }

      // Test products
      try {
        const response = await fetch(`${API_BASE}/products`);
        console.log('Products response status:', response.status);
        setErrors(prev => [...prev, `Products response status: ${response.status}`]);
        
        if (response.ok) {
          const data = await response.json();
          console.log('Products data:', data);
          setProductsData(data);
        } else {
          setErrors(prev => [...prev, `Products failed: ${response.status} ${response.statusText}`]);
        }
      } catch (error) {
        console.error('Products error:', error);
        setErrors(prev => [...prev, `Products error: ${error}`]);
      }
    };

    testAPI();
  }, []);

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">API Debug Page</h1>
      
      <div className="mb-8 p-4 bg-gray-100 rounded">
        <h2 className="text-xl font-semibold mb-2">API Status</h2>
        <p>{apiStatus}</p>
      </div>

      <div className="mb-8 p-4 bg-red-50 rounded">
        <h2 className="text-xl font-semibold mb-2">Debug Log</h2>
        {errors.map((error, index) => (
          <p key={index} className="text-sm font-mono">{error}</p>
        ))}
      </div>

      {categoriesData && (
        <div className="mb-8 p-4 bg-green-50 rounded">
          <h2 className="text-xl font-semibold mb-2">Categories ({Array.isArray(categoriesData) ? categoriesData.length : 'Not array'})</h2>
          <pre className="text-xs overflow-auto max-h-40">
            {JSON.stringify(categoriesData, null, 2)}
          </pre>
        </div>
      )}

      {productsData && (
        <div className="mb-8 p-4 bg-blue-50 rounded">
          <h2 className="text-xl font-semibold mb-2">Products</h2>
          <p>Data type: {Array.isArray((productsData as { data?: unknown[] })?.data) ? 'Array' : typeof (productsData as { data?: unknown })?.data}</p>
          <p>Count: {Array.isArray((productsData as { data?: unknown[] })?.data) ? (productsData as { data: unknown[] }).data.length : 'Unknown'}</p>
          <pre className="text-xs overflow-auto max-h-40">
            {JSON.stringify(productsData, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}
