'use client';

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

interface ServiceTile {
  id: number;
  title: string;
  description: string;
  category: 'TRAUMA_CARE' | 'ACUTE_CARE_SURGERY';
  isActive: boolean;
  displayOrder: number;
  createdDate: string;
  lastModified: string;
}

const StatisticsTiles = () => {
  const [traumaCareTiles, setTraumaCareTiles] = useState<ServiceTile[]>([]);
  const [acuteCareTiles, setAcuteCareTiles] = useState<ServiceTile[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  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();
          
          // Separate tiles by category
          const traumaTiles = data
            .filter(tile => tile.isActive && tile.category === 'TRAUMA_CARE')
            .sort((a, b) => a.displayOrder - b.displayOrder);
          
          const acuteTiles = data
            .filter(tile => tile.isActive && tile.category === 'ACUTE_CARE_SURGERY')
            .sort((a, b) => a.displayOrder - b.displayOrder);
          
          setTraumaCareTiles(traumaTiles);
          setAcuteCareTiles(acuteTiles);
          setError(false);
        } else {
          setError(true);
        }
      } catch (err) {
        console.error('Error fetching service tiles:', err);
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    fetchServiceTiles();
  }, []);

  // Function to parse description and convert to bullet points (comma-separated)
  const parseDescription = (description: string) => {
    const points = description
      .split(',')
      .map(point => point.trim())
      .filter(point => point.length > 0);
    
    return points;
  };

  return (
    <section className="py-12 sm:py-16" style={{ backgroundColor: '#f4f4f4' }}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {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>
        ) : error ? (
          // Error state
          <div className="text-center py-8">
            <p className="text-gray-600 text-base sm:text-lg">
              Unable to load services. Please check back later.
            </p>
          </div>
        ) : traumaCareTiles.length === 0 && acuteCareTiles.length === 0 ? (
          // No services available
          <div className="text-center py-8">
            <p className="text-gray-600 text-base sm:text-lg">
              No services are currently available. Please check back later.
            </p>
          </div>
        ) : (
          <>
            {/* Trauma Care Section */}
            {traumaCareTiles.length > 0 && (
              <div id="trauma-care" className="mb-16 scroll-mt-20">
                <h2 
                  className="text-3xl sm:text-4xl font-bold text-center mb-12 sm:mb-16" 
                  style={{ color: '#012068' }}
                >
                  Our Trauma Care Services
                </h2>
                
                <div className="space-y-8">
                  {traumaCareTiles.map((tile) => (
                    <div key={tile.id} className="text-left">
                      <h3 
                        className="text-xl sm:text-2xl font-bold mb-4 pb-2 border-b-2 inline-block" 
                        style={{ color: '#012068', borderColor: '#012068' }}
                      >
                        {tile.title}
                      </h3>
                      <ul className="space-y-2.5 mt-4">
                        {parseDescription(tile.description).map((point, idx) => (
                          <li 
                            key={idx}
                            className="text-sm sm:text-base leading-relaxed flex items-start" 
                            style={{ color: '#333' }}
                          >
                            <span 
                              className="inline-block w-1.5 h-1.5 rounded-full mt-2 mr-3 flex-shrink-0"
                              style={{ backgroundColor: '#012068' }}
                            ></span>
                            <span>{point}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Acute Care Surgery Section */}
            {acuteCareTiles.length > 0 && (
              <div id="acute-care-surgery" className="scroll-mt-20">
                <h2 
                  className="text-3xl sm:text-4xl font-bold text-center mb-12 sm:mb-16" 
                  style={{ color: '#012068' }}
                >
                  Acute Care Surgery Services
                </h2>
                
                <div className="space-y-8">
                  {acuteCareTiles.map((tile) => (
                    <div key={tile.id} className="text-left">
                      <h3 
                        className="text-xl sm:text-2xl font-bold mb-4 pb-2 border-b-2 inline-block" 
                        style={{ color: '#012068', borderColor: '#012068' }}
                      >
                        {tile.title}
                      </h3>
                      <ul className="space-y-2.5 mt-4">
                        {parseDescription(tile.description).map((point, idx) => (
                          <li 
                            key={idx}
                            className="text-sm sm:text-base leading-relaxed flex items-start" 
                            style={{ color: '#333' }}
                          >
                            <span 
                              className="inline-block w-1.5 h-1.5 rounded-full mt-2 mr-3 flex-shrink-0"
                              style={{ backgroundColor: '#012068' }}
                            ></span>
                            <span>{point}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </section>
  );
};

export default StatisticsTiles;