/**
 * Admin Credit Packages Page
 * Manage credit packages available for purchase
 */

import { useState, useEffect } from 'react';
import { Plus, Loader2, AlertCircle, Edit, Trash } from 'lucide-react';
import { Card } from '../../components/ui/card';
import Badge from '../../components/ui/badge/Badge';
import { useToast } from '../../components/ui/toast/ToastContainer';
import {
  getAdminCreditPackages,
  createAdminCreditPackage,
  updateAdminCreditPackage,
  deleteAdminCreditPackage,
  type CreditPackage,
} from '../../services/billing.api';

export default function AdminCreditPackagesPage() {
  const toast = useToast();
  const [packages, setPackages] = useState<CreditPackage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form, setForm] = useState({
    name: '',
    credits: '',
    price: '',
    discount_percentage: '',
    description: '',
    is_active: true,
    is_featured: false,
    sort_order: '',
  });

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

  const loadPackages = async () => {
    try {
      setLoading(true);
      const data = await getAdminCreditPackages();
      setPackages(data.results || []);
    } catch (err: any) {
      setError(err.message || 'Failed to load credit packages');
      toast?.error?.(err.message || 'Failed to load credit packages');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setEditingId(null);
    setForm({
      name: '',
      credits: '',
      price: '',
      discount_percentage: '',
      description: '',
      is_active: true,
      is_featured: false,
      sort_order: '',
    });
  };

  const startEdit = (pkg: CreditPackage) => {
    setEditingId(pkg.id);
    setForm({
      name: pkg.name || '',
      credits: pkg.credits?.toString?.() || '',
      price: pkg.price?.toString?.() || '',
      discount_percentage: pkg.discount_percentage?.toString?.() || '',
      description: pkg.description || '',
      is_active: pkg.is_active ?? true,
      is_featured: pkg.is_featured ?? false,
      sort_order: (pkg.sort_order ?? pkg.display_order ?? '').toString(),
    });
  };

  const handleSubmit = async () => {
    if (!form.name.trim() || !form.credits || !form.price) {
      setError('Name, credits, and price are required');
      return;
    }
    try {
      setSaving(true);
      const payload = {
        name: form.name,
        credits: Number(form.credits),
        price: form.price,
        discount_percentage: form.discount_percentage ? Number(form.discount_percentage) : 0,
        description: form.description || undefined,
        is_active: form.is_active,
        is_featured: form.is_featured,
        sort_order: form.sort_order ? Number(form.sort_order) : undefined,
      };
      if (editingId) {
        await updateAdminCreditPackage(editingId, payload);
        toast?.success?.('Package updated');
      } else {
        await createAdminCreditPackage(payload);
        toast?.success?.('Package created');
      }
      resetForm();
      await loadPackages();
    } catch (err: any) {
      setError(err.message || 'Failed to save package');
      toast?.error?.(err.message || 'Failed to save package');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Delete this credit package?')) return;
    try {
      await deleteAdminCreditPackage(id);
      toast?.success?.('Package deleted');
      await loadPackages();
    } catch (err: any) {
      setError(err.message || 'Failed to delete package');
      toast?.error?.(err.message || 'Failed to delete package');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  return (
    <div className="p-6">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Credit Packages</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Manage credit packages available for purchase
          </p>
        </div>
      </div>

      {/* Form */}
      <Card className="p-4 mb-6">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <Plus className="w-4 h-4 text-blue-600" />
            <h2 className="text-lg font-semibold">{editingId ? 'Edit Package' : 'Add Package'}</h2>
          </div>
          {editingId && (
            <button
              className="text-sm text-blue-600 hover:underline"
              onClick={resetForm}
            >
              Cancel edit
            </button>
          )}
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name</label>
            <input
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
              value={form.name}
              onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
              placeholder="Starter Pack"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Credits</label>
            <input
              type="number"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
              value={form.credits}
              onChange={(e) => setForm((p) => ({ ...p, credits: e.target.value }))}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Price</label>
            <input
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
              value={form.price}
              onChange={(e) => setForm((p) => ({ ...p, price: e.target.value }))}
              placeholder="99.00"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Discount %</label>
            <input
              type="number"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
              value={form.discount_percentage}
              onChange={(e) => setForm((p) => ({ ...p, discount_percentage: e.target.value }))}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Sort Order</label>
            <input
              type="number"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
              value={form.sort_order}
              onChange={(e) => setForm((p) => ({ ...p, sort_order: e.target.value }))}
              placeholder="e.g., 1"
            />
          </div>
          <div className="md:col-span-3">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Description</label>
            <textarea
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
              value={form.description}
              onChange={(e) => setForm((p) => ({ ...p, description: e.target.value }))}
              placeholder="Optional description"
            />
          </div>
          <div className="flex items-center gap-3">
            <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
              <input
                type="checkbox"
                checked={form.is_active}
                onChange={(e) => setForm((p) => ({ ...p, is_active: e.target.checked }))}
              />
              Active
            </label>
            <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
              <input
                type="checkbox"
                checked={form.is_featured}
                onChange={(e) => setForm((p) => ({ ...p, is_featured: e.target.checked }))}
              />
              Featured
            </label>
          </div>
        </div>
        <div className="mt-4 flex justify-end gap-2">
          <button
            className="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800"
            onClick={resetForm}
          >
            Reset
          </button>
          <button
            className="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-60"
            onClick={handleSubmit}
            disabled={saving}
          >
            {saving ? 'Saving...' : editingId ? 'Update Package' : 'Create Package'}
          </button>
        </div>
      </Card>

      {error && (
        <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5 text-red-600" />
          <p className="text-red-800 dark:text-red-200">{error}</p>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {packages.map((pkg) => (
          <Card key={pkg.id} className="p-6">
            <div className="flex items-start justify-between mb-4">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">{pkg.name}</h3>
                {pkg.is_featured && (
                  <Badge variant="light" color="primary" className="mt-1">Featured</Badge>
                )}
              </div>
              <Badge variant="light" color={pkg.is_active ? 'success' : 'error'}>
                {pkg.is_active ? 'Active' : 'Inactive'}
              </Badge>
            </div>
            
            <div className="mb-4">
              <div className="text-3xl font-bold text-blue-600">{pkg.credits.toLocaleString()}</div>
              <div className="text-sm text-gray-500">credits</div>
            </div>
            
            <div className="mb-4">
              <div className="text-2xl font-semibold text-gray-900 dark:text-white">${pkg.price}</div>
              {pkg.discount_percentage > 0 && (
                <div className="text-sm text-green-600">Save {pkg.discount_percentage}%</div>
              )}
            </div>

            {pkg.description && (
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{pkg.description}</p>
            )}

            <div className="flex gap-2 mt-4">
              <button
                className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800"
                onClick={() => startEdit(pkg)}
              >
                <Edit className="w-4 h-4" />
                Edit
              </button>
              <button
                className="px-3 py-2 border border-red-300 dark:border-red-600 text-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20"
                onClick={() => handleDelete(pkg.id)}
              >
                <Trash className="w-4 h-4" />
              </button>
            </div>
          </Card>
        ))}

        {packages.length === 0 && (
          <div className="col-span-3 text-center py-12 text-gray-500">
            No credit packages configured. Click "Add Package" to create one.
          </div>
        )}
      </div>
    </div>
  );
}
