'use client';

import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import AdminLayout from '@/components/admin/AdminLayout';
import Pagination from '@/components/admin/Pagination';
import RichTextEditor from '@/components/admin/RichTextEditor';

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 AdminDoctorsPage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [doctors, setDoctors] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [search, setSearch] = useState('');
  const [filterActive, setFilterActive] = useState('');
  const [page, setPage] = useState(1);
  const perPage = 10;

  const [form, setForm] = useState({
    name: '',
    slug: '',
    title: '',
    specialty: '',
    bio: '',
    education: '',
    experience: '',
    services: '',
    isActive: true,
    sortOrder: 0,
  });

  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [msg, setMsg] = useState('');
  const [msgType, setMsgType] = useState<'success' | 'error'>('success');

  useEffect(() => {
    const token = localStorage.getItem('admin_token') || localStorage.getItem('admin_logged_in');
    if (!token) { router.push('/admin/login'); return; }
    loadData();
  }, [router]);

  const loadData = async () => {
    try {
      const token = localStorage.getItem('admin_token');
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/doctors?all=true`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      if (res.ok) setDoctors(await res.json());
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  };

  const headers = () => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` });

  const filtered = doctors.filter(d => {
    const matchActive = !filterActive || (filterActive === 'active' ? d.isActive : !d.isActive);
    const matchSearch = d.name.toLowerCase().includes(search.toLowerCase()) || d.specialty?.toLowerCase().includes(search.toLowerCase());
    return matchActive && matchSearch;
  });

  const totalPages = Math.max(1, Math.ceil(filtered.length / 10));
  const paginated = filtered.slice((page - 1) * 10, page * 10);

  const openCreate = () => {
    setEditingId(null);
    setForm({ name: '', slug: '', title: '', specialty: '', bio: '', education: '', experience: '', services: '', isActive: true, sortOrder: 0 });
    setShowForm(true);
  };

  const openEdit = (d: any) => {
    setEditingId(d.id);
    setForm({ name: d.name, slug: d.slug, title: d.title || '', specialty: d.specialty || '', bio: d.bio || '', education: d.education || '', experience: d.experience || '', services: d.services || '', isActive: d.isActive, sortOrder: d.sortOrder || 0 });
    setShowForm(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMsg('');
    const slug = form.slug || form.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
    const body = { ...form, slug };
    try {
      const method = editingId ? 'PUT' : 'POST';
      const url = editingId ? `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/doctors/${editingId}` : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/doctors`;
      const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` }, body: JSON.stringify(body) });
      if (res.ok) { setShowForm(false); setPage(1); loadData(); }
      else { const d = await res.json(); alert(d.message || 'Gagal'); }
    } catch (e) { alert('Gagal'); }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus dokter ini?')) return;
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/doctors/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` } });
    if (res.ok) loadData(); else alert('Gagal menghapus');
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) { alert('File terlalu besar (max 5MB)'); return; }
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) { alert('Format tidak didukung'); return; }
    const reader = new FileReader();
    reader.onload = () => setImagePreview(reader.result as string);
    reader.readAsDataURL(file);
  };

  return (
    <AdminLayout title="Manajemen Dokter">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{doctors.length} dokter</p>
          <button onClick={openCreate} className="admin-btn-primary">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4"/></svg>
            Tambah Dokter
          </button>
        </div>

        <div className="flex flex-col sm:flex-row gap-3">
          <input type="text" value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} className="admin-input flex-[3]" placeholder="Cari nama atau spesialisasi..." />
          <select value={filterActive} onChange={e => { setFilterActive(e.target.value); setPage(1); }} className="admin-select flex-1 sm:max-w-[220px]">
            <option value="">Semua Status</option>
            <option value="active">Aktif</option>
            <option value="inactive">Nonaktif</option>
          </select>
        </div>

        {showForm && (
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-800 mb-4">{editingId ? 'Edit' : 'Tambah'} Dokter</h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl">
                <div>
                  <label className="admin-label">Nama Lengkap *</label>
                  <input type="text" value={form.name} onChange={e => setForm({ ...form, name: e.target.value, slug: editingId ? form.slug : e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') })} required className="admin-input" placeholder="dr. Sarah Sp.KK" />
                </div>
                <div>
                  <label className="admin-label">Slug (URL)</label>
                  <input type="text" value={form.slug} onChange={e => setForm({ ...form, slug: e.target.value })} className="admin-input" placeholder="dr-sarah-sp-kk" />
                </div>
                <div>
                  <label className="admin-label">Gelar / Title</label>
                  <input type="text" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} className="admin-input" placeholder="Sp.KK, Sp.DV, dll" />
                </div>
                <div>
                  <label className="admin-label">Spesialisasi</label>
                  <input type="text" value={form.specialty} onChange={e => setForm({ ...form, specialty: e.target.value })} className="admin-input" placeholder="Dermatologi & Venereologi" />
                </div>
              </div>

              <div>
                <label className="admin-label">Foto Dokter</label>
                <div className="flex items-center gap-4">
                  <label className="inline-flex items-center gap-2 px-4 py-2 bg-gold text-white text-xs font-semibold rounded-lg cursor-pointer hover:bg-gold-dark transition">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                    Pilih Gambar
                    <input type="file" accept="image/*" className="hidden" onChange={e => { const files = e.target.files; if (!files || files.length === 0) return; const file = files[0]; if (file.size > 5 * 1024 * 1024) { alert('File terlalu besar (max 5MB)'); return; } if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) { alert('Format tidak didukung'); return; } setImagePreview(URL.createObjectURL(file)); }} />
                  </label>
                  {imagePreview && <img src={imagePreview} className="h-16 rounded border object-cover" />}
                </div>
              </div>

              <div>
                <label className="admin-label">Biografi</label>
                <RichTextEditor value={form.bio} onChange={html => setForm({ ...form, bio: html })} placeholder="Tulis biografi dokter..." />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="admin-label">Pendidikan</label>
                  <textarea value={form.education} onChange={e => setForm({ ...form, education: e.target.value })} className="admin-textarea" rows={3} placeholder="FK Universitas Indonesia (S1)\nSpesialis Kulit & Kelamin (Sp.KK) - FKUI/RSCM" />
                </div>
                <div>
                  <label className="admin-label">Pengalaman</label>
                  <input type="text" value={form.experience} onChange={e => setForm({ ...form, experience: e.target.value })} className="admin-input" placeholder="15+ tahun pengalaman" />
                </div>
                <div>
                  <label className="admin-label">Spesialisasi</label>
                  <input type="text" value={form.specialty} onChange={e => setForm({ ...form, specialty: e.target.value })} className="admin-input" placeholder="Dermatologi & Venereologi" />
                </div>
                <div>
                  <label className="admin-label">Gelar / Title</label>
                  <input type="text" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} className="admin-input" placeholder="Sp.KK, Sp.DV, dll" />
                </div>
              </div>

              <div>
                <label className="admin-label">Layanan (pisahkan dengan koma, akan diubah ke JSON array)</label>
                <input type="text" value={form.services} onChange={e => setForm({ ...form, services: e.target.value })} className="admin-input" placeholder="clara-basic-facial, clara-glow-facial, clara-acne-laser" />
              </div>

              <div>
                <label className="admin-label">Pengalaman (teks)</label>
                <input type="text" value={form.experience} onChange={e => setForm({ ...form, experience: e.target.value })} className="admin-input" placeholder="15+ tahun pengalaman" />
              </div>

              <div className="flex items-center gap-3">
                <label className="flex items-center gap-2">
                  <input type="checkbox" checked={form.isActive} onChange={e => setForm({ ...form, isActive: e.target.checked })} className="accent-gold" />
                  <span className="text-sm text-gray-600">Aktif</span>
                </label>
                <div className="flex items-center gap-2 ml-4">
                  <label className="text-sm text-gray-600">Urutan:</label>
                  <input type="number" value={form.sortOrder} onChange={e => setForm({ ...form, sortOrder: parseInt(e.target.value) || 0 })} className="admin-input w-20" />
                </div>
              </div>

              <div className="flex gap-3 justify-end pt-2 border-t border-gray-100">
                <button type="button" onClick={() => setShowForm(false)} className="admin-btn-secondary">Batal</button>
                <button type="submit" className="admin-btn-primary">{editingId ? 'Simpan Perubahan' : 'Tambah Dokter'}</button>
              </div>
            </form>
          </div>
        )}

        {loading ? (
          <p className="text-gray-400">Memuat...</p>
        ) : filtered.length === 0 ? (
          <div className="bg-white rounded-xl border border-gray-200 p-12 text-center"><p className="text-4xl mb-3">👨‍⚕️</p><p className="text-gray-500">Tidak ada dokter</p></div>
        ) : (
          <>
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="admin-table">
                <thead><tr><th>Dokter</th><th>Spesialisasi</th><th>Status</th><th className="text-right">Aksi</th></tr></thead>
                <tbody>{paginated.map(d => (
                  <tr key={d.id}>
                    <td>
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-blush rounded flex items-center justify-center text-xl flex-shrink-0 overflow-hidden">
                          {d.photo ? <img src={d.photo} alt={d.name} className="w-full h-full object-cover" /> : <span className="text-xl">👨‍⚕️</span>}
                        </div>
                        <div>
                          <p className="font-medium text-gray-800">{d.name}</p>
                          <p className="text-xs text-gray-400">{d.specialty}</p>
                        </div>
                      </div>
                    </td>
                    <td className="text-gray-600">{d.specialty}</td>
                    <td>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${d.isActive ? 'bg-green-50 text-green-600' : 'bg-gray-100 text-gray-500'}`}>
                        {d.isActive ? 'Aktif' : 'Nonaktif'}
                      </span>
                    </td>
                    <td className="text-right"><div className="flex gap-1.5 justify-end">
                      <button onClick={() => openEdit(d)} className="admin-btn-edit">Edit</button>
                      <button onClick={() => handleDelete(d.id)} className="admin-btn-danger">Hapus</button>
                    </div></td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}