'use client';

import { useState, useEffect, useCallback } from 'react';

// ─── Types ───────────────────────────────────────────────────────────────────

interface Artwork {
  src: string;
  title: string;
  price?: string;
  available?: boolean;
  medium?: string;
  dimensions?: string;
}

interface Service {
  title: string;
  subtitle: string;
  duration: string;
  price?: string;
  description: string;
  longDescription?: string;
  color: string;
  image: string;
  highlighted?: boolean;
  recommendedFor?: string[];
}

interface Testimonial {
  quote: string;
  author: string;
  context?: string;
}

interface ReEvolutionEvent {
  title: string;
  description: string;
  image: string;
  objectPosition?: string;
}

type Tab = 'artworks' | 'services' | 'testimonials' | 'events';

// ─── Helpers ─────────────────────────────────────────────────────────────────

function getPassword(): string {
  return sessionStorage.getItem('admin_password') || '';
}

async function apiFetch(url: string, options?: RequestInit) {
  const headers: Record<string, string> = {
    'X-Admin-Password': getPassword(),
    ...(options?.headers as Record<string, string> || {}),
  };
  if (!(options?.body instanceof FormData)) {
    headers['Content-Type'] = 'application/json';
  }
  return fetch(url, { ...options, headers });
}

// ─── Auth Gate ───────────────────────────────────────────────────────────────

function AuthGate({ onAuth }: { onAuth: () => void }) {
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    const res = await fetch('/api/cms/auth', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ password }),
    });

    if (res.ok) {
      sessionStorage.setItem('admin_password', password);
      onAuth();
    } else {
      setError('Invalid password');
    }
    setLoading(false);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-[var(--bg-cream)]">
      <form onSubmit={handleSubmit} className="bg-white p-8 rounded-xl shadow-lg max-w-sm w-full">
        <h1 className="text-2xl font-light mb-6 text-center">Site Admin</h1>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password"
          className="w-full px-4 py-3 border border-gray-200 rounded-lg mb-4 focus:outline-none focus:border-[var(--accent-gold)]"
          autoFocus
        />
        {error && <p className="text-red-600 text-sm mb-4">{error}</p>}
        <button
          type="submit"
          disabled={loading}
          className="btn-filled w-full"
          style={loading ? { opacity: 0.7, cursor: 'not-allowed' } : undefined}
        >
          {loading ? 'Checking...' : 'Sign In'}
        </button>
      </form>
    </div>
  );
}

// ─── Image Upload Button ─────────────────────────────────────────────────────

function ImageUpload({ onUploaded }: { onUploaded: (url: string) => void }) {
  const [uploading, setUploading] = useState(false);

  const handleFile = async (file: File) => {
    setUploading(true);
    const form = new FormData();
    form.append('file', file);
    const res = await apiFetch('/api/cms/upload', { method: 'POST', body: form });
    if (res.ok) {
      const { url } = await res.json();
      onUploaded(url);
    } else {
      alert('Upload failed');
    }
    setUploading(false);
  };

  return (
    <label className="inline-flex items-center gap-2 px-3 py-1.5 border border-gray-300 rounded-lg cursor-pointer hover:border-[var(--accent-gold)] transition-colors text-sm">
      {uploading ? 'Uploading...' : 'Upload Image'}
      <input
        type="file"
        accept="image/*"
        className="hidden"
        onChange={(e) => e.target.files?.[0] && handleFile(e.target.files[0])}
        disabled={uploading}
      />
    </label>
  );
}

// ─── Artworks Tab ────────────────────────────────────────────────────────────

function ArtworksTab() {
  const [featured, setFeatured] = useState<Artwork[]>([]);
  const [all, setAll] = useState<Artwork[]>([]);
  const [saving, setSaving] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [editMode, setEditMode] = useState<'featured' | 'gallery'>('featured');

  const load = useCallback(async () => {
    const res = await apiFetch('/api/cms/artworks');
    if (res.ok) {
      const data = await res.json();
      setFeatured(data.featured);
      setAll(data.all);
      setLoaded(true);
    }
  }, []);

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

  const save = async () => {
    setSaving(true);
    await apiFetch('/api/cms/artworks', {
      method: 'POST',
      body: JSON.stringify({ featured, all }),
    });
    setSaving(false);
  };

  const items = editMode === 'featured' ? featured : all;
  const setItems = editMode === 'featured' ? setFeatured : setAll;

  const addItem = () => {
    const newItem: Artwork = { src: '', title: '' };
    if (editMode === 'featured') {
      newItem.price = '';
      newItem.medium = '';
      newItem.available = true;
    }
    setItems([...items, newItem]);
  };

  const updateItem = (index: number, field: keyof Artwork, value: string | boolean) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const removeItem = (index: number) => {
    if (!confirm('Delete this artwork?')) return;
    setItems(items.filter((_, i) => i !== index));
  };

  const moveItem = (index: number, direction: -1 | 1) => {
    const newIndex = index + direction;
    if (newIndex < 0 || newIndex >= items.length) return;
    const updated = [...items];
    [updated[index], updated[newIndex]] = [updated[newIndex], updated[index]];
    setItems(updated);
  };

  if (!loaded) return <p className="p-8 text-center opacity-60">Loading...</p>;

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => setEditMode('featured')}
          className={`px-4 py-2 rounded-lg text-sm ${editMode === 'featured' ? 'bg-[var(--accent-gold)] text-white' : 'border border-gray-300'}`}
        >
          Featured ({featured.length})
        </button>
        <button
          onClick={() => setEditMode('gallery')}
          className={`px-4 py-2 rounded-lg text-sm ${editMode === 'gallery' ? 'bg-[var(--accent-gold)] text-white' : 'border border-gray-300'}`}
        >
          Gallery ({all.length})
        </button>
        <div className="flex-1" />
        <button onClick={addItem} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm">
          + Add
        </button>
        <button onClick={save} disabled={saving} className="px-4 py-2 bg-[var(--accent-gold)] text-white rounded-lg text-sm">
          {saving ? 'Saving...' : 'Save All'}
        </button>
      </div>

      <div className="space-y-4">
        {items.map((item, i) => (
          <div key={i} className="border border-gray-200 rounded-lg p-4 bg-white">
            <div className="flex items-start gap-4">
              {item.src && (
                <div className="w-16 h-16 rounded overflow-hidden flex-shrink-0 bg-gray-100">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={item.src} alt={item.title} className="w-full h-full object-cover" />
                </div>
              )}
              <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
                <input
                  value={item.title}
                  onChange={(e) => updateItem(i, 'title', e.target.value)}
                  placeholder="Title"
                  className="px-3 py-2 border border-gray-200 rounded text-sm"
                />
                <div className="flex gap-2">
                  <input
                    value={item.src}
                    onChange={(e) => updateItem(i, 'src', e.target.value)}
                    placeholder="Image path (e.g. /images/art/...)"
                    className="flex-1 px-3 py-2 border border-gray-200 rounded text-sm"
                  />
                  <ImageUpload onUploaded={(url) => updateItem(i, 'src', url)} />
                </div>
                {editMode === 'featured' && (
                  <>
                    <input
                      value={item.price || ''}
                      onChange={(e) => updateItem(i, 'price', e.target.value)}
                      placeholder="Price (e.g. CHF 4,800)"
                      className="px-3 py-2 border border-gray-200 rounded text-sm"
                    />
                    <input
                      value={item.medium || ''}
                      onChange={(e) => updateItem(i, 'medium', e.target.value)}
                      placeholder="Medium"
                      className="px-3 py-2 border border-gray-200 rounded text-sm"
                    />
                    <label className="flex items-center gap-2 text-sm">
                      <input
                        type="checkbox"
                        checked={item.available ?? false}
                        onChange={(e) => updateItem(i, 'available', e.target.checked)}
                      />
                      Available
                    </label>
                  </>
                )}
              </div>
              <div className="flex flex-col gap-1">
                <button onClick={() => moveItem(i, -1)} className="text-gray-400 hover:text-gray-600 text-xs" title="Move up">&uarr;</button>
                <button onClick={() => moveItem(i, 1)} className="text-gray-400 hover:text-gray-600 text-xs" title="Move down">&darr;</button>
                <button onClick={() => removeItem(i)} className="text-red-400 hover:text-red-600 text-xs" title="Delete">&times;</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Services Tab ────────────────────────────────────────────────────────────

function ServicesTab() {
  const [items, setItems] = useState<Service[]>([]);
  const [saving, setSaving] = useState(false);
  const [loaded, setLoaded] = useState(false);

  const load = useCallback(async () => {
    const res = await apiFetch('/api/cms/services');
    if (res.ok) {
      const data = await res.json();
      setItems(data.services);
      setLoaded(true);
    }
  }, []);

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

  const save = async () => {
    setSaving(true);
    await apiFetch('/api/cms/services', {
      method: 'POST',
      body: JSON.stringify({ services: items }),
    });
    setSaving(false);
  };

  const updateItem = (index: number, field: keyof Service, value: string | boolean | string[]) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const addItem = () => {
    setItems([...items, {
      title: '', subtitle: '', duration: '', description: '',
      color: 'lavender', image: '',
    }]);
  };

  const removeItem = (index: number) => {
    if (!confirm('Delete this service?')) return;
    setItems(items.filter((_, i) => i !== index));
  };

  if (!loaded) return <p className="p-8 text-center opacity-60">Loading...</p>;

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <span className="text-sm text-gray-500">{items.length} services</span>
        <div className="flex-1" />
        <button onClick={addItem} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm">
          + Add
        </button>
        <button onClick={save} disabled={saving} className="px-4 py-2 bg-[var(--accent-gold)] text-white rounded-lg text-sm">
          {saving ? 'Saving...' : 'Save All'}
        </button>
      </div>

      <div className="space-y-6">
        {items.map((item, i) => (
          <div key={i} className="border border-gray-200 rounded-lg p-4 bg-white">
            <div className="flex items-center justify-between mb-3">
              <h4 className="font-medium">{item.title || '(untitled)'}</h4>
              <button onClick={() => removeItem(i)} className="text-red-400 hover:text-red-600 text-sm">Delete</button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <input
                value={item.title}
                onChange={(e) => updateItem(i, 'title', e.target.value)}
                placeholder="Title"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
              <input
                value={item.subtitle}
                onChange={(e) => updateItem(i, 'subtitle', e.target.value)}
                placeholder="Subtitle"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
              <input
                value={item.duration}
                onChange={(e) => updateItem(i, 'duration', e.target.value)}
                placeholder="Duration"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
              <input
                value={item.price || ''}
                onChange={(e) => updateItem(i, 'price', e.target.value)}
                placeholder="Price (optional)"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
              <div className="flex gap-2">
                <input
                  value={item.image}
                  onChange={(e) => updateItem(i, 'image', e.target.value)}
                  placeholder="Image path"
                  className="flex-1 px-3 py-2 border border-gray-200 rounded text-sm"
                />
                <ImageUpload onUploaded={(url) => updateItem(i, 'image', url)} />
              </div>
              <select
                value={item.color}
                onChange={(e) => updateItem(i, 'color', e.target.value)}
                className="px-3 py-2 border border-gray-200 rounded text-sm bg-white"
              >
                <option value="lavender">Lavender</option>
                <option value="mint">Mint</option>
                <option value="rose">Rose</option>
                <option value="pink">Pink</option>
              </select>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={item.highlighted ?? false}
                  onChange={(e) => updateItem(i, 'highlighted', e.target.checked)}
                />
                Highlighted
              </label>
            </div>
            <textarea
              value={item.description}
              onChange={(e) => updateItem(i, 'description', e.target.value)}
              placeholder="Short description"
              rows={2}
              className="w-full mt-3 px-3 py-2 border border-gray-200 rounded text-sm resize-none"
            />
            <textarea
              value={item.longDescription || ''}
              onChange={(e) => updateItem(i, 'longDescription', e.target.value)}
              placeholder="Long description (optional)"
              rows={3}
              className="w-full mt-2 px-3 py-2 border border-gray-200 rounded text-sm resize-none"
            />
            <div className="mt-2">
              <label className="block text-xs text-gray-500 mb-1">Recommended For (one per line)</label>
              <textarea
                value={(item.recommendedFor || []).join('\n')}
                onChange={(e) => updateItem(i, 'recommendedFor', e.target.value.split('\n').filter(Boolean))}
                rows={3}
                placeholder="One item per line"
                className="w-full px-3 py-2 border border-gray-200 rounded text-sm resize-none"
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Testimonials Tab ────────────────────────────────────────────────────────

function TestimonialsTab() {
  const [items, setItems] = useState<Testimonial[]>([]);
  const [saving, setSaving] = useState(false);
  const [loaded, setLoaded] = useState(false);

  const load = useCallback(async () => {
    const res = await apiFetch('/api/cms/testimonials');
    if (res.ok) {
      setItems(await res.json());
      setLoaded(true);
    }
  }, []);

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

  const save = async () => {
    setSaving(true);
    await apiFetch('/api/cms/testimonials', {
      method: 'POST',
      body: JSON.stringify(items),
    });
    setSaving(false);
  };

  const updateItem = (index: number, field: keyof Testimonial, value: string) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const addItem = () => {
    setItems([...items, { quote: '', author: '' }]);
  };

  const removeItem = (index: number) => {
    if (!confirm('Delete this testimonial?')) return;
    setItems(items.filter((_, i) => i !== index));
  };

  if (!loaded) return <p className="p-8 text-center opacity-60">Loading...</p>;

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <span className="text-sm text-gray-500">{items.length} testimonials</span>
        <div className="flex-1" />
        <button onClick={addItem} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm">
          + Add
        </button>
        <button onClick={save} disabled={saving} className="px-4 py-2 bg-[var(--accent-gold)] text-white rounded-lg text-sm">
          {saving ? 'Saving...' : 'Save All'}
        </button>
      </div>

      <div className="space-y-4">
        {items.map((item, i) => (
          <div key={i} className="border border-gray-200 rounded-lg p-4 bg-white">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm font-medium">{item.author || '(no author)'}</span>
              <button onClick={() => removeItem(i)} className="text-red-400 hover:text-red-600 text-sm">Delete</button>
            </div>
            <textarea
              value={item.quote}
              onChange={(e) => updateItem(i, 'quote', e.target.value)}
              placeholder="Quote"
              rows={3}
              className="w-full px-3 py-2 border border-gray-200 rounded text-sm resize-none mb-2"
            />
            <div className="grid grid-cols-2 gap-3">
              <input
                value={item.author}
                onChange={(e) => updateItem(i, 'author', e.target.value)}
                placeholder="Author"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
              <input
                value={item.context || ''}
                onChange={(e) => updateItem(i, 'context', e.target.value)}
                placeholder="Context (e.g. Crystal Therapy)"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Events Tab ──────────────────────────────────────────────────────────────

function EventsTab() {
  const [items, setItems] = useState<ReEvolutionEvent[]>([]);
  const [saving, setSaving] = useState(false);
  const [loaded, setLoaded] = useState(false);

  const load = useCallback(async () => {
    const res = await apiFetch('/api/cms/events');
    if (res.ok) {
      const data = await res.json();
      setItems(data.events);
      setLoaded(true);
    }
  }, []);

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

  const save = async () => {
    setSaving(true);
    await apiFetch('/api/cms/events', {
      method: 'POST',
      body: JSON.stringify({ events: items }),
    });
    setSaving(false);
  };

  const updateItem = (index: number, field: keyof ReEvolutionEvent, value: string) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const addItem = () => {
    setItems([...items, { title: '', description: '', image: '' }]);
  };

  const removeItem = (index: number) => {
    if (!confirm('Delete this event?')) return;
    setItems(items.filter((_, i) => i !== index));
  };

  if (!loaded) return <p className="p-8 text-center opacity-60">Loading...</p>;

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <span className="text-sm text-gray-500">{items.length} events</span>
        <div className="flex-1" />
        <button onClick={addItem} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm">
          + Add
        </button>
        <button onClick={save} disabled={saving} className="px-4 py-2 bg-[var(--accent-gold)] text-white rounded-lg text-sm">
          {saving ? 'Saving...' : 'Save All'}
        </button>
      </div>

      <div className="space-y-4">
        {items.map((item, i) => (
          <div key={i} className="border border-gray-200 rounded-lg p-4 bg-white">
            <div className="flex items-center justify-between mb-3">
              <h4 className="font-medium">{item.title || '(untitled)'}</h4>
              <button onClick={() => removeItem(i)} className="text-red-400 hover:text-red-600 text-sm">Delete</button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <input
                value={item.title}
                onChange={(e) => updateItem(i, 'title', e.target.value)}
                placeholder="Title"
                className="px-3 py-2 border border-gray-200 rounded text-sm"
              />
              <div className="flex gap-2">
                <input
                  value={item.image}
                  onChange={(e) => updateItem(i, 'image', e.target.value)}
                  placeholder="Image path"
                  className="flex-1 px-3 py-2 border border-gray-200 rounded text-sm"
                />
                <ImageUpload onUploaded={(url) => updateItem(i, 'image', url)} />
              </div>
            </div>
            <textarea
              value={item.description}
              onChange={(e) => updateItem(i, 'description', e.target.value)}
              placeholder="Description"
              rows={2}
              className="w-full mt-3 px-3 py-2 border border-gray-200 rounded text-sm resize-none"
            />
            <input
              value={item.objectPosition || ''}
              onChange={(e) => updateItem(i, 'objectPosition', e.target.value)}
              placeholder="Object position (optional, e.g. center top)"
              className="w-full mt-2 px-3 py-2 border border-gray-200 rounded text-sm"
            />
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Main CMS Page ───────────────────────────────────────────────────────────

export default function UpdatePage() {
  const [authenticated, setAuthenticated] = useState(false);
  const [activeTab, setActiveTab] = useState<Tab>('artworks');

  // Check if already authenticated from sessionStorage
  useEffect(() => {
    const pw = sessionStorage.getItem('admin_password');
    if (pw) {
      fetch('/api/cms/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password: pw }),
      }).then((res) => {
        if (res.ok) setAuthenticated(true);
        else sessionStorage.removeItem('admin_password');
      });
    }
  }, []);

  if (!authenticated) {
    return <AuthGate onAuth={() => setAuthenticated(true)} />;
  }

  const tabs: { key: Tab; label: string }[] = [
    { key: 'artworks', label: 'Artworks' },
    { key: 'services', label: 'Services' },
    { key: 'testimonials', label: 'Testimonials' },
    { key: 'events', label: 'Events' },
  ];

  return (
    <div className="min-h-screen bg-[var(--bg-cream)] pt-24 pb-12 px-4">
      <div className="max-w-5xl mx-auto">
        <div className="flex items-center justify-between mb-8">
          <h1 className="text-3xl font-light">Content Manager</h1>
          <button
            onClick={() => {
              sessionStorage.removeItem('admin_password');
              setAuthenticated(false);
            }}
            className="text-sm text-gray-500 hover:text-gray-700"
          >
            Sign Out
          </button>
        </div>

        {/* Tabs */}
        <div className="flex gap-2 mb-8 border-b border-gray-200 pb-2">
          {tabs.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`px-4 py-2 rounded-t-lg text-sm transition-colors ${
                activeTab === tab.key
                  ? 'bg-white border border-b-0 border-gray-200 text-[var(--text-dark)]'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Tab Content */}
        {activeTab === 'artworks' && <ArtworksTab />}
        {activeTab === 'services' && <ServicesTab />}
        {activeTab === 'testimonials' && <TestimonialsTab />}
        {activeTab === 'events' && <EventsTab />}
      </div>
    </div>
  );
}
