'use client';

import React, { useState, useEffect } from 'react';

interface ServiceTile {
  id: number;
  title: string;
  description: string;
  isActive: boolean;
  displayOrder: number;
  createdDate: string;
  lastModified: string;
}

const StatisticsTiles = () => {
  const [tiles, setTiles] = useState<ServiceTile[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  // Default fallback data
  const defaultTiles = [
    { 
      title: "Primary Trauma Care", 
      description: "Specialized care for Priority One trauma patients in close coordination with the Emergency Department team."
    },
    { 
      title: "24x7 Trauma Surgeon", 
      description: "Round-the-clock availability of trauma surgeons ensures immediate surgical intervention when needed."
    },
    { 
      title: "Trauma Intensive & Ward Care", 
      description: "Comprehensive trauma intensive care and dedicated trauma ward services for critical and recovering patients."
    },
    { 
      title: "Trauma Education", 
      description: "Focused education and counseling for patients and families to enhance recovery and awareness."
    },
  ];

  useEffect(() => {
    const fetchServiceTiles = async () => {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
        const response = await fetch(`${apiUrl}/service-tiles/active`);
        
        if (response.ok) {
          const data: ServiceTile[] = await response.json();
          // Filter active tiles and sort by display order
          const activeTiles = data
            .filter(tile => tile.isActive)
            .sort((a, b) => a.displayOrder - b.displayOrder);
          
          if (activeTiles.length > 0) {
            setTiles(activeTiles);
            setError(false);
          } else {
            // No active tiles, use defaults
            setError(true);
          }
        } else {
          // API error, use defaults
          setError(true);
        }
      } catch (err) {
        console.error('Error fetching service tiles:', err);
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    fetchServiceTiles();
  }, []);

  // Use fetched tiles or fall back to default
  const displayTiles = error || tiles.length === 0 ? defaultTiles : tiles;

  return (
    <section className="py-8 sm:py-12" style={{ backgroundColor: '#f4f4f4' }}>
      <div className="max-w-7xl mx-auto px-4">
        <h2 
          className="text-2xl sm:text-3xl font-semibold text-center mb-8 sm:mb-12" 
          style={{ color: '#012068' }}
        >
          Our Trauma Care Services
        </h2>
        
        {loading ? (
          // Loading state
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          </div>
        ) : (
          // Display tiles
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6">
            {displayTiles.map((tile, index) => (
              <div 
                key={index} 
                className="border border-gray-300 rounded-lg p-5 h-full hover:shadow-lg transition-shadow duration-300" 
                style={{ backgroundColor: '#ffffff' }}
              >
                <div className="flex flex-col h-full">
                  <div className="flex items-center mb-3">
                    <h3 
                      className="text-base sm:text-lg font-medium" 
                      style={{ color: '#012068' }}
                    >
                      {tile.title}
                    </h3>
                  </div>
                  <p 
                    className="text-sm sm:text-base leading-relaxed flex-grow" 
                    style={{ color: '#333' }}
                  >
                    {tile.description}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
};

export default StatisticsTiles;