'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 Promo {
  id: number;
  title: string;
  description: string | null;
  image: string | null;
  normalPrice: string | null;
  promoPrice: string | null;
  discount: string | null;
  periodStart: string | null;
  periodEnd: string | null;
  category: string;
  featured: boolean;
  isActive: boolean;
}

interface Category {
  id: number;
  name: string;
  slug: string;
}

interface PromoForm {
  title: string;
  slug: string;
  description: string;
  normalPrice: string;
  promoPrice: string;
  discount: string;
  periodStart: string;
  periodEnd: string;
  category: string;
  featured: boolean;
  isActive: boolean;
}

export default function AdminPromoPage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [promos, setPromos] = useState<Promo[]>([]);
  const [promoCategories, setPromoCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [filterCat, setFilterCat] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const perPage = 10;

  const [form, setForm] = useState<PromoForm>({
    title: '',
    slug: '',
    description: '',
    normalPrice: '',
    promoPrice: '',
    discount: '',
    periodStart: '',
    periodEnd: '',
    category: '',
    featured: false,
    isActive: true,
  });

  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [showCatModal, setShowCatModal] = useState(false);
  const [editingCatId, setEditingCatId] = useState<number | null>(null);
  const [catForm, setCatForm] = useState({ name: '', slug: '' });
  const [msg, setMsg] = useState('');
  const [msgType, setMsgType] = useState<'success' | 'error'>('success');

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

  const loadData = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('admin_token');
      const [promosRes, categoriesRes] = await Promise.all([
        fetch(`${apiUrl}/api/promos`, { headers: { Authorization: `Bearer ${token}` } }),
        fetch(`${apiUrl}/api/promo-categories`, { headers: { Authorization: `Bearer ${token}` } }),
      ]);

      if (promosRes.ok) setPromos(await promosRes.json());
      else setPromos([]);

      if (categoriesRes.ok) setPromoCategories(await categoriesRes.json());
      else setPromoCategories([]);
    } catch (e) {
      showMsg('Gagal memuat data', 'error');
    } finally {
      setLoading(false);
    }
  };

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

  // Strip HTML tags for plain text display
  const stripHtml = (html: string | null) => (html || '').replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim();

  const filtered = promos.filter(p => {
    const matchCat = !filterCat || p.category === filterCat;
    const matchSearch = p.title.toLowerCase().includes(search.toLowerCase()) || (p.description || '').toLowerCase().includes(search.toLowerCase());
    return matchCat && matchSearch;
  });

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

  // Auto-generate slug from title
  const handleTitleChange = (title: string) => {
    const autoSlug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
    setForm({ ...form, title, slug: editingId ? form.slug : autoSlug });
  };

  const openCreate = () => {
    setEditingId(null);
    setForm({
      title: '',
      slug: '',
      description: '',
      normalPrice: '',
      promoPrice: '',
      discount: '',
      periodStart: '',
      periodEnd: '',
      category: promoCategories[0]?.slug || '',
      featured: false,
      isActive: true,
    });
    setImageFile(null);
    setImagePreview(null);
    setShowForm(true);
  };

  const openEdit = (promo: Promo) => {
    setEditingId(promo.id);
    // Use periodStart and periodEnd directly from promo object
    const periodStart = promo.periodStart ? promo.periodStart.split('T')[0] : '';
    const periodEnd = promo.periodEnd ? promo.periodEnd.split('T')[0] : '';
    setForm({
      title: promo.title,
      slug: promo.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''),
      description: promo.description || '',
      normalPrice: promo.normalPrice || '',
      promoPrice: promo.promoPrice || '',
      discount: promo.discount || '',
      periodStart,
      periodEnd,
      category: promo.category || '',
      featured: promo.featured,
      isActive: promo.isActive,
    });
    setImageFile(null);
    // Set preview to show existing image if available
    setImagePreview(promo.image ? `http://localhost:5000${promo.image}` : null);
    setShowForm(true);
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Check file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      showMsg('File terlalu besar (max 5MB)', 'error');
      return;
    }

    // Check file type
    if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
      showMsg('Format file tidak didukung (JPEG, PNG, GIF, WebP)', 'error');
      return;
    }

    setImageFile(file);
    const reader = new FileReader();
    reader.onload = (event) => {
      setImagePreview(event.target?.result as string);
    };
    reader.readAsDataURL(file);
  };

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

    // Generate slug if not provided
    const slug = form.slug || form.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');

    const formData = new FormData();
    formData.append('title', form.title);
    formData.append('slug', slug);
    formData.append('description', form.description);
    formData.append('normalPrice', form.normalPrice);
    formData.append('promoPrice', form.promoPrice);
    formData.append('discount', form.discount);
    formData.append('periodStart', form.periodStart);
    formData.append('periodEnd', form.periodEnd);
    formData.append('category', form.category);
    formData.append('featured', form.featured ? 'true' : 'false');
    formData.append('isActive', form.isActive ? 'true' : 'false');
    if (imageFile) formData.append('image', imageFile);

    try {
      const method = editingId ? 'PUT' : 'POST';
      const url = editingId ? `${apiUrl}/api/promos/${editingId}` : `${apiUrl}/api/promos`;
      const res = await fetch(url, {
        method,
        headers: { Authorization: `Bearer ${localStorage.getItem('admin_token')}` },
        body: formData,
      });
      const data = await res.json();
      if (res.ok) {
        showMsg(data.message || 'Promo berhasil disimpan');
        setShowForm(false);
        setPage(1);
        loadData();
      } else {
        showMsg(data.message || 'Gagal menyimpan promo', 'error');
      }
    } catch (e) {
      showMsg('Terjadi kesalahan koneksi', 'error');
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus promo ini?')) return;
    try {
      const res = await fetch(`${apiUrl}/api/promos/${id}`, { method: 'DELETE', headers: headers() });
      const data = await res.json();
      if (res.ok) {
        showMsg(data.message || 'Promo berhasil dihapus');
        loadData();
      } else {
        showMsg(data.message || 'Gagal menghapus promo', 'error');
      }
    } catch (e) {
      showMsg('Terjadi kesalahan koneksi', 'error');
    }
  };

  const showMsg = (text: string, type: 'success' | 'error' = 'success') => {
    setMsg(text);
    setMsgType(type);
    setTimeout(() => setMsg(''), 4000);
  };

  // Category CRUD
  const openCatCreate = () => {
    setEditingCatId(null);
    setCatForm({ name: '', slug: '' });
    setShowCatModal(true);
  };

  const openCatEdit = (cat: Category) => {
    setEditingCatId(cat.id);
    setCatForm({ name: cat.name, slug: cat.slug });
    setShowCatModal(true);
  };

  const handleCatSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!catForm.name || !catForm.slug) {
      showMsg('Nama dan slug kategori wajib diisi', 'error');
      return;
    }
    try {
      const method = editingCatId ? 'PUT' : 'POST';
      const url = editingCatId
        ? `${apiUrl}/api/promo-categories/${editingCatId}`
        : `${apiUrl}/api/promo-categories`;
      const res = await fetch(url, {
        method,
        headers: jsonHeaders(),
        body: JSON.stringify(catForm),
      });
      const data = await res.json();
      if (res.ok) {
        showMsg(data.message || 'Kategori berhasil disimpan');
        setShowCatModal(false);
        loadData();
      } else {
        showMsg(data.message || 'Gagal menyimpan kategori', 'error');
      }
    } catch (e) {
      showMsg('Terjadi kesalahan koneksi', 'error');
    }
  };

  const handleCatDelete = async (id: number) => {
    if (!confirm('Hapus kategori ini?')) return;
    try {
      const res = await fetch(`${apiUrl}/api/promo-categories/${id}`, { method: 'DELETE', headers: headers() });
      const data = await res.json();
      if (res.ok) {
        showMsg(data.message || 'Kategori berhasil dihapus');
        loadData();
      } else {
        showMsg(data.message || 'Gagal menghapus kategori', 'error');
      }
    } catch (e) {
      showMsg('Terjadi kesalahan koneksi', 'error');
    }
  };

  return (
    <AdminLayout title="Promo">
      <div className="space-y-6">
        {msg && (
          <div className={`p-3 rounded-lg text-sm flex items-center gap-2 ${msgType === 'success' ? 'bg-green-50 border border-green-100 text-green-600' : 'bg-red-50 border border-red-100 text-red-600'}`}>
            <span>{msgType === 'success' ? '✅' : '❌'}</span>
            {msg}
          </div>
        )}

        {/* Categories Section */}
        <div className="flex flex-wrap gap-2 items-center">
          <span className="text-xs font-semibold text-gray-400 uppercase mr-1">Kategori:</span>
          {promoCategories.map(c => (
            <div key={c.id} className="group flex items-center gap-1 px-3 py-1 bg-gold/10 text-gold rounded-full text-xs font-medium">
              <span>{c.name}</span>
              <button onClick={() => openCatEdit(c)} className="opacity-0 group-hover:opacity-100 hover:text-gold-dark transition ml-0.5 text-[10px]">✏️</button>
              <button onClick={() => handleCatDelete(c.id)} className="opacity-0 group-hover:opacity-100 hover:text-red-500 transition text-[10px]">✕</button>
            </div>
          ))}
          <button
            onClick={() => openCatCreate()}
            className="px-3 py-1 text-xs border border-dashed border-gray-300 text-gray-400 rounded-full hover:border-gold hover:text-gold transition"
          >
            + Kategori
          </button>
        </div>

        {/* Category Modal */}
        {showCatModal && (
          <div className="bg-white rounded-xl border border-gray-200 p-5">
            <h3 className="font-semibold text-gray-800 mb-3">{editingCatId ? 'Edit' : 'Tambah'} Kategori Promo</h3>
            <form onSubmit={handleCatSubmit} className="flex flex-wrap gap-3 items-end">
              <div>
                <label className="admin-label">Nama</label>
                <input
                  type="text"
                  value={catForm.name}
                  onChange={e =>
                    setCatForm({
                      ...catForm,
                      name: e.target.value,
                      slug: editingCatId ? catForm.slug : e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''),
                    })
                  }
                  required
                  className="admin-input w-52"
                />
              </div>
              <div>
                <label className="admin-label">Slug</label>
                <input
                  type="text"
                  value={catForm.slug}
                  onChange={e => setCatForm({ ...catForm, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })}
                  className="admin-input w-40"
                  placeholder="Otomatis dari nama"
                />
              </div>
              <div className="flex gap-2 items-end">
                <button type="submit" className="admin-btn-primary">
                  {editingCatId ? 'Simpan' : 'Tambah'}
                </button>
                <button type="button" onClick={() => setShowCatModal(false)} className="admin-btn-secondary">
                  Batal
                </button>
              </div>
            </form>
          </div>
        )}

        {/* Top Actions */}
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">
            {promos.length} promo · {promoCategories.length} kategori
          </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 Promo
          </button>
        </div>

        {/* Search & Filter */}
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            type="text"
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="admin-input flex-[3]"
            placeholder="Cari promo..."
          />
          <select
            value={filterCat}
            onChange={e => {
              setFilterCat(e.target.value);
              setPage(1);
            }}
            className="admin-select flex-1 sm:max-w-[220px]"
          >
            <option value="">Semua Kategori</option>
            {promoCategories.map(c => (
              <option key={c.id} value={c.slug}>
                {c.name}
              </option>
            ))}
          </select>
        </div>

        {/* Form */}
        {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'} Promo</h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Judul */}
                <div className="md:col-span-2">
                  <label className="admin-label">Judul Promo *</label>
                  <input
                    type="text"
                    value={form.title}
                    onChange={e => handleTitleChange(e.target.value)}
                    required
                    className="admin-input"
                    placeholder="Masukkan judul promo"
                  />
                </div>

                {/* Slug */}
                <div className="md:col-span-2">
                  <label className="admin-label">Slug (otomatis dari judul)</label>
                  <input
                    type="text"
                    value={form.slug}
                    onChange={e => setForm({ ...form, slug: e.target.value })}
                    className="admin-input bg-gray-50"
                    placeholder="Otomatis generate"
                    disabled
                  />
                </div>

                {/* Deskripsi - using RichTextEditor */}
                <div className="md:col-span-2">
                  <label className="admin-label">Deskripsi</label>
                  <RichTextEditor
                    value={form.description}
                    onChange={(html) => setForm({ ...form, description: html })}
                    placeholder="Deskripsi promo"
                  />
                </div>

                {/* Harga Normal */}
                <div>
                  <label className="admin-label">Harga Normal</label>
                  <input
                    type="text"
                    value={form.normalPrice}
                    onChange={e => setForm({ ...form, normalPrice: e.target.value })}
                    className="admin-input"
                    placeholder="Rp 500.000"
                  />
                </div>

                {/* Harga Promo */}
                <div>
                  <label className="admin-label">Harga Promo</label>
                  <input
                    type="text"
                    value={form.promoPrice}
                    onChange={e => setForm({ ...form, promoPrice: e.target.value })}
                    className="admin-input"
                    placeholder="Rp 350.000"
                  />
                </div>

                {/* Diskon */}
                <div>
                  <label className="admin-label">Diskon</label>
                  <input
                    type="text"
                    value={form.discount}
                    onChange={e => setForm({ ...form, discount: e.target.value })}
                    className="admin-input"
                    placeholder="30%"
                  />
                </div>

                {/* Kategori */}
                <div>
                  <label className="admin-label">Kategori *</label>
                  <select
                    value={form.category}
                    onChange={e => setForm({ ...form, category: e.target.value })}
                    required
                    className="admin-select"
                  >
                    {promoCategories.map(c => (
                      <option key={c.slug} value={c.slug}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Periode Start */}
                <div>
                  <label className="admin-label">Tanggal Mulai</label>
                  <input
                    type="date"
                    value={form.periodStart}
                    onChange={e => setForm({ ...form, periodStart: e.target.value })}
                    className="admin-input"
                  />
                </div>

                {/* Periode End */}
                <div>
                  <label className="admin-label">Tanggal Akhir</label>
                  <input
                    type="date"
                    value={form.periodEnd}
                    onChange={e => setForm({ ...form, periodEnd: e.target.value })}
                    className="admin-input"
                  />
                </div>
              </div>

              {/* Image Section */}
              <div className="bg-gray-50 rounded-lg p-4">
                <label className="admin-label block mb-3">Gambar Promo</label>
                {/* Show preview of selected image */}
                {imagePreview && (
                  <div className="mb-4">
                    <img src={imagePreview} alt="Preview" className="h-32 object-cover rounded-lg border border-gray-200" />
                    <p className="text-xs text-gray-500 mt-1">
                      {editingId ? 'Gambar yang akan diupload' : 'Gambar yang akan diupload'}
                    </p>
                  </div>
                )}
                {/* Show existing image when editing and no new preview */}
                {editingId && !imagePreview && (
                  (() => {
                    const currentPromo = promos.find(p => p.id === editingId);
                    return currentPromo?.image ? (
                      <div className="mb-4">
                        <img src={`${apiUrl}${currentPromo.image}`} alt="Current" className="h-32 object-cover rounded-lg border border-gray-200" />
                        <p className="text-xs text-gray-500 mt-1">Gambar yang sudah ada</p>
                      </div>
                    ) : null;
                  })()
                )}
                <div className="flex items-center gap-2">
                  <label className="inline-flex items-center px-3 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 mr-1" 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={handleImageChange}
                    />
                  </label>
                  <span className="text-xs text-gray-500">(Max 5MB)</span>
                </div>
              </div>

              {/* Checkboxes */}
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={form.featured}
                    onChange={e => setForm({ ...form, featured: e.target.checked })}
                    className="accent-gold"
                  />
                  <span className="text-sm text-gray-600">Tampilkan di Featured (Carousel)</span>
                </label>
                <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>

              {/* Buttons */}
              <div className="flex gap-3 justify-end pt-4 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'} Promo
                </button>
              </div>
            </form>
          </div>
        )}

        {/* Promo Table */}
        {loading ? (
          <p className="text-gray-400">Memuat...</p>
        ) : paginated.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 promo</p>
          </div>
        ) : (
          <>
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Promo</th>
                    <th>Kategori</th>
                    <th>Harga</th>
                    <th>Status</th>
                    <th className="text-right">Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  {paginated.map(p => (
                    <tr key={p.id}>
                      <td>
                        <div className="flex items-center gap-3">
                          {p.image && (
                            <Image src={`${apiUrl}${p.image}`} alt={p.title} width={40} height={40} className="object-cover rounded" />
                          )}
                          <div>
                            <p className="font-medium text-gray-800">{p.title}</p>
                            <p className="text-xs text-gray-400 truncate max-w-sm">{stripHtml(p.description)}</p>
                          </div>
                        </div>
                      </td>
                      <td>
                        <span className="bg-gold/10 text-gold px-2 py-0.5 rounded-full text-xs font-medium">
                          {promoCategories.find(c => c.slug === p.category)?.name || p.category}
                        </span>
                      </td>
                      <td>
                        {p.promoPrice ? (
                          <>
                            <p className="text-sm text-gray-500 line-through">{p.normalPrice}</p>
                            <p className="font-semibold text-gold">{p.promoPrice}</p>
                          </>
                        ) : (
                          <p className="font-medium text-gray-800">{p.normalPrice || '-'}</p>
                        )}
                      </td>
                      <td>
                        <span
                          className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                            p.isActive ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-600'
                          }`}
                        >
                          {p.isActive ? 'Aktif' : 'Tidak Aktif'}
                        </span>
                      </td>
                      <td className="text-right">
                        <button onClick={() => openEdit(p)} className="admin-btn-edit mr-1">
                          Edit
                        </button>
                        <button onClick={() => handleDelete(p.id)} className="admin-btn-danger">
                          Hapus
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}
