'use client';

import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import api from '@/lib/api';

/**
 * Donors Section
 * Showcases partner organizations and donors with professional design
 * Fetches donors from API
 */
export const Donors: React.FC = () => {
  const [donors, setDonors] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchDonors();
  }, []);

  const fetchDonors = async () => {
    try {
      setLoading(true);
      setError(null);
      const response: any = await api.getDonors({ status: 'active' });
      
      let donorsData: any[] = [];
      if (Array.isArray(response)) {
        donorsData = response;
      } else if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        donorsData = response.data;
      }
      
      setDonors(donorsData);
    } catch (err: any) {
      console.error('Error fetching donors:', err);
      setError(err?.message || 'Failed to fetch donors.');
      setDonors([]);
    } finally {
      setLoading(false);
    }
  };

  // Show loading state
  if (loading) {
    return (
      <section id="donors" className="relative pt-24 md:pt-32 pb-12 md:pb-16 bg-gradient-to-br from-white via-neutral-50 to-primary-50/20 overflow-hidden">
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <div className="inline-flex items-center gap-2 mb-6">
              <div className="h-px w-12 bg-gradient-to-r from-transparent to-primary-500" />
              <span className="px-5 py-2 bg-gradient-to-r from-primary-500 to-primary-400 text-neutral-900 rounded-full text-sm font-semibold shadow-lg">
                Our Partners
              </span>
              <div className="h-px w-12 bg-gradient-to-l from-transparent to-primary-500" />
            </div>
            
            <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold text-primary-500 mb-6 leading-tight">
              Backed by{' '}
              <span className="bg-gradient-to-r from-primary-500 via-primary-400 to-primary-500 bg-clip-text text-transparent">
                Trusted Partners
              </span>
            </h2>
          </div>
          
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-6 mb-12">
            {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((i) => (
              <div key={i} className="relative bg-white rounded-xl p-6 shadow-md border border-neutral-100 flex items-center justify-center min-h-[140px] animate-pulse">
                <div className="w-24 h-16 bg-neutral-200 rounded" />
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="donors" className="relative pt-24 md:pt-32 pb-12 md:pb-16 bg-gradient-to-br from-white via-neutral-50 to-primary-50/20 overflow-hidden">
      {/* Decorative Background Elements */}
      <div className="absolute top-0 right-0 w-96 h-96 bg-gradient-to-br from-primary-200/10 to-transparent rounded-full blur-3xl" />
      <div className="absolute bottom-0 left-0 w-96 h-96 bg-gradient-to-tr from-primary-200/10 to-transparent rounded-full blur-3xl" />
      
      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-16">
          <div className="inline-flex items-center gap-2 mb-6">
            <div className="h-px w-12 bg-gradient-to-r from-transparent to-primary-500" />
            <span className="px-5 py-2 bg-gradient-to-r from-primary-500 to-primary-400 text-neutral-900 rounded-full text-sm font-semibold shadow-lg">
              Our Partners
            </span>
            <div className="h-px w-12 bg-gradient-to-l from-transparent to-primary-500" />
          </div>
          
          <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold text-primary-500 mb-6 leading-tight">
            Backed by{' '}
            <span className="bg-gradient-to-r from-primary-500 via-primary-400 to-primary-500 bg-clip-text text-transparent">
              Trusted Partners
            </span>
          </h2>
          
          <p className="text-xl md:text-2xl text-neutral-600 max-w-3xl mx-auto leading-relaxed mb-4">
            SSEOA&apos;s work is made possible through the generous support of donors, UN agencies, and institutional partners committed to lasting change across Afghanistan.
          </p>
          
          <Link
            href="/donors"
            className="inline-flex items-center gap-2 text-primary-600 hover:text-primary-700 font-semibold transition-colors duration-300 group"
          >
            View All Partners
            <svg className="w-5 h-5 transform group-hover:translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
            </svg>
          </Link>
        </div>

        {/* Donors Grid */}
        {donors.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-6 mb-12">
            {donors.map((donor, index) => (
              <div
                key={donor.id || index}
                className="group relative bg-white rounded-xl p-6 shadow-md hover:shadow-xl transition-all duration-500 transform hover:-translate-y-2 border border-neutral-100 flex items-center justify-center min-h-[140px]"
              >
                {/* Gradient Background on Hover */}
                <div className="absolute inset-0 bg-gradient-to-br from-primary-500/5 to-primary-600/5 opacity-0 group-hover:opacity-100 rounded-xl transition-opacity duration-500" />
                
                {/* Logo Container */}
                <div className="relative w-full h-full flex items-center justify-center">
                  <div className="relative w-full h-20 flex items-center justify-center">
                    {donor.image || donor.image_large || donor.image_medium ? (
                      <img
                        src={donor.image_large || donor.image_medium || donor.image}
                        alt={donor.name}
                        className="max-w-full max-h-full object-contain transition-transform duration-500 group-hover:scale-105"
                      />
                    ) : (
                      <div className="text-neutral-400 text-sm font-semibold text-center">
                        {donor.name}
                      </div>
                    )}
                  </div>
                </div>
                
                {/* Hover Border */}
                <div className="absolute inset-0 rounded-xl border-2 border-primary-500/0 group-hover:border-primary-500/20 transition-all duration-500" />
              </div>
            ))}
          </div>
        ) : !loading && !error ? (
          <div className="text-center py-12 mb-12">
            <p className="text-neutral-500">No donors available from the API.</p>
            <button
              onClick={fetchDonors}
              className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-neutral-900 bg-primary-500 hover:bg-primary-400"
            >
              Retry
            </button>
          </div>
        ) : error ? (
          <div className="text-center py-12 mb-12 text-red-600">
            <p className="text-xl">Error: {error}</p>
            <button
              onClick={fetchDonors}
              className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700"
            >
              Retry
            </button>
          </div>
        ) : null}
      </div>
    </section>
  );
};
