'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import AdminLayout from '@/components/admin/AdminLayout';
import { locations as initialLocations } from '@/data/locations';

interface Location {
  id: string; name: string; address: string; city: string;
  phone: string; whatsapp: string; operatingHours: string;
  type: string[]; latitude: number; longitude: number;
}

export default function AdminLocationsPage() {
  const router = useRouter();
  const [locations, setLocations] = useState<Location[]>(initialLocations);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<any>({});
  const [search, setSearch] = useState('');

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

  const filtered = locations.filter(l =>
    l.name.toLowerCase().includes(search.toLowerCase()) ||
    l.city.toLowerCase().includes(search.toLowerCase())
  );

  const openCreate = () => {
    setEditingId(null);
    setForm({ name: '', address: '', city: '', phone: '', whatsapp: '', operatingHours: 'Senin-Minggu 10:00-21:00', type: 'Skin Clinic', latitude: '', longitude: '' });
    setShowForm(true);
  };

  const openEdit = (l: Location) => {
    setEditingId(l.id);
    setForm({ name: l.name, address: l.address, city: l.city, phone: l.phone, whatsapp: l.whatsapp, operatingHours: l.operatingHours, type: l.type.join(', '), latitude: l.latitude.toString(), longitude: l.longitude.toString() });
    setShowForm(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const types = form.type.split(',').map((t: string) => t.trim()).filter(Boolean);
    const data: Location = {
      id: editingId || String(Date.now()), name: form.name, address: form.address,
      city: form.city, phone: form.phone, whatsapp: form.whatsapp,
      operatingHours: form.operatingHours, type: types,
      latitude: parseFloat(form.latitude) || 0, longitude: parseFloat(form.longitude) || 0,
    };
    if (editingId) {
      setLocations(locations.map(l => l.id === editingId ? data : l));
    } else {
      setLocations([...locations, data]);
    }
    setShowForm(false);
  };

  const handleDelete = (id: string) => {
    if (!confirm('Hapus lokasi ini?')) return;
    setLocations(locations.filter(l => l.id !== id));
  };

  return (
    <AdminLayout title="Locations">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{locations.length} cabang</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 Cabang</button>
        </div>

        <input type="text" value={search} onChange={e => setSearch(e.target.value)} className="admin-input" placeholder="Cari cabang atau kota..." />

        {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'} Cabang</h3>
            <form onSubmit={handleSubmit} className="space-y-4 max-w-2xl">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2"><label className="admin-label">Nama Cabang *</label><input type="text" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required className="admin-input" /></div>
                <div className="md:col-span-2"><label className="admin-label">Alamat</label><input type="text" value={form.address} onChange={e => setForm({ ...form, address: e.target.value })} className="admin-input" /></div>
                <div><label className="admin-label">Kota</label><input type="text" value={form.city} onChange={e => setForm({ ...form, city: e.target.value })} className="admin-input" /></div>
                <div><label className="admin-label">Tipe (pisahkan dengan koma)</label><input type="text" value={form.type} onChange={e => setForm({ ...form, type: e.target.value })} className="admin-input" placeholder="Skin Clinic, Premiere" /></div>
                <div><label className="admin-label">Telepon</label><input type="text" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} className="admin-input" /></div>
                <div><label className="admin-label">WhatsApp</label><input type="text" value={form.whatsapp} onChange={e => setForm({ ...form, whatsapp: e.target.value })} className="admin-input" /></div>
                <div><label className="admin-label">Jam Operasional</label><input type="text" value={form.operatingHours} onChange={e => setForm({ ...form, operatingHours: e.target.value })} className="admin-input" /></div>
                <div><label className="admin-label">Latitude</label><input type="text" value={form.latitude} onChange={e => setForm({ ...form, latitude: e.target.value })} className="admin-input" placeholder="-6.1453" /></div>
                <div><label className="admin-label">Longitude</label><input type="text" value={form.longitude} onChange={e => setForm({ ...form, longitude: e.target.value })} className="admin-input" placeholder="106.7878" /></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' : 'Tambah'}</button>
              </div>
            </form>
          </div>
        )}

        {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 cabang</p></div>
        ) : (
          <div className="space-y-3">
            {filtered.map(l => (
              <div key={l.id} className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition">
                <div className="flex items-start justify-between gap-4">
                  <div className="flex-1">
                    <h3 className="font-semibold text-gray-800">{l.name}</h3>
                    <p className="text-xs text-gray-500 mt-1">{l.address}</p>
                    <div className="flex flex-wrap gap-4 mt-2 text-xs text-gray-400">
                      <span>📍 {l.city}</span>
                      <span>📞 {l.phone}</span>
                      <span>💬 {l.whatsapp}</span>
                      <span>🕐 {l.operatingHours}</span>
                    </div>
                    <div className="flex flex-wrap gap-1.5 mt-2">
                      {l.type.map((t, i) => (
                        <span key={i} className={`text-xs px-2 py-0.5 rounded-full font-medium ${t === 'Premiere' ? 'bg-gold/10 text-gold' : t === 'Corporate Office' ? 'bg-purple-50 text-purple-600' : 'bg-gray-50 text-gray-600'}`}>{t}</span>
                      ))}
                    </div>
                  </div>
                  <div className="flex gap-2 flex-shrink-0">
                    <button onClick={() => openEdit(l)} className="admin-btn-edit">Edit</button>
                    <button onClick={() => handleDelete(l.id)} className="admin-btn-danger">Hapus</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </AdminLayout>
  );
}
