'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useParams } from 'next/navigation';
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;
}

const localDoctors: Doctor[] = [
  {
    id: 1,
    name: 'dr. Sarah Sp.KK',
    slug: 'dr-sarah-sp-kk',
    title: 'Sp.KK',
    specialty: 'Dermatologi & Venereologi',
    bio: 'Dokter spesialis kulit dan kelamin dengan pengalaman lebih dari 15 tahun di bidang dermatologi kosmetik dan klinik. Ahli dalam penanganan jerawat, anti-aging, dan perawatan kulit canggih.',
    photo: 'https://i.pravatar.cc/150?img=10',
    education: 'FK Universitas Indonesia (S1)\nSpesialis Kulit & Kelamin (Sp.KK) - FKUI/RSCM\nFellowship Dermatologi Kosmetik - Singapore',
    experience: '15+ tahun pengalaman',
    services: JSON.stringify(['clara-basic-facial', 'clara-glow-facial', 'clara-acne-laser', 'clara-lift-hifu']),
    isActive: true,
    sortOrder: 1,
  },
  {
    id: 2,
    name: 'dr. Maya Sp.KK',
    slug: 'dr-maya-sp-kk',
    title: 'Sp.KK',
    specialty: 'Dermatologi & Venereologi',
    bio: 'Dokter spesialis kulit dengan fokus pada dermatologi kosmetik dan laser. Berpengalaman menangani berbagai masalah kulit mulai dari jerawat, pigmentasi, hingga anti-aging.',
    photo: 'https://i.pravatar.cc/150?img=11',
    education: 'FK Universitas Padjadjaran (S1)\nSpesialis Kulit & Kelamin (Sp.KK) - FKUNPAD/RSHS\nSertifikasi Laser Dermatologi - ASLM',
    experience: '12+ tahun pengalaman',
    services: JSON.stringify(['clara-bright-laser', 'clara-acne-laser', 'clara-glow-facial']),
    isActive: true,
    sortOrder: 2,
  },
  {
    id: 3,
    name: 'dr. Rina Sp.KK',
    slug: 'dr-rina-sp-kk',
    title: 'Sp.KK',
    specialty: 'Dermatologi & Venereologi',
    bio: 'Dokter spesialis kulit dengan keahlian pada laser estetika dan perawatan anti-aging. Memiliki pengalaman internasional di bidang dermatologi kosmetik.',
    photo: 'https://i.pravatar.cc/150?img=12',
    education: 'FK Universitas Airlangga (S1)\nSpesialis Kulit & Kelamin (Sp.KK) - FKUNAIR/RSHS\nFellowship Laser Dermatology - South Korea',
    experience: '10+ tahun pengalaman',
    services: JSON.stringify(['clara-lift-hifu', 'clara-bright-laser', 'clara-glow-facial']),
    isActive: true,
    sortOrder: 3,
  },
  {
    id: 4,
    name: 'dr. Andi Sp.KK',
    slug: 'dr-andi-sp-kk',
    title: 'Sp.KK',
    specialty: 'Dermatologi & Venereologi',
    bio: 'Dokter spesialis kulit dengan fokus pada hair removal laser dan perawatan kulit pria. Ahli dalam diode laser dan teknologi penghilangan bulu permanen.',
    photo: 'https://i.pravatar.cc/150?img=13',
    education: 'FK Universitas Gadjah Mada (S1)\nSpesialis Kulit & Kelamin (Sp.KK) - FKUGM/RSHS\nSertifikasi Diode Laser Hair Removal',
    experience: '8+ tahun pengalaman',
    services: JSON.stringify(['ipl-hair-removal', 'diode-laser-hair-removal', 'clara-hair-free-6x']),
    isActive: true,
    sortOrder: 4,
  },
];

export default function DoctorDetailPage() {
  const params = useParams();
  const slug = params.slug as string;
  const { t } = useLanguage();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [doctor, setDoctor] = useState<Doctor | null>(null);
  const [relatedDoctors, setRelatedDoctors] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchDoctor = async () => {
      try {
        setLoading(true);

        try {
          const response = await fetch(`${apiUrl}/api/doctors/${slug}`);
          if (response.ok) {
            const data = await response.json();
            setDoctor(data);
            // Recent list from published doctors
            try {
              const listRes = await fetch(`${apiUrl}/api/doctors`);
              if (listRes.ok) {
                const list = await listRes.json();
                const recent = (Array.isArray(list) ? list : [])
                  .filter((p: any) => p.id !== data.id)
                  .slice(0, 5);
                setRelatedDoctors(recent);
              }
            } catch (e) { /* ignore */ }
            return;
          }
        } catch (apiError) {
          console.log('API not available, using local data');
        }

        const localDoctor = localDoctors.find((d) => d.slug === slug);
        if (localDoctor) {
          setDoctor(localDoctor);
          const related = localDoctors.filter((d) => d.slug !== slug).slice(0, 5);
          setRelatedDoctors(related);
        } else {
          setError('Dokter tidak ditemukan');
        }
      } catch (err) {
        setError('Gagal memuat data dokter');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    if (slug) fetchDoctor();
  }, [slug]);

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

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

  if (error || !doctor) {
    return (
      <main className="min-h-screen bg-ivory">
        <Navbar />
        <div className="container-custom py-24 text-center">
          <p className="text-5xl mb-4">👨‍⚕️</p>
          <h1 className="font-cormorant text-3xl font-bold text-espresso mb-4">{error || 'Dokter tidak ditemukan'}</h1>
          <Link href="/dokter" className="text-gold hover:underline inline-block mt-4">
            ← Kembali ke Daftar Dokter
          </Link>
        </div>
        <Footer />
      </main>
    );
  }

  const services = doctor.services ? JSON.parse(doctor.services) : [];
  const educationLines = doctor.education ? doctor.education.split('\n').filter(l => l.trim()) : [];
  const bioParagraphs = doctor.bio ? doctor.bio.split('\n\n').filter(p => p.trim()) : [];
  const recentIsReal = (img: string) => !!img && (img.startsWith('/') || img.startsWith('http'));

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

      {/* Breadcrumb */}
      <section className="relative py-12 md:py-16 bg-espresso">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-3xl md:text-5xl font-bold mb-4 text-white">{doctor.name}</h1>
          <nav className="mt-4 text-xs tracking-widest uppercase text-white">
            <Link href="/" className="hover:text-gold transition text-white">{t('breadcrumb.home')}</Link>
            <span className="mx-2 text-white">/</span>
            <Link href="/dokter" className="hover:text-gold transition text-white">{t('breadcrumb.doctors')}</Link>
            <span className="mx-2 text-white">/</span>
            <span className="text-white/60">{doctor.name}</span>
          </nav>
        </div>
      </section>

      {/* Doctor Profile */}
      <section className="py-12 md:py-20 bg-ivory">
        <div className="container-custom max-w-5xl">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-10 lg:gap-12">
            {/* Sidebar - Photo & Info */}
            <aside className="lg:col-span-1 space-y-8">
              {/* Photo Card */}
              <div className="bg-white rounded-2xl overflow-hidden shadow-lg border border-blush sticky top-24">
                {doctor.photo ? (
                  <Image
                    src={doctor.photo}
                    alt={doctor.name}
                    width={350}
                    height={450}
                    className="w-full h-auto object-cover"
                  />
                ) : (
                  <div className="w-full h-72 bg-blush flex items-center justify-center text-7xl">👨‍⚕️</div>
                )}
                <div className="p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <span className="px-3 py-1 bg-gold text-white text-xs font-bold rounded-full">
                      {doctor.title || 'Sp.KK'}
                    </span>
                    <span className="px-3 py-1 bg-blush text-gold text-xs font-bold rounded-full">
                      {doctor.specialty || 'Dermatologi'}
                    </span>
                  </div>
                  <h2 className="font-cormorant text-2xl font-bold text-espresso mb-2">{doctor.name}</h2>
                  {doctor.title && <p className="text-gold font-semibold mb-3">{doctor.title}</p>}
                  <p className="text-grey-dark text-sm mb-4">
                    {doctor.specialty || 'Dermatologi & Venereologi'}
                  </p>

                  <div className="flex items-center gap-2 text-sm text-grey-dark mb-4">
                    <span>📅</span>
                    <span>{doctor.experience || 'Berpengalaman'}</span>
                  </div>

                  <div className="pt-4 border-t border-blush">
                    <p className="font-semibold text-espresso mb-2">Layanan yang Ditangani</p>
                    <div className="flex flex-wrap gap-2">
                      {doctor.services && JSON.parse(doctor.services).slice(0, 4).map((svc: string, idx: number) => (
                        <span key={idx} className="px-2 py-1 bg-blush text-espresso text-xs rounded-full">
                          {svc.replace('clara-', '').replace(/-/g, ' ')}
                        </span>
                      ))}
                      {doctor.services && JSON.parse(doctor.services).length > 4 && (
                        <span className="px-2 py-1 bg-gold/10 text-gold text-xs rounded-full">
                          +{JSON.parse(doctor.services).length - 4} lainnya
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {/* CTA Buttons */}
              <div className="space-y-3">
                <Link
                  href="/online-booking"
                  className="block w-full py-4 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded hover:bg-gold-dark hover:text-white transition duration-300 text-center"
                >
                  Booking Konsultasi dengan {doctor.name.split(' ').slice(0, 2).join(' ')}
                </Link>
                <a
                  href={`https://api.whatsapp.com/send/?phone=6281911111636&text=${encodeURIComponent(`Halo, saya ingin konsultasi dengan ${doctor.name}`)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="block w-full py-4 border-2 border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded hover:bg-gold hover:text-white transition-all duration-300 text-center flex items-center justify-center gap-2"
                >
                  <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.373-.273.299-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.884 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                  WhatsApp
                </a>
                <a href="https://www.instagram.com/carlaskinclinic/" target="_blank" rel="noopener noreferrer"
                  className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                  <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                </a>
                <a href="https://www.facebook.com/carlaskinclinic.fb" target="_blank" rel="noopener noreferrer"
                  className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                  <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                </a>
                <a href="https://www.tiktok.com/@carlaskinclinic" target="_blank" rel="noopener noreferrer"
                  className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                  <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>
                </a>
                <button onClick={() => { navigator.clipboard.writeText(window.location.href); alert('Link copied!'); }}
                  className="w-10 h-10 bg-blush rounded-full flex items-center justify-center hover:bg-gold hover:text-white transition group">
                  <svg className="w-5 h-5 text-espresso group-hover:text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg>
                </button>
              </div>
            </aside>

            {/* Main Content */}
            <div className="lg:col-span-2 space-y-8">
              {/* Bio */}
              <div className="bg-white rounded-2xl p-8 shadow-sm border border-blush">
                <h3 className="font-cormorant text-2xl font-bold text-espresso mb-6">Tentang Dokter</h3>
                <div className="prose prose-lg max-w-none prose-headings:font-cormorant prose-headings:text-espresso prose-p:text-grey-dark">
                  {bioParagraphs.map((para: string, idx: number) => (
                    <p key={idx}>{para}</p>
                  ))}
                </div>

                {educationLines.length > 0 && (
                  <div className="mt-8 pt-6 border-t border-blush">
                    <h4 className="font-semibold text-espresso mb-3">Pendidikan</h4>
                    <ul className="space-y-1 text-sm text-grey-dark">
                      {educationLines.map((line: string, idx: number) => (
                        <li key={idx} className="flex items-start gap-2">
                          <span className="text-gold mt-1">•</span>
                          <span>{line}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>

              {/* Services */}
              {services.length > 0 && (
                <div className="bg-white rounded-2xl p-8 shadow-sm border border-blush">
                  <h3 className="font-cormorant text-2xl font-bold text-espresso mb-6">Layanan yang Ditangani</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    {services.map((svc: string, idx: number) => (
                      <div key={idx} className="flex items-center gap-3 p-3 bg-blush/30 rounded-lg">
                        <span className="w-2 h-2 bg-gold rounded-full flex-shrink-0"></span>
                        <span className="text-grey-dark">{svc.replace('clara-', '').replace(/-/g, ' ')}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Related Doctors */}
              {relatedDoctors.length > 0 && (
                <div className="bg-white rounded-2xl p-8 shadow-sm border border-blush">
                  <h3 className="font-cormorant text-2xl font-bold text-espresso mb-6">Dokter Lainnya</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    {relatedDoctors.map((d) => (
                      <Link key={d.id} href={`/dokter/${d.slug}`} className="group block">
                        <div className="bg-white rounded-xl overflow-hidden shadow-sm border border-blush hover:shadow-lg transition-all duration-300 h-full">
                          <div className="relative h-32 bg-blush flex items-center justify-center text-4xl overflow-hidden">
                            {d.photo ? (
                              <Image
                                src={d.photo}
                                alt={d.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-4xl">👨‍⚕️</div>
                            )}
                          </div>
                          <div className="p-4">
                            <span className="inline-block px-2 py-1 bg-gold text-white text-xs font-bold rounded-full mb-3">
                              {d.title || 'Sp.KK'}
                            </span>
                            <h4 className="font-cormorant text-lg font-semibold text-espresso mb-1 group-hover:text-gold transition-colors">
                              {d.name}
                            </h4>
                            <p className="text-gold text-xs font-semibold mb-2">{d.specialty || 'Dermatologi'}</p>
                            <span className="text-xs text-grey">Lihat Detail →</span>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                  <div className="text-center mt-8">
                    <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">
                      Lihat Semua Dokter
                    </Link>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </main>
  );
}