'use client';

import { useState, useEffect } from 'react';
import type { Service } from '@/lib/types';

export default function AdminServices() {
  const [services, setServices] = useState<Service[]>([]);
  const [editing, setEditing] = useState<Service | null>(null);
  const [isNew, setIsNew] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchServices = async () => {
    const res = await fetch('/api/admin/services');
    setServices(await res.json());
    setLoading(false);
  };

  useEffect(() => { fetchServices(); }, []);

  const handleSave = async () => {
    if (!editing) return;
    const method = isNew ? 'POST' : 'PUT';
    const url = isNew ? '/api/admin/services' : `/api/admin/services/${editing.id}`;
    await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(editing),
    });
    setEditing(null);
    setIsNew(false);
    fetchServices();
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this service?')) return;
    await fetch(`/api/admin/services/${id}`, { method: 'DELETE' });
    fetchServices();
  };

  const handleUpload = async (file: File): Promise<string> => {
    const form = new FormData();
    form.append('file', file);
    const res = await fetch('/api/admin/upload', { method: 'POST', body: form });
    const data = await res.json();
    return data.url || '';
  };

  const updateBullet = (field: 'howItWorks' | 'whoItIsFor', index: number, value: string) => {
    if (!editing) return;
    const arr = [...editing[field]];
    arr[index] = value;
    setEditing({ ...editing, [field]: arr });
  };

  const addBullet = (field: 'howItWorks' | 'whoItIsFor') => {
    if (!editing) return;
    setEditing({ ...editing, [field]: [...editing[field], ''] });
  };

  const removeBullet = (field: 'howItWorks' | 'whoItIsFor', index: number) => {
    if (!editing) return;
    setEditing({ ...editing, [field]: editing[field].filter((_, i) => i !== index) });
  };

  const newService = (): Service => ({
    id: `service-${Date.now()}`,
    title: '',
    subtitle: '',
    duration: '',
    description: '',
    howItWorks: ['', '', ''],
    whoItIsFor: ['', '', ''],
    image: '',
    color: 'lavender',
    calendlyLink: '',
    highlighted: false,
    sortOrder: services.length + 1,
  });

  if (loading) return <div className="p-8 text-gray-400">Loading...</div>;

  return (
    <div className="p-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-light">Services</h1>
        <button
          onClick={() => { setEditing(newService()); setIsNew(true); }}
          className="px-4 py-2 bg-[#2d2d2d] text-white rounded-lg text-sm hover:bg-[#c9a962] transition-colors"
        >
          + Add Service
        </button>
      </div>

      {/* Edit Modal */}
      {editing && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-6">
            <h2 className="text-xl font-light mb-4">{isNew ? 'New Service' : 'Edit Service'}</h2>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">TITLE</label>
                  <input value={editing.title} onChange={(e) => setEditing({...editing, title: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">SUBTITLE</label>
                  <input value={editing.subtitle} onChange={(e) => setEditing({...editing, subtitle: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">DURATION</label>
                  <input value={editing.duration} onChange={(e) => setEditing({...editing, duration: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">COLOR</label>
                  <select value={editing.color} onChange={(e) => setEditing({...editing, color: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]">
                    <option value="lavender">Lavender</option>
                    <option value="pink">Pink</option>
                    <option value="mint">Mint</option>
                    <option value="rose">Rose</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-xs tracking-widest mb-1">DESCRIPTION</label>
                <textarea value={editing.description} onChange={(e) => setEditing({...editing, description: e.target.value})} rows={3}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962] resize-none" />
              </div>
              <div>
                <label className="block text-xs tracking-widest mb-1">IMAGE</label>
                {editing.image && (
                  <div className="w-20 h-14 bg-gray-100 rounded overflow-hidden mb-2">
                    <img src={editing.image} alt="" className="w-full h-full object-cover" />
                  </div>
                )}
                <label className="text-xs text-blue-600 hover:text-blue-800 cursor-pointer block mb-2">
                  Upload image
                  <input type="file" accept="image/*" className="hidden" onChange={async (e) => {
                    const file = e.target.files?.[0];
                    if (file) { const url = await handleUpload(file); if (url) setEditing({...editing, image: url}); }
                  }} />
                </label>
                <input value={editing.image} onChange={(e) => setEditing({...editing, image: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]"
                  placeholder="Or paste image path" />
              </div>

              {/* How it works */}
              <div>
                <label className="block text-xs tracking-widest mb-2">HOW IT WORKS</label>
                {editing.howItWorks.map((bullet, i) => (
                  <div key={i} className="flex gap-2 mb-2">
                    <input value={bullet} onChange={(e) => updateBullet('howItWorks', i, e.target.value)}
                      className="flex-1 px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                    <button onClick={() => removeBullet('howItWorks', i)} className="text-red-400 hover:text-red-600 text-xs px-2">x</button>
                  </div>
                ))}
                <button onClick={() => addBullet('howItWorks')} className="text-xs text-blue-600 hover:text-blue-800">+ Add bullet</button>
              </div>

              {/* Who it is for */}
              <div>
                <label className="block text-xs tracking-widest mb-2">WHO IT IS FOR</label>
                {editing.whoItIsFor.map((bullet, i) => (
                  <div key={i} className="flex gap-2 mb-2">
                    <input value={bullet} onChange={(e) => updateBullet('whoItIsFor', i, e.target.value)}
                      className="flex-1 px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                    <button onClick={() => removeBullet('whoItIsFor', i)} className="text-red-400 hover:text-red-600 text-xs px-2">x</button>
                  </div>
                ))}
                <button onClick={() => addBullet('whoItIsFor')} className="text-xs text-blue-600 hover:text-blue-800">+ Add bullet</button>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">CALENDLY LINK</label>
                  <input value={editing.calendlyLink} onChange={(e) => setEditing({...editing, calendlyLink: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]"
                    placeholder="https://calendly.com/..." />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">SORT ORDER</label>
                  <input type="number" value={editing.sortOrder} onChange={(e) => setEditing({...editing, sortOrder: parseInt(e.target.value) || 0})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
              </div>
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" checked={editing.highlighted} onChange={(e) => setEditing({...editing, highlighted: e.target.checked})} />
                Highlighted (gold ring)
              </label>
            </div>
            <div className="flex gap-3 mt-6">
              <button onClick={handleSave} className="px-6 py-2 bg-[#2d2d2d] text-white rounded-lg text-sm hover:bg-[#c9a962] transition-colors">
                Save
              </button>
              <button onClick={() => { setEditing(null); setIsNew(false); }} className="px-6 py-2 border rounded-lg text-sm hover:bg-gray-50">
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Services List */}
      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left">
            <tr>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">IMAGE</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">TITLE</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">SUBTITLE</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">COLOR</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">ACTIONS</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {services.sort((a, b) => a.sortOrder - b.sortOrder).map((service) => (
              <tr key={service.id} className="hover:bg-gray-50">
                <td className="px-4 py-3">
                  {service.image && (
                    <div className="w-16 h-10 rounded overflow-hidden bg-gray-100">
                      <img src={service.image} alt="" className="w-full h-full object-cover" />
                    </div>
                  )}
                </td>
                <td className="px-4 py-3 font-medium">{service.title}</td>
                <td className="px-4 py-3 text-gray-500">{service.subtitle}</td>
                <td className="px-4 py-3">
                  <span className={`inline-block w-4 h-4 rounded-full ${
                    service.color === 'lavender' ? 'bg-[#d4c4e8]' :
                    service.color === 'pink' ? 'bg-[#e8c4d4]' :
                    service.color === 'mint' ? 'bg-[#c4e8d4]' :
                    'bg-[#e8d4c4]'
                  }`} />
                </td>
                <td className="px-4 py-3">
                  <button onClick={() => { setEditing(service); setIsNew(false); }} className="text-blue-600 hover:text-blue-800 mr-3 text-xs">Edit</button>
                  <button onClick={() => handleDelete(service.id)} className="text-red-600 hover:text-red-800 text-xs">Delete</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
