import { useState } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { ArrowLeft, Plus, Trash2, Save, LogOut, LayoutDashboard, Package, BarChart3, Settings } from 'lucide-react';
import { useApp } from '../context/AppContext';
import type { Product } from '../context/AppContext';

const EMPTY_PRODUCT: Omit<Product, 'id'> = {
  name: '',
  slug: '',
  category: 'design-tools',
  subcategory: 'Design Tools',
  badge: '',
  image: '',
  shortDesc: '',
  description: '',
  features: [''],
  benefits: [''],
  plans: [''],
  activation: '',
  deliveryTime: '2-5 minutes',
  faqs: [{ question: '', answer: '' }],
  reviews: [{ name: '', location: '', rating: 5, text: '', verified: true }],
  metaTitle: '',
  metaDesc: '',
  h1: '',
};

const badgeOptions = ['', 'Best Seller', 'Trending', 'Premium', 'Value Pack', 'Sale', 'Lifetime'];
const categoryOptions = [
  { id: 'design-tools', name: 'Design Tools' },
  { id: 'ai-tools', name: 'AI Tools' },
  { id: 'video-audio', name: 'Video & Audio' },
  { id: 'creative-assets', name: 'Creative Assets' },
  { id: 'streaming', name: 'Streaming & OTT' },
  { id: 'productivity', name: 'Productivity' },
  { id: 'security', name: 'Security & VPN' },
  { id: 'developer', name: 'Developer Tools' },
  { id: 'microsoft', name: 'Microsoft' },
  { id: 'learning', name: 'Learning & Education' },
];

function StringArrayField({ label, values, onChange }: { label: string; values: string[]; onChange: (v: string[]) => void }) {
  return (
    <div className="space-y-2">
      <p className="text-text-secondary text-sm font-medium">{label}</p>
      {values.map((val, i) => (
        <div key={i} className="flex gap-2">
          <input
            type="text"
            value={val}
            onChange={(e) => {
              const next = [...values];
              next[i] = e.target.value;
              onChange(next);
            }}
            className="flex-1 bg-bg-input border border-bg-border rounded-xl py-2 px-3 text-sm text-white placeholder:text-text-muted focus:outline-none focus:border-accent-yellow"
            aria-label={`${label} item ${i + 1}`}
            placeholder={`Item ${i + 1}`}
          />
          <button
            type="button"
            onClick={() => onChange(values.filter((_, idx) => idx !== i))}
            className="w-9 h-9 rounded-lg bg-bg-tertiary flex items-center justify-center hover:bg-error/10 hover:text-error transition-colors text-text-secondary shrink-0"
          >
            <Trash2 size={14} />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={() => onChange([...values, ''])}
        className="text-accent-yellow text-xs font-semibold hover:underline flex items-center gap-1"
      >
        <Plus size={14} /> Add item
      </button>
    </div>
  );
}

// AdminSidebar component
function AdminSidebar() {
  const { adminLogout } = useApp();
  const navigate = useNavigate();
  const location = useLocation();

  const navItems = [
    { path: '/admin/dashboard', label: 'Dashboard', icon: LayoutDashboard },
    { path: '/admin/products', label: 'Products', icon: Package },
    { path: '/admin/analytics', label: 'Analytics', icon: BarChart3 },
    { path: '/admin/settings', label: 'Settings', icon: Settings },
  ];

  return (
    <div className="fixed left-0 top-0 bottom-0 w-64 bg-[#111111] border-r border-[#2A2A2A] hidden lg:flex flex-col z-50">
      <div className="p-6 border-b border-[#2A2A2A]">
        <Link to="/" className="flex items-center gap-0">
          <span className="text-lg font-bold text-white">MFA</span>
          <span className="text-lg font-bold text-accent-lime">Tools</span>
          <span className="text-lg font-extrabold text-accent-yellow">Net</span>
        </Link>
        <p className="text-text-tertiary text-xs mt-1">Admin Panel</p>
      </div>
      <nav className="flex-1 p-4 space-y-1">
        {navItems.map((item) => {
          const isActive = location.pathname === item.path || (item.path === '/admin/products' && location.pathname.startsWith('/admin/products'));
          return (
            <Link
              key={item.path}
              to={item.path}
              className={`flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-colors ${
                isActive
                  ? 'text-white bg-[#1A1A1A]'
                  : 'text-text-secondary hover:text-white hover:bg-[#1A1A1A]'
              }`}
            >
              <item.icon size={18} /> {item.label}
            </Link>
          );
        })}
      </nav>
      <div className="p-4 border-t border-[#2A2A2A]">
        <button
          onClick={() => { adminLogout(); navigate('/admin/login'); }}
          className="flex items-center gap-3 text-error hover:bg-error/10 px-4 py-3 rounded-xl text-sm font-medium transition-colors w-full"
        >
          <LogOut size={18} /> Logout
        </button>
      </div>
    </div>
  );
}

export default function AdminAddProduct() {
  const { t, addProduct, isAdmin } = useApp();
  const navigate = useNavigate();
  const [form, setForm] = useState(EMPTY_PRODUCT);
  const [saving, setSaving] = useState(false);

  if (!isAdmin) {
    navigate('/admin/login');
    return null;
  }

  const update = (k: keyof typeof form, v: unknown) => setForm(prev => ({ ...prev, [k]: v }));

  const handleSave = () => {
    if (!form.name || !form.slug) return;
    setSaving(true);
    const newId = Date.now().toString();
    const product: Product = {
      ...form,
      id: newId,
    };
    addProduct(product);
    setTimeout(() => {
      setSaving(false);
      navigate('/admin/products');
    }, 500);
  };

  return (
    <div className="min-h-screen bg-bg-primary text-text-primary">
      <AdminSidebar />
      <div className="lg:ml-64">
        <div className="p-6 lg:p-10 max-w-4xl mx-auto">
          <div className="flex items-center justify-between mb-8">
            <div className="flex items-center gap-3">
              <Link to="/admin/products" className="text-text-tertiary hover:text-white transition-colors"><ArrowLeft size={20} /></Link>
              <h1 className="text-2xl font-bold text-white">{t('addProduct')}</h1>
            </div>
          </div>

          <div className="bg-bg-secondary border border-bg-border rounded-2xl p-6 lg:p-8 space-y-6">
            {/* Basic Info */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-name">{t('name')}</label>
          <input type="text" value={form.name} onChange={(e) => update('name', e.target.value)} id="t-name" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-slug">{t('slug')}</label>
          <input type="text" value={form.slug} onChange={(e) => update('slug', e.target.value)} id="t-slug" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" placeholder="kanva-pro" />
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-category">{t('category')}</label>
          <select value={form.category} onChange={(e) => update('category', e.target.value)} id="t-category" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow">
                  {categoryOptions.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-subcategory">{t('subcategory')}</label>
          <input type="text" value={form.subcategory} onChange={(e) => update('subcategory', e.target.value)} id="t-subcategory" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-badge">{t('badge')}</label>
          <select value={form.badge} onChange={(e) => update('badge', e.target.value)} id="t-badge" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow">
                  {badgeOptions.map(b => <option key={b || 'none'} value={b}>{b || 'None'}</option>)}
                </select>
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-deliverytimelabel">{t('deliveryTimeLabel')}</label>
          <input type="text" value={form.deliveryTime} onChange={(e) => update('deliveryTime', e.target.value)} id="t-deliverytimelabel" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="meta-title">Meta Title</label>
          <input type="text" value={form.metaTitle} onChange={(e) => update('metaTitle', e.target.value)} id="meta-title" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="h1-heading">H1 Heading</label>
          <input type="text" value={form.h1} onChange={(e) => update('h1', e.target.value)} id="h1-heading" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
              </div>
              <div>
                <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="image-url">Image URL</label>
          <input type="text" value={form.image} onChange={(e) => update('image', e.target.value)} id="image-url" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" placeholder="/product-name.jpg" />
              </div>
            </div>

            {/* Descriptions */}
            <div>
              <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-shortdesc">{t('shortDesc')}</label>
          <input type="text" value={form.shortDesc} onChange={(e) => update('shortDesc', e.target.value)} id="t-shortdesc" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
            </div>
            <div>
              <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-fulldescription">{t('fullDescription')}</label>
          <textarea value={form.description} onChange={(e) => update('description', e.target.value)} id="t-fulldescription" rows={4} className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
            </div>
            <div>
              <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="meta-description">Meta Description</label>
          <textarea value={form.metaDesc} onChange={(e) => update('metaDesc', e.target.value)} id="meta-description" rows={2} className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
            </div>

            {/* Arrays */}
            <StringArrayField label={t('featureList')} values={form.features} onChange={(v) => update('features', v)} />
            <StringArrayField label={t('benefitList')} values={form.benefits} onChange={(v) => update('benefits', v)} />
            <StringArrayField label={t('planList')} values={form.plans} onChange={(v) => update('plans', v)} />

            <div>
              <label className="text-text-secondary text-sm font-medium block mb-1.5" htmlFor="t-activationmethod">{t('activationMethod')}</label>
          <input type="text" value={form.activation} onChange={(e) => update('activation', e.target.value)} id="t-activationmethod" className="w-full bg-bg-input border border-bg-border rounded-xl py-2.5 px-4 text-sm text-white focus:outline-none focus:border-accent-yellow" />
            </div>

            {/* FAQs */}
            <div className="space-y-3">
              <label className="text-text-secondary text-sm font-medium block">{t('faqList')}</label>
              {form.faqs.map((faq, i) => (
                <div key={i} className="bg-bg-tertiary border border-bg-border rounded-xl p-4 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-text-tertiary font-medium">FAQ {i + 1}</span>
                    <button type="button" onClick={() => update('faqs', form.faqs.filter((_, idx) => idx !== i))} className="text-error hover:text-red-400 transition-colors"><Trash2 size={14} /></button>
                  </div>
                  <input type="text" value={faq.question} onChange={(e) => { const next = [...form.faqs]; next[i] = { ...next[i], question: e.target.value }; update('faqs', next); }} placeholder="Question" className="w-full bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow" />
                  <textarea value={faq.answer} onChange={(e) => { const next = [...form.faqs]; next[i] = { ...next[i], answer: e.target.value }; update('faqs', next); }} placeholder="Answer" rows={2} className="w-full bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow" />
                </div>
              ))}
              <button type="button" onClick={() => update('faqs', [...form.faqs, { question: '', answer: '' }])} className="text-accent-yellow text-xs font-semibold hover:underline flex items-center gap-1"><Plus size={14} /> Add FAQ</button>
            </div>

            {/* Reviews */}
            <div className="space-y-3">
              <label className="text-text-secondary text-sm font-medium block">{t('reviewList')}</label>
              {form.reviews.map((review, i) => (
                <div key={i} className="bg-bg-tertiary border border-bg-border rounded-xl p-4 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-text-tertiary font-medium">Review {i + 1}</span>
                    <button type="button" onClick={() => update('reviews', form.reviews.filter((_, idx) => idx !== i))} className="text-error hover:text-red-400 transition-colors"><Trash2 size={14} /></button>
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <input type="text" value={review.name} onChange={(e) => { const next = [...form.reviews]; next[i] = { ...next[i], name: e.target.value }; update('reviews', next); }} placeholder="Name" className="bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow" />
                    <input type="text" value={review.location} onChange={(e) => { const next = [...form.reviews]; next[i] = { ...next[i], location: e.target.value }; update('reviews', next); }} placeholder="Location" className="bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow" />
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <input type="number" min={1} max={5} value={review.rating} onChange={(e) => { const next = [...form.reviews]; next[i] = { ...next[i], rating: Number(e.target.value) }; update('reviews', next); }} className="bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow" />
                    <select value={review.verified ? 'true' : 'false'} onChange={(e) => { const next = [...form.reviews]; next[i] = { ...next[i], verified: e.target.value === 'true' }; update('reviews', next); }} className="bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow">
                      <option value="true">Verified</option>
                      <option value="false">Not Verified</option>
                    </select>
                  </div>
                  <textarea value={review.text} onChange={(e) => { const next = [...form.reviews]; next[i] = { ...next[i], text: e.target.value }; update('reviews', next); }} placeholder="Review text" rows={2} className="w-full bg-bg-input border border-bg-border rounded-lg py-2 px-3 text-sm text-white focus:outline-none focus:border-accent-yellow" />
                </div>
              ))}
              <button type="button" onClick={() => update('reviews', [...form.reviews, { name: '', location: '', rating: 5, text: '', verified: true }])} className="text-accent-yellow text-xs font-semibold hover:underline flex items-center gap-1"><Plus size={14} /> Add Review</button>
            </div>

            {/* Save */}
            <div className="flex gap-3 pt-4 border-t border-bg-border">
              <button
                onClick={handleSave}
                disabled={saving}
                className="flex-1 bg-accent-yellow text-bg-primary font-semibold py-3 rounded-xl hover:bg-accent-yellow-dark transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
              >
                <Save size={18} /> {saving ? t('loading') : t('save')}
              </button>
              <Link to="/admin/products" className="flex-1 bg-bg-tertiary border border-bg-border text-white font-semibold py-3 rounded-xl hover:bg-bg-border transition-colors text-center">
                {t('cancel')}
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
