'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 Doctor {
  id: number;
  name: string;
  slug: string;
  title: string | null;
  specialty: string | null;
  bio: string | null;
  photo: string | null;
  education: string | null;
  experience: string | null;
  services: string | null;
  isActive: boolean;
  sortOrder: number;
}

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

  useEffect(() => {
    const fetchDoctors = async () => {
      try {
        const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/doctors`);
        if (!res.ok) throw new Error('Failed to fetch');
        const data = await res.json();
        setDoctors(data.filter((d: any) => d.isActive));
      } catch (err) {
        setError('Gagal memuat data dokter');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    fetchDoctors();
  }, []);

  const formatEducation = (edu: string | null) => {
    if (!edu) return [];
    return edu.split('\n').filter(line => line.trim());
  };

  const formatServices = (services: string | null) => {
    if (!services) return [];
    try {
      return JSON.parse(services);
    } catch {
      return [];
    }
  };

  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">{t('doctors.loading')}</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">{t('general.backHome')}</Link>
        </div>
        <Footer />
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />

      {/* Hero Section */}
      <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">{t('doctors.title')}</h1>
          <p className="text-ivory/80 max-w-2xl mx-auto text-lg md:text-xl">{t('doctors.subtitle')}</p>
        </div>
        <div className="absolute inset-0 opacity-5" aria-hidden="true">
          <div className="absolute top-10 left-10 text-8xl">👨‍⚕️</div>
          <div className="absolute bottom-10 right-10 text-8xl rotate-180">🏥</div>
        </div>
      </section>

      {/* Doctors Grid */}
      <section className="py-12 md:py-20 bg-ivory">
        <div className="container-custom">
          {/* Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-12">
            <div className="bg-white rounded-xl p-6 shadow-sm border border-blush text-center">
              <div className="text-3xl md:text-4xl font-bold text-gold">{4}</div>
              <p className="text-grey-dark mt-1">{t('doctors.specialistDoctors')}</p>
            </div>
            <div className="bg-white rounded-xl p-6 shadow-sm border border-blush text-center">
              <div className="text-3xl md:text-4xl font-bold text-gold">{'15+'}</div>
              <p className="text-grey-dark mt-1">{t('doctors.yearsExperience')}</p>
            </div>
            <div className="bg-white rounded-xl p-6 shadow-sm border border-blush text-center">
              <div className="text-3xl md:text-4xl font-bold text-gold">{'100%'}%</div>
              <p className="text-grey-dark mt-1">{t('doctors.specialistDoctors')}</p>
            </div>
            <div className="bg-white rounded-xl p-6 shadow-sm border border-blush text-center">
              <div className="text-3xl md:text-4xl font-bold text-gold">{'25+'}</div>
              <p className="text-grey-dark mt-1">{t('doctors.branches')}</p>
            </div>
          </div>

          {/* Doctors Grid */}
          <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">
                <article className="bg-white rounded-2xl overflow-hidden shadow-sm border border-blush hover:shadow-xl transition-all duration-300 h-full flex flex-col">
                  {/* Photo */}
                  <div className="relative h-56 md:h-64 overflow-hidden bg-blush">
                    {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-6xl">👨‍⚕️</div>
                    )}
                    <div className="absolute inset-0 bg-gradient-to-t from-espresso/80 via-transparent to-transparent" />
                    <div className="absolute bottom-4 left-4 right-4 text-white">
                      <span className="inline-block px-3 py-1 bg-gold text-white text-xs font-bold rounded-full">
                        {doctor.title || 'Sp.KK'}
                      </span>
                    </div>
                  </div>

                  <div className="p-6 flex flex-col flex-1">
                    <div className="flex items-center gap-2 mb-3">
                      <span className="px-2 py-1 bg-gold/10 text-gold text-xs font-bold rounded-full">
                        {doctor.specialty || 'Dermatologi'}
                      </span>
                    </div>

                    <h3 className="font-cormorant text-xl font-bold text-espresso mb-2 group-hover:text-gold transition-colors">
                      {doctor.name}
                    </h3>

                    {doctor.title && (
                      <p className="text-gold text-sm font-semibold mb-2">{doctor.title}</p>
                    )}

                    <p className="text-grey-dark text-sm mb-4 line-clamp-2 flex-1">
                      {doctor.bio || 'Dokter spesialis kulit berpengalaman di Carla Skin Clinic.'}
                    </p>

                    {/* Experience & Services Preview */}
                    <div className="border-t border-blush pt-4 mt-auto">
                      <div className="flex items-center gap-2 text-xs text-grey-dark mb-2">
                        <span>📅</span>
                        <span>{doctor.experience || 'Berpengalaman'}</span>
                      </div>

                      <div className="flex flex-wrap gap-1.5">
                        {doctor.services && JSON.parse(doctor.services).slice(0, 3).map((svc: string, i: number) => (
                          <span key={i} className="px-2 py-0.5 bg-blush text-espresso text-xs rounded-full">
                            {svc.replace('clara-', '').replace(/-/g, ' ')}
                          </span>
                        ))}
                        {doctor.services && JSON.parse(doctor.services).length > 3 && (
                          <span className="px-2 py-0.5 bg-gold/10 text-gold text-xs rounded-full">
                            +{JSON.parse(doctor.services).length - 3} lagi
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </article>
              </Link>
            ))}
          </div>

          {/* CTA */}
          <div className="text-center mt-16">
            <Link href="/online-booking" className="inline-block px-8 py-4 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded hover:bg-gold-dark hover:text-white transition duration-300">
              {t('doctors.bookConsultation')}
            </Link>
            <p className="mt-4 text-grey-dark text-sm">{t('doctors.consultationNote')}</p>
          </div>
        </div>
      </section>

      <Footer />
    </main>
  );
}