import React, { useState, useEffect } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/react';
import { Save, Plus, Trash2 } from 'lucide-react';
import AdminLayout from '../../components/AdminLayout';

interface Plan {
  id: number;
  name: string;
  slug: string;
  stripe_product_id: string;
  stripe_price_id: string | null;
  price_cents: number;
  currency: string;
  billing_interval: string;
  features: any;
  query_limit: number | null;
  file_upload_limit: number | null;
  message_limit: number | null;
  is_active: boolean;
  sort_order: number;
}

export default function AdminPackages() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [plans, setPlans] = useState<Plan[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    try {
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'dark') setDarkMode(true);
    } catch {}
  }, []);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
    }
  }, [status, router]);

  useEffect(() => {
    if (status === 'authenticated') {
      loadPlans();
    }
  }, [status]);

  async function loadPlans() {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/packages');
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      setPlans(data.plans || []);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  async function savePlan(plan: Plan) {
    setSaving(true);
    try {
      const res = await fetch('/api/admin/packages', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(plan),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      await loadPlans();
      alert('Plan saved successfully!');
    } catch (err: any) {
      alert('Error saving plan: ' + err.message);
    } finally {
      setSaving(false);
    }
  }

  function updatePlan(id: number, field: string, value: any) {
    setPlans(plans.map(p => p.id === id ? { ...p, [field]: value } : p));
  }

  const theme = {
    bg: darkMode ? '#1a1a2e' : '#f8fafc',
    cardBg: darkMode ? '#16213e' : '#ffffff',
    text: darkMode ? '#e2e8f0' : '#1e293b',
    textSecondary: darkMode ? '#94a3b8' : '#64748b',
    border: darkMode ? '#2d3748' : '#e2e8f0',
    inputBg: darkMode ? '#1f2937' : '#ffffff',
  };

  const S: Record<string, React.CSSProperties> = {
    grid: {
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
      gap: 20,
      width: '100%',
    },
    card: {
      background: theme.cardBg,
      borderRadius: 12,
      border: `1px solid ${theme.border}`,
      padding: 20,
    },
    cardHeader: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 16,
    },
    planName: {
      fontSize: 18,
      fontWeight: 600,
      color: theme.text,
    },
    badge: {
      padding: '4px 8px',
      borderRadius: 4,
      fontSize: 12,
      fontWeight: 500,
    },
    field: {
      marginBottom: 12,
    },
    label: {
      display: 'block',
      fontSize: 12,
      fontWeight: 500,
      color: theme.textSecondary,
      marginBottom: 4,
    },
    input: {
      width: '100%',
      padding: '8px 12px',
      borderRadius: 6,
      border: `1px solid ${theme.border}`,
      background: theme.inputBg,
      color: theme.text,
      fontSize: 14,
      boxSizing: 'border-box' as const,
    },
    row: {
      display: 'flex',
      gap: 12,
    },
    saveBtn: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 8,
      width: '100%',
      padding: '10px 16px',
      borderRadius: 8,
      border: 'none',
      background: 'linear-gradient(90deg, #2563eb, #7c3aed)',
      color: '#fff',
      fontSize: 14,
      fontWeight: 500,
      cursor: 'pointer',
      marginTop: 16,
    },
  };

  if (status === 'loading' || loading) {
    return (
      <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="packages">
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh', color: theme.textSecondary }}>
          Loading...
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="packages">
      <Head>
        <title>Manage Packages - Admin - Gregory AI</title>
      </Head>

      {error && (
        <div style={{ padding: 16, background: '#fee2e2', color: '#dc2626', borderRadius: 8, marginBottom: 24 }}>
          {error}
        </div>
      )}

      <div style={S.grid}>
        {plans.map((plan) => (
          <div key={plan.id} style={S.card}>
            <div style={S.cardHeader}>
              <div style={S.planName}>{plan.name}</div>
              <span style={{
                ...S.badge,
                background: plan.is_active ? '#dcfce7' : '#fee2e2',
                color: plan.is_active ? '#16a34a' : '#dc2626',
              }}>
                {plan.is_active ? 'Active' : 'Inactive'}
              </span>
            </div>

            <div style={S.field}>
              <label style={S.label}>Name</label>
              <input
                style={S.input}
                value={plan.name}
                onChange={(e) => updatePlan(plan.id, 'name', e.target.value)}
              />
            </div>

            <div style={S.row}>
              <div style={{ ...S.field, flex: 1 }}>
                <label style={S.label}>Price (cents)</label>
                <input
                  style={S.input}
                  type="number"
                  value={plan.price_cents}
                  onChange={(e) => updatePlan(plan.id, 'price_cents', parseInt(e.target.value) || 0)}
                />
              </div>
              <div style={{ ...S.field, flex: 1 }}>
                <label style={S.label}>Interval</label>
                <select
                  style={S.input}
                  value={plan.billing_interval}
                  onChange={(e) => updatePlan(plan.id, 'billing_interval', e.target.value)}
                >
                  <option value="month">Monthly</option>
                  <option value="year">Yearly</option>
                </select>
              </div>
            </div>

            <div style={S.row}>
              <div style={{ ...S.field, flex: 1 }}>
                <label style={S.label}>Messages/Day</label>
                <input
                  style={S.input}
                  type="number"
                  placeholder="Unlimited"
                  value={plan.query_limit ?? ''}
                  onChange={(e) => {
                    const val = e.target.value ? parseInt(e.target.value) : null;
                    updatePlan(plan.id, 'query_limit', val);
                    updatePlan(plan.id, 'message_limit', val);
                  }}
                />
              </div>
              <div style={{ ...S.field, flex: 1 }}>
                <label style={S.label}>File Uploads/Day</label>
                <input
                  style={S.input}
                  type="number"
                  placeholder="Unlimited"
                  value={plan.file_upload_limit ?? ''}
                  onChange={(e) => updatePlan(plan.id, 'file_upload_limit', e.target.value ? parseInt(e.target.value) : null)}
                />
              </div>
            </div>

            <div style={S.field}>
              <label style={S.label}>Stripe Product ID</label>
              <input
                style={S.input}
                value={plan.stripe_product_id || ''}
                onChange={(e) => updatePlan(plan.id, 'stripe_product_id', e.target.value)}
                placeholder="prod_xxx"
              />
            </div>

            <div style={S.field}>
              <label style={{ ...S.label, display: 'flex', alignItems: 'center', gap: 8 }}>
                <input
                  type="checkbox"
                  checked={plan.is_active}
                  onChange={(e) => updatePlan(plan.id, 'is_active', e.target.checked)}
                />
                Active
              </label>
            </div>

            <button
              style={S.saveBtn}
              onClick={() => savePlan(plan)}
              disabled={saving}
            >
              <Save size={16} />
              {saving ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        ))}
      </div>
    </AdminLayout>
  );
}
