'use client';

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

interface Doctor {
  id: number;
  name: string;
  slug: string;
  title: string | null;
  specialty: string | null;
  photo: string | null;
}

export default function FeaturedDoctors() {
  const { t } = useLanguage();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [doctors, setDoctors] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDoctors = async () => {
      try {
        const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/doctors?all=true`);
        if (res.ok) {
          const data = await res.json();
          const active = (Array.isArray(data) ? data : []).filter((d: any) => d.isActive);
          setDoctors(active.slice(0, 4));
        }
      } catch (e) {
        console.error('Failed to fetch doctors:', e);
      } finally {
        setLoading(false);
      }
    };
    fetchDoctors();
  }, []);

  const isRealImage = (img: string | null) => !!img && (img.startsWith('/') || img.startsWith('http'));

  if (loading) {
    return (
      <section className="py-16 md:py-24 bg-ivory">
        <div className="container-custom text-center">
          <p className="text-grey-dark">Memuat dokter...</p>
        </div>
      </section>
    );
  }

  if (!loading && doctors.length === 0) {
    return null;
  }

  return (
    <section className="py-16 md:py-24 bg-ivory">
      <div className="container-custom">
        <div className="text-center mb-12">
          <h2 className="font-cormorant text-3xl md:text-5xl text-espresso font-bold mb-4">{t('doctors.title')}</h2>
          <div className="w-12 h-0.5 bg-gold mx-auto mb-4"></div>
          <p className="text-grey-dark">{t('doctors.subtitle')}</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 md:gap-8">
          {doctors.map((doctor) => (
            <Link key={doctor.id} href={`/dokter/${doctor.slug}`} className="group block">
              <div className="bg-white rounded-2xl overflow-hidden shadow-sm border border-blush hover:shadow-xl transition-all duration-300">
                <div className="relative h-40 bg-blush flex items-center justify-center text-5xl overflow-hidden">
                  {doctor.photo ? (
                    <Image
                      src={doctor.photo}
                      alt={doctor.name}
                      fill
                      className="object-cover transition-transform duration-500 group-hover:scale-105"
                      sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 25vw"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-5xl">👨‍⚕️</div>
                  )}
                </div>
                <div className="p-6">
                  <span className="inline-block px-3 py-1 bg-gold text-white text-xs font-bold rounded-full mb-4">
                    {doctor.title || 'Sp.KK'}
                  </span>
                  <h3 className="font-cormorant text-xl font-semibold text-espresso mb-2 group-hover:text-gold transition-colors">
                    {doctor.name}
                  </h3>
                  <p className="text-sm text-grey-dark mb-4 line-clamp-2">
                    {doctor.specialty || 'Dermatologi & Venereologi'}
                  </p>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-grey">Lihat Detail →</span>
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>

        <div className="text-center mt-12">
          <Link href="/dokter" 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">
            {t('doctors.seeAll')}
          </Link>
        </div>
      </div>
    </section>
  );
}