'use client'
import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { ChevronRight } from 'lucide-react';
import testimonialService, { Testimonial } from '@/services/testimonialService';
import TraumaStats from './TraumaStats';

interface TestimonialsListingProps {
  title?: string;
  onTestimonialClick?: (testimonial: Testimonial) => void;
}

const TestimonialsListing: React.FC<TestimonialsListingProps> = ({ 
  title = "Patient Stories",
  onTestimonialClick
}) => {
  const [testimonials, setTestimonials] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadTestimonials = async () => {
      try {
        setLoading(true);
        const data = await testimonialService.getActiveTestimonials();
        setTestimonials(data);
        setError(null);
      } catch (err) {
        console.error('Failed to load testimonials:', err);
        setError('Failed to load testimonials. Please try again later.');
      } finally {
        setLoading(false);
      }
    };

    loadTestimonials();
  }, []);

  // Group testimonials by category
  const traumaCases = testimonials.filter(t => t.category === 'Trauma' || t.category === 'Road Accident');
  const surgicalCases = testimonials.filter(t => t.category === 'Surgery' || t.category === 'Surgical');
  const otherCases = testimonials.filter(t => !['Trauma', 'Road Accident', 'Surgery', 'Surgical'].includes(t.category || ''));

  const handleTestimonialClick = (testimonial: Testimonial) => {
    if (onTestimonialClick) {
      onTestimonialClick(testimonial);
    } else {
      window.location.href = `/testimonials/${testimonial.id}`;
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p>Loading testimonials...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <button 
            onClick={() => window.location.reload()} 
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  const TestimonialCard: React.FC<{ testimonial: Testimonial }> = ({ testimonial }) => {
    return (
      <div 
        className="group cursor-pointer bg-white rounded-lg border border-gray-300 overflow-hidden hover:shadow-lg transition-all duration-300"
        onClick={() => handleTestimonialClick(testimonial)}
      >
        <div className="relative aspect-square overflow-hidden">
          <div 
            className="w-full h-full flex items-center justify-center p-6 transition-transform duration-300 group-hover:scale-105"
            style={{ backgroundColor: '#f4f4f4' }}
          >
            <div className="text-center">
              <svg
                className="w-16 h-16 mx-auto mb-3 opacity-30"
                style={{ color: '#012068' }}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1.5}
                  d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                />
              </svg>
              <p className="text-xs leading-relaxed line-clamp-4 px-2" style={{ color: '#333' }}>
                {testimonial.story}
              </p>
            </div>
          </div>
        </div>
        
        <div className="p-4 sm:p-6">
          <h3 className="text-lg font-medium mb-2 group-hover:opacity-70 transition-opacity" style={{ color: '#012068' }}>
            {testimonial.name}{testimonial.age ? `, ${testimonial.age}` : ''}
          </h3>
          <p className="text-sm leading-relaxed mb-1" style={{ color: '#e64838' }}>
            {testimonial.category || 'Patient Story'}
          </p>
          {testimonial.title && (
            <p className="text-xs mt-2 font-medium line-clamp-2" style={{ color: '#333' }}>
              {testimonial.title}
            </p>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-screen">
      {/* Breadcrumb Section */}
      <section className="py-4" style={{ backgroundColor: '#f4f4f4' }}>
        <div className="max-w-7xl mx-auto px-4">
          <nav className="flex items-center space-x-2 text-sm">
            <Link 
              href="/" 
              className="hover:opacity-70 transition-opacity duration-200"
              style={{ color: '#012068' }}
            >
              Home
            </Link>
            <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
            <span className="font-medium" style={{ color: '#e64838' }}>
              Testimonials
            </span>
          </nav>
          
          <div className="mt-6">
            <div className="flex items-center mb-4">
              <h1 className="text-3xl font-bold" style={{ color: '#012068' }}>
                {title}
              </h1>
            </div>
            <p className="text-base max-w-3xl leading-relaxed" style={{ color: '#333' }}>
              Real stories of hope, recovery, and resilience from patients treated at Christian Medical College, Vellore. Each story represents the dedication of our medical team and the strength of our patients.
            </p>
          </div>
        </div>
      </section>

      {/* Stats Section */}
      <TraumaStats />

      {/* Trauma Cases Section */}
      {traumaCases.length > 0 && (
        <section className="py-4" style={{ backgroundColor: '#fff' }}>
          <div className="max-w-7xl mx-auto px-4">
            <div className="mb-6">
              <h2 className="text-2xl font-bold mb-2" style={{ color: '#012068' }}>
                Trauma & Emergency Cases
              </h2>
              <p className="text-sm" style={{ color: '#666' }}>
                Stories of survival and recovery from critical trauma and emergency situations
              </p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {traumaCases.map((testimonial) => (
                <TestimonialCard key={testimonial.id} testimonial={testimonial} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Surgical Cases Section */}
      {surgicalCases.length > 0 && (
        <section className="py-8" style={{ backgroundColor: '#f9f9f9' }}>
          <div className="max-w-7xl mx-auto px-4">
            <div className="mb-8">
              <h2 className="text-2xl font-bold mb-4" style={{ color: '#012068' }}>
                Surgical Success Stories
              </h2>
              <p className="text-sm" style={{ color: '#666' }}>
                Remarkable journeys through complex surgical procedures and recovery
              </p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {surgicalCases.map((testimonial) => (
                <TestimonialCard key={testimonial.id} testimonial={testimonial} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Other Cases Section */}
      {otherCases.length > 0 && (
        <section className="py-4" style={{ backgroundColor: '#fff' }}>
          <div className="max-w-7xl mx-auto px-4">
            <div className="mb-8">
              <h2 className="text-2xl font-bold mb-4" style={{ color: '#012068' }}>
                More Patient Stories
              </h2>
              <p className="text-sm" style={{ color: '#666' }}>
                Additional testimonials from patients across various medical specialties
              </p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {otherCases.map((testimonial) => (
                <TestimonialCard key={testimonial.id} testimonial={testimonial} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Show message if no testimonials */}
      {testimonials.length === 0 && !loading && (
        <section className="py-16 text-center">
          <div className="max-w-2xl mx-auto px-4">
            <h2 className="text-2xl font-bold mb-4" style={{ color: '#012068' }}>
              No Testimonials Available
            </h2>
            <p className="text-gray-600 mb-6">
              Patient testimonials are currently being updated. Please check back later.
            </p>
            <button 
              onClick={() => window.location.reload()} 
              className="px-6 py-3 text-white rounded-lg hover:opacity-90 transition-opacity"
              style={{ backgroundColor: '#012068' }}
            >
              Refresh Page
            </button>
          </div>
        </section>
      )}

      {/* Bottom CTA Section */}
      <div className="border-t border-gray-100 bg-gray-50">
        <div className="max-w-7xl mx-auto px-6 sm:px-8 md:px-6 lg:px-6 xl:px-6 py-12">
          <div className="flex flex-col md:flex-row items-center justify-between gap-6">
            <div>
              <h3 className="text-xl font-semibold mb-2" style={{ color: '#012068' }}>
                Support Emergency Trauma Care
              </h3>
              <p className="text-sm leading-relaxed" style={{ color: '#333' }}>
                Your donation ensures trauma victims receive immediate, life-saving treatment.
              </p>
            </div>
            <a
              href="https://givecmc.org/trauma-centre/"
              target="_blank"
              rel="noopener noreferrer"
              className="px-8 py-3 text-sm font-medium text-white hover:opacity-90 transition-opacity whitespace-nowrap"
              style={{ backgroundColor: '#e64838' }}
            >
              Donate Now
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TestimonialsListing;