'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { useLanguage } from '@/context/LanguageContext';

interface Testimonial {
  id: number;
  name: string;
  text: string;
  rating: number;
  photo: string | null;
  position: string | null;
  isActive: boolean;
}

export default function TestimonialsPage() {
  const { t } = useLanguage();
  const [testimonials, setTestimonials] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';

  useEffect(() => {
    const fetchTestimonials = async () => {
      try {
        const res = await fetch(`${apiUrl}/api/testimonials`);
        if (res.ok) {
          const data = await res.json();
          setTestimonials(data.filter((t: Testimonial) => t.isActive));
        }
      } catch (err) {
        setError('Gagal memuat testimonial');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchTestimonials();
  }, [apiUrl]);

  const formatText = (text: string | null) => {
    if (!text) return '';
    return text.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ');
  };

  if (loading) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <div className="container-custom py-16 text-center">
          <div className="text-5xl mb-4">💬</div>
          <h1 className="font-cormorant text-2xl md:text-3xl font-bold text-espresso mb-2">Memuat testimonial...</h1>
        </div>
        <Footer />
      </main>
    );
  }

  if (error) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <div className="container-custom py-16 text-center">
          <p className="text-5xl mb-4">💬</p>
          <h1 className="font-cormorant text-2xl font-bold text-espresso mb-2">{error}</h1>
          <Link href="/" className="text-gold hover:underline inline-block mt-4">← Kembali ke Home</Link>
        </div>
        <Footer />
      </main>
    );
  }

  const featuredTestimonial = testimonials[0] || null;
  const otherTestimonials = testimonials.slice(1);

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />
      <section className="relative py-16 md:py-24 bg-espresso overflow-hidden">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-4xl md:text-6xl font-bold mb-4 uppercase text-white">Testimoni Klien</h1>
          <p className="text-ivory/80 max-w-2xl mx-auto">Apa yang dikatakan klien kami tentang pengalaman mereka di Carla Skin Clinic.</p>
        </div>
      </section>

      <section className="py-12 md:py-20 bg-ivory">
        <div className="container-custom">
          {/* Featured Testimonial */}
          {featuredTestimonial && (
            <div className="mb-12">
              <div className="bg-white rounded-2xl overflow-hidden shadow-lg border border-blush">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-0">
                  <div className="bg-blush h-64 md:h-auto flex items-center justify-center">
                    {featuredTestimonial.photo ? (
                      <Image
                        src={featuredTestimonial.photo}
                        alt={featuredTestimonial.name}
                        width={600}
                        height={400}
                        className="w-full h-auto object-cover"
                      />
                    ) : (
                      <div className="w-full h-64 bg-blush flex items-center justify-center">
                        <span className="text-8xl">💬</span>
                      </div>
                    )}
                  </div>
                  <div className="p-6 md:p-8 flex flex-col justify-center">
                    <span className="inline-block px-3 py-1 bg-gold text-white text-xs font-bold rounded-full mb-3">
                      Testimoni Unggulan
                    </span>
                    <h2 className="font-cormorant text-2xl md:text-3xl font-bold text-espresso mb-4">
                      {featuredTestimonial.name}
                    </h2>
                    <div className="flex items-center gap-2 mb-4">
                      {[...Array(5)].map((_, i) => (
                        <svg key={i} className="w-4 h-4 text-gold" fill="currentColor" viewBox="0 0 20 20">
                          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
                        </svg>
                      ))}
                    </div>
                    <p className="text-grey-dark mb-4">{featuredTestimonial.text || ''}</p>
                    <div className="flex items-center gap-4 text-xs text-grey">
                      <span>✍️ {featuredTestimonial.name}</span>
                      <span>{featuredTestimonial.position}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

        </div>

          {/* All Testimonials Grid */}
          <div className="py-12">
            <div className="container-custom">
              <h2 className="font-cormorant text-3xl md:text-5xl text-espresso font-bold mb-4 text-center">Semua Testimoni</h2>
              <div className="w-12 h-0.5 bg-gold mx-auto mb-4"></div>
              <p className="text-grey-dark text-center mb-10">Klien kami yang puas dengan layanan Carla Skin Clinic</p>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
                {otherTestimonials.map((testimonial) => (
                  <Link key={testimonial.id} href={`/testimonials/${testimonial.id}`} className="block">
                    <div className="bg-white rounded-2xl overflow-hidden shadow-sm border border-blush hover:shadow-xl transition-all duration-300 h-full flex flex-col">
                      <div className="h-40 bg-blush flex items-center justify-center text-5xl overflow-hidden">
                        {testimonial.photo ? (
                          <img src={testimonial.photo} alt={testimonial.name} className="w-full h-full object-cover" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center text-5xl">💬</div>
                        )}
                      </div>
                      <div className="p-6 flex flex-col flex-1">
                        <div className="flex items-center gap-2 mb-3">
                          {[...Array(5)].map((_, i) => (
                            <svg key={i} className="w-4 h-4 text-gold" fill="currentColor" viewBox="0 0 20 20">
                              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-.364 1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
                            </svg>
                          ))}
                        </div>
                      <h3 className="font-cormorant text-xl font-semibold text-espresso mb-2">{testimonial.name}</h3>
                      <p className="text-sm text-grey-dark mb-3 line-clamp-2">{testimonial.text}</p>
                      <div className="flex items-center justify-between text-xs text-grey">
                        <span>✍️ {testimonial.name}</span>
                        <span>{testimonial.position}</span>
                      </div>
                    </div>
                  </div>
                </Link>
              ))}
            </div>

            <div className="text-center mt-10">
              <Link href="/testimonials" className="inline-block px-8 py-3 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded hover:bg-gold-dark hover:text-white transition duration-300">
                Lihat Semua Testimoni
              </Link>
            </div>
          </div>
        </div>
      </section>
      <Footer />
    </main>
  );
}