'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import {
  Package,
  Plus,
  Edit2,
  Trash2,
  Eye,
  CheckCircle2,
  X,
  Save,
  Image as ImageIcon,
  FileCode,
  DollarSign,
} from 'lucide-react';
import { Product, Category, PlanOption } from '@/types';
import AdminSidebar from '@/components/admin/AdminSidebar';

interface AdminProductsClientProps {
  initialProducts: Product[];
  categories: Category[];
}

export default function AdminProductsClient({
  initialProducts,
  categories,
}: AdminProductsClientProps) {
  const [products, setProducts] = useState<Product[]>(initialProducts);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  // Form State
  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [shortDesc, setShortDesc] = useState('');
  const [fullDesc, setFullDesc] = useState('');
  const [price, setPrice] = useState<number>(0);
  const [regularPrice, setRegularPrice] = useState<number>(0);
  const [isFree, setIsFree] = useState(false);
  const [hasTrial, setHasTrial] = useState(false);
  const [trialDays, setTrialDays] = useState(3);
  const [categoryId, setCategoryId] = useState<number>(categories[0]?.id || 1);
  const [techStacks, setTechStacks] = useState('PHP, Laravel, MySQL');
  const [previewUrl, setPreviewUrl] = useState('');
  const [coverImage, setCoverImage] = useState('');
  const [version, setVersion] = useState('v1.0.0');
  const [fileName, setFileName] = useState('script-release.zip');
  const [fileSize, setFileSize] = useState('5.0 MB');
  const [isSaving, setIsSaving] = useState(false);

  const openAddModal = () => {
    setEditingProduct(null);
    setTitle('');
    setSlug('');
    setShortDesc('');
    setFullDesc('');
    setPrice(9.99);
    setRegularPrice(49.99);
    setIsFree(false);
    setHasTrial(true);
    setTrialDays(3);
    setCategoryId(categories[0]?.id || 1);
    setTechStacks('PHP, MySQL, TailwindCSS');
    setPreviewUrl('https://demo.hostneko.com');
    setCoverImage('https://images.unsplash.com/photo-1555066931-4365d14bab8c?w=800&q=80');
    setVersion('v1.0.0');
    setFileName('script-v1.zip');
    setFileSize('4.5 MB');
    setIsModalOpen(true);
  };

  const openEditModal = (p: Product) => {
    setEditingProduct(p);
    setTitle(p.title);
    setSlug(p.slug);
    setShortDesc(p.short_desc);
    setFullDesc(p.full_desc);
    setPrice(p.price);
    setRegularPrice(p.regular_price || 0);
    setIsFree(p.is_free);
    setHasTrial(p.has_trial);
    setTrialDays(p.trial_days || 3);
    setCategoryId(p.category_id);
    setTechStacks(p.tech_stacks.join(', '));
    setPreviewUrl(p.preview_url || '');
    setCoverImage(p.cover_image);
    setVersion(p.version);
    setFileName(p.file_name || 'script.zip');
    setFileSize(p.file_size || '5.0 MB');
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number | string) => {
    if (!confirm('Are you sure you want to delete this product?')) return;
    try {
      await fetch(`/api/products/${id}`, { method: 'DELETE' });
      setProducts(products.filter((p) => String(p.id) !== String(id)));
    } catch {
      setProducts(products.filter((p) => String(p.id) !== String(id)));
    }
  };

  const handleSaveProduct = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);

    const cat = categories.find((c) => c.id === Number(categoryId));
    const stacks = techStacks.split(',').map((s) => s.trim());

    // Generate plans
    const plans: PlanOption[] = [];
    if (hasTrial) {
      plans.push({
        id: 'plan-trial',
        name: 'Trial Version',
        type: 'trial',
        price: 0,
        billing_period: `${trialDays} days`,
      });
    }

    if (isFree) {
      plans.push({
        id: 'plan-free',
        name: 'Free Edition',
        type: 'onetime',
        price: 0,
        billing_period: 'Lifetime',
      });
    } else {
      plans.push({
        id: 'plan-monthly',
        name: 'Monthly License',
        type: 'monthly',
        price: Number(price),
        regular_price: Number(regularPrice) || undefined,
        billing_period: 'month',
        is_popular: true,
      });
      plans.push({
        id: 'plan-yearly',
        name: 'Yearly License',
        type: 'yearly',
        price: Math.round(Number(price) * 10 * 100) / 100,
        billing_period: 'year',
      });
      plans.push({
        id: 'plan-lifetime',
        name: 'Lifetime License',
        type: 'lifetime',
        price: Math.round(Number(price) * 25 * 100) / 100,
        billing_period: 'Lifetime',
      });
    }

    const payload: Partial<Product> = {
      id: editingProduct?.id,
      title: title.trim(),
      slug: slug.trim() || title.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
      short_desc: shortDesc.trim(),
      full_desc: fullDesc.trim(),
      price: isFree ? 0 : Number(price),
      regular_price: Number(regularPrice) || undefined,
      is_free: isFree,
      has_trial: hasTrial,
      trial_days: Number(trialDays),
      category_id: Number(categoryId),
      category_name: cat?.name || 'Web Scripts',
      tech_stacks: stacks,
      preview_url: previewUrl.trim() || undefined,
      cover_image: coverImage.trim() || 'https://images.unsplash.com/photo-1555066931-4365d14bab8c?w=800&q=80',
      gallery_images: [coverImage],
      version: version.trim() || 'v1.0.0',
      file_name: fileName.trim(),
      file_size: fileSize.trim(),
      plans,
      features: [
        'Instant Automated Key Generation',
        'Multi-domain Whitelisting Support',
        'Complete Unobfuscated Source Code',
      ],
      changelogs: editingProduct?.changelogs || [
        {
          version: version.trim() || 'v1.0.0',
          release_date: new Date().toISOString().split('T')[0],
          title: 'Initial Release',
          changes: ['Production ready release version'],
        },
      ],
      documentation: editingProduct?.documentation || [
        {
          id: 'setup',
          title: 'Quick Installation Guide',
          content: 'Upload the ZIP file to your web server root, create MySQL database and run setup wizard.',
        },
      ],
    };

    try {
      const res = await fetch('/api/products', {
        method: editingProduct ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data.product) {
        if (editingProduct) {
          setProducts(products.map((p) => (p.id === editingProduct.id ? data.product : p)));
        } else {
          setProducts([data.product, ...products]);
        }
        setIsModalOpen(false);
      }
    } catch {
      // Fallback local update
      if (editingProduct) {
        setProducts(products.map((p) => (p.id === editingProduct.id ? ({ ...p, ...payload } as Product) : p)));
      } else {
        const newLocal = { ...payload, id: Date.now() } as Product;
        setProducts([newLocal, ...products]);
      }
      setIsModalOpen(false);
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="py-8 md:py-12 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-7xl">
        <div className="flex flex-col lg:flex-row gap-8 items-start">
          <AdminSidebar />

          <div className="flex-1 space-y-6 w-full">
            {/* Top Toolbar */}
            <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-gray-100 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <h1 className="text-2xl sm:text-3xl font-black text-gray-900">
                  Products & Scripts Catalog ({products.length})
                </h1>
                <p className="text-xs sm:text-sm text-gray-500 mt-1">
                  Manage scripts, WHMCS provisioning modules, Telegram bots, and ZIP file releases.
                </p>
              </div>

              <button
                onClick={openAddModal}
                className="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-xl shadow-md transition flex items-center justify-center gap-2 shrink-0 active:scale-95"
              >
                <Plus className="w-4 h-4" />
                <span>Add New Product</span>
              </button>
            </div>

            {/* Products Table */}
            <div className="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead className="bg-gray-50/80 text-gray-400 font-bold uppercase tracking-wider border-b border-gray-100">
                    <tr>
                      <th className="px-6 py-4">Product Details</th>
                      <th className="px-4 py-4">Category</th>
                      <th className="px-4 py-4">Pricing & Tier</th>
                      <th className="px-4 py-4">Orders</th>
                      <th className="px-4 py-4">Status</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 text-gray-700">
                    {products.map((p) => (
                      <tr key={p.id} className="hover:bg-gray-50/50 transition">
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-3">
                            <div className="w-12 h-12 rounded-xl bg-gray-50 overflow-hidden border border-gray-100 shrink-0">
                              <img src={p.cover_image} alt={p.title} className="w-full h-full object-cover" />
                            </div>
                            <div className="max-w-xs space-y-0.5">
                              <h4 className="font-bold text-sm text-gray-900 truncate">{p.title}</h4>
                              <p className="text-[11px] text-gray-400 font-mono">{p.version} • {p.file_size || 'N/A'}</p>
                            </div>
                          </div>
                        </td>

                        <td className="px-4 py-4">
                          <span className="font-semibold text-gray-700 bg-gray-100 px-2.5 py-1 rounded-md">
                            {p.category_name}
                          </span>
                        </td>

                        <td className="px-4 py-4">
                          {p.is_free ? (
                            <span className="font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded">
                              Free
                            </span>
                          ) : (
                            <div className="space-y-0.5">
                              <span className="font-black text-indigo-600 text-sm">
                                ${p.price.toFixed(2)}
                              </span>
                              {p.has_trial && (
                                <span className="block text-[10px] text-blue-600 font-semibold">
                                  {p.trial_days} Days Trial
                                </span>
                              )}
                            </div>
                          )}
                        </td>

                        <td className="px-4 py-4 font-bold text-gray-800">
                          {p.sales_count || 0} Sold
                        </td>

                        <td className="px-4 py-4">
                          <span className="inline-flex items-center gap-1 text-emerald-600 font-bold">
                            <CheckCircle2 className="w-3.5 h-3.5" /> Active
                          </span>
                        </td>

                        <td className="px-6 py-4 text-right">
                          <div className="flex items-center justify-end gap-2">
                            <Link
                              href={`/product/${p.id}`}
                              target="_blank"
                              className="p-2 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition"
                              title="View on site"
                            >
                              <Eye className="w-4 h-4" />
                            </Link>

                            <button
                              onClick={() => openEditModal(p)}
                              className="p-2 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition"
                              title="Edit product"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>

                            <button
                              onClick={() => handleDelete(p.id)}
                              className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition"
                              title="Delete product"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Add / Edit Product Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setIsModalOpen(false)} />
          <div className="relative w-full max-w-2xl max-h-[90vh] bg-white rounded-3xl shadow-2xl p-6 sm:p-8 space-y-5 z-10 overflow-y-auto animate-fade-in">
            <div className="flex items-center justify-between border-b border-gray-100 pb-3">
              <h3 className="text-xl font-black text-gray-900">
                {editingProduct ? 'Edit Product & Release' : 'Add New Digital Product'}
              </h3>
              <button
                onClick={() => setIsModalOpen(false)}
                className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 text-gray-500 flex items-center justify-center"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleSaveProduct} className="space-y-4 text-xs">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="sm:col-span-2">
                  <label className="block font-bold text-gray-700 mb-1">Product Title *</label>
                  <input
                    type="text"
                    required
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                  />
                </div>

                <div>
                  <label className="block font-bold text-gray-700 mb-1">Category *</label>
                  <select
                    value={categoryId}
                    onChange={(e) => setCategoryId(Number(e.target.value))}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600 font-semibold"
                  >
                    {categories.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block font-bold text-gray-700 mb-1">Release Version</label>
                  <input
                    type="text"
                    placeholder="e.g. v2.4.0"
                    value={version}
                    onChange={(e) => setVersion(e.target.value)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600 font-mono"
                  />
                </div>
              </div>

              {/* Pricing Grid */}
              <div className="p-4 bg-gray-50/80 rounded-2xl border border-gray-100 space-y-3">
                <div className="flex items-center gap-6">
                  <label className="flex items-center gap-2 cursor-pointer font-bold text-gray-700">
                    <input
                      type="checkbox"
                      checked={isFree}
                      onChange={(e) => setIsFree(e.target.checked)}
                      className="rounded text-indigo-600"
                    />
                    <span>100% Free Script</span>
                  </label>

                  <label className="flex items-center gap-2 cursor-pointer font-bold text-gray-700">
                    <input
                      type="checkbox"
                      checked={hasTrial}
                      onChange={(e) => setHasTrial(e.target.checked)}
                      className="rounded text-indigo-600"
                    />
                    <span>Enable Free Trial</span>
                  </label>
                </div>

                {!isFree && (
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 pt-2">
                    <div>
                      <label className="block font-bold text-gray-700 mb-1">Monthly Price ($)</label>
                      <input
                        type="number"
                        step="0.01"
                        required={!isFree}
                        value={price}
                        onChange={(e) => setPrice(parseFloat(e.target.value) || 0)}
                        className="w-full py-2 px-3 bg-white border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-gray-700 mb-1">Regular Price ($)</label>
                      <input
                        type="number"
                        step="0.01"
                        value={regularPrice}
                        onChange={(e) => setRegularPrice(parseFloat(e.target.value) || 0)}
                        className="w-full py-2 px-3 bg-white border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600"
                      />
                    </div>

                    {hasTrial && (
                      <div>
                        <label className="block font-bold text-gray-700 mb-1">Trial Days</label>
                        <input
                          type="number"
                          value={trialDays}
                          onChange={(e) => setTrialDays(parseInt(e.target.value) || 3)}
                          className="w-full py-2 px-3 bg-white border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-600"
                        />
                      </div>
                    )}
                  </div>
                )}
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">Tech Stacks (Comma separated)</label>
                <input
                  type="text"
                  placeholder="PHP, Laravel, Proxmox, TMA"
                  value={techStacks}
                  onChange={(e) => setTechStacks(e.target.value)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block font-bold text-gray-700 mb-1">Cover Image URL</label>
                  <input
                    type="text"
                    value={coverImage}
                    onChange={(e) => setCoverImage(e.target.value)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                  />
                </div>

                <div>
                  <label className="block font-bold text-gray-700 mb-1">Live Demo / Preview URL</label>
                  <input
                    type="text"
                    value={previewUrl}
                    onChange={(e) => setPreviewUrl(e.target.value)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                  />
                </div>
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">Short Summary *</label>
                <textarea
                  rows={2}
                  required
                  value={shortDesc}
                  onChange={(e) => setShortDesc(e.target.value)}
                  className="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">Full Specifications & Features</label>
                <textarea
                  rows={5}
                  value={fullDesc}
                  onChange={(e) => setFullDesc(e.target.value)}
                  className="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
              </div>

              <div className="flex justify-end gap-3 pt-3 border-t border-gray-100">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-xl"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSaving}
                  className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl shadow-md transition flex items-center gap-1.5"
                >
                  <Save className="w-4 h-4" />
                  {isSaving ? 'Saving...' : 'Save Product'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
