'use client';

import { useState, useEffect, useCallback, use } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Save, ToggleLeft, ToggleRight, Check, DollarSign, Loader2, AlertCircle } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { getAdminBillingPlan, createAdminBillingPlan, updateAdminBillingPlan } from '@client/api/admin';
import { toast } from 'sonner';

function getAllFeatures(t: (k: string, f: string) => string) {
  return [
    { key: 'voice_agent', label: t('billing.features.voiceAgent', 'Voice Agent'), desc: t('billing.features.voiceAgentDesc', 'AI-powered phone call handling') },
    { key: 'chat_agent', label: t('billing.features.chatAgent', 'Chat Agent'), desc: t('billing.features.chatAgentDesc', 'Web chat and messaging') },
    { key: 'multi_branch', label: t('billing.features.multiBranch', 'Multi-Branch'), desc: t('billing.features.multiBranchDesc', 'Multiple location support') },
    { key: 'analytics', label: t('billing.features.analytics', 'Advanced Analytics'), desc: t('billing.features.analyticsDesc', 'Detailed reports and insights') },
    { key: 'knowledge_base', label: t('billing.features.knowledgeBase', 'Knowledge Base'), desc: t('billing.features.knowledgeBaseDesc', 'Custom AI knowledge sources') },
    { key: 'bulk_upload', label: t('billing.features.bulkUpload', 'Bulk Menu Upload'), desc: t('billing.features.bulkUploadDesc', 'AI-powered menu import') },
    { key: 'priority_support', label: t('billing.features.prioritySupport', 'Priority Support'), desc: t('billing.features.prioritySupportDesc', '24/7 dedicated support') },
  ];
}

const DEFAULT_FORM = {
  name: '',
  description: '',
  priceMonthly: '',
  priceAnnual: '',
  trialDays: '14',
  active: true,
  features: [] as string[],
  limits: {
    conversations_per_month: '',
    api_calls_per_minute: '',
    concurrent_voice_calls: '',
    max_branches: '',
  },
};

type FormType = typeof DEFAULT_FORM;

export default function PlanFormPage({ params }: { params: Promise<{ id?: string }> }) {
  const { t } = useLanguage();
  const router = useRouter();
  const resolvedParams = use(params);
  const planId = resolvedParams?.id;
  const isNew = !planId || planId === 'new';
  const allFeatures = getAllFeatures(t);

  usePageHeader(
    isNew ? t('billing.addPlan', 'Add Plan') : t('billing.editPlan', 'Edit Plan'),
    t('billing.planDescription', 'Configure subscription plan details and features')
  );

  const [form, setForm] = useState<FormType>(DEFAULT_FORM);
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);
  const [stripeSkippedWarning, setStripeSkippedWarning] = useState(false);

  useEffect(() => {
    if (isNew) return;
    getAdminBillingPlan(planId!)
      .then((res: { plan: {
        name: string; description: string; priceMonthly: number; priceAnnual: number;
        trialDays: number; isActive: boolean; features: string[];
        limits: Record<string, unknown>;
      } }) => {
        const p = res.plan;
        const lim = p.limits ?? {};
        setForm({
          name: p.name ?? '',
          description: p.description ?? '',
          priceMonthly: p.priceMonthly > 0 ? String(p.priceMonthly) : '',
          priceAnnual: p.priceAnnual > 0 ? String(p.priceAnnual) : '',
          trialDays: String(p.trialDays ?? 14),
          active: p.isActive !== false,
          features: Array.isArray(p.features) ? p.features : [],
          limits: {
            conversations_per_month: lim.conversations_per_month != null ? String(lim.conversations_per_month) : '',
            api_calls_per_minute: lim.api_calls_per_minute != null ? String(lim.api_calls_per_minute) : '',
            concurrent_voice_calls: lim.concurrent_voice_calls != null ? String(lim.concurrent_voice_calls) : '',
            max_branches: lim.max_branches != null ? String(lim.max_branches) : '',
          },
        });
      })
      .catch(() => toast.error('Failed to load plan'))
      .finally(() => setLoading(false));
  }, [isNew, planId]);

  const toggleFeature = useCallback((key: string) => {
    setForm(f => ({
      ...f,
      features: f.features.includes(key) ? f.features.filter(k => k !== key) : [...f.features, key],
    }));
  }, []);

  const buildLimits = useCallback((lim: typeof DEFAULT_FORM.limits) => {
    const result: Record<string, number> = {};
    if (lim.conversations_per_month !== '') result.conversations_per_month = parseInt(lim.conversations_per_month, 10) || 0;
    if (lim.api_calls_per_minute !== '') result.api_calls_per_minute = parseInt(lim.api_calls_per_minute, 10) || 0;
    if (lim.concurrent_voice_calls !== '') result.concurrent_voice_calls = parseInt(lim.concurrent_voice_calls, 10) || 0;
    if (lim.max_branches !== '') result.max_branches = parseInt(lim.max_branches, 10) || 0;
    return result;
  }, []);

  const handleSave = useCallback(async () => {
    if (!form.name.trim()) { toast.error('Plan name is required'); return; }
    if (!form.priceMonthly && parseFloat(form.priceMonthly) !== 0) { toast.error('Monthly price is required'); return; }

    setSaving(true);
    setStripeSkippedWarning(false);
    const payload = {
      name: form.name.trim(),
      description: form.description.trim(),
      priceMonthly: parseFloat(form.priceMonthly) || 0,
      priceAnnual: parseFloat(form.priceAnnual) || 0,
      trialDays: parseInt(form.trialDays, 10) || 14,
      isActive: form.active,
      features: form.features,
      limits: buildLimits(form.limits),
    };

    try {
      const res: { stripeSkipped?: boolean } = isNew
        ? await createAdminBillingPlan(payload)
        : await updateAdminBillingPlan(planId!, payload);

      if (res.stripeSkipped) {
        setStripeSkippedWarning(true);
        toast.success(`Plan ${isNew ? 'created' : 'saved'} (Stripe not configured — price not synced)`);
      } else {
        toast.success(`Plan ${isNew ? 'created' : 'saved'} and synced with Stripe`);
      }
      router.push('/admin/billing');
    } catch {
      toast.error(`Failed to ${isNew ? 'create' : 'save'} plan`);
    }
    setSaving(false);
  }, [form, isNew, planId, buildLimits, router]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="animate-spin" size={32} />
      </div>
    );
  }

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Link href="/admin/billing" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>
          {isNew ? t('billing.addNewPlan', 'Add New Plan') : t('billing.editPlan', 'Edit Plan')}
        </h2>
        <div className="ml-auto flex gap-2">
          <Link href="/admin/billing" className="btn-secondary">{t('common.cancel', 'Cancel')}</Link>
          <button className="btn-primary" onClick={handleSave} disabled={saving}>
            {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
            {isNew ? t('billing.createPlan', 'Create Plan') : t('billing.saveChanges', 'Save Changes')}
          </button>
        </div>
      </div>

      {stripeSkippedWarning && (
        <div className="flex items-center gap-2 p-3 rounded-lg mb-5 text-sm" style={{ backgroundColor: 'hsl(var(--warning) / 0.1)', color: 'hsl(var(--warning))' }}>
          <AlertCircle size={15} />
          Stripe is not configured — plan saved to DB only. Set STRIPE_SECRET_KEY to enable price syncing.
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.planDetails', 'Plan Details')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('billing.planName', 'Plan Name')} *</label>
                <input className="input-base" placeholder="e.g. Starter, Growth, Enterprise" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Description</label>
                <input className="input-base" placeholder="Short plan description" value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('billing.priceUsd', 'Monthly Price (USD)')} *</label>
                <div className="relative">
                  <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input type="number" min="0" step="0.01" className="input-base pl-9" placeholder="49" value={form.priceMonthly} onChange={e => setForm(f => ({ ...f, priceMonthly: e.target.value }))} required />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Annual Price (USD) <span className="font-normal opacity-60">optional</span></label>
                <div className="relative">
                  <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input type="number" min="0" step="0.01" className="input-base pl-9" placeholder="490 (save ~17%)" value={form.priceAnnual} onChange={e => setForm(f => ({ ...f, priceAnnual: e.target.value }))} />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Trial Days</label>
                <input type="number" min="0" max="365" className="input-base" placeholder="14" value={form.trialDays} onChange={e => setForm(f => ({ ...f, trialDays: e.target.value }))} />
              </div>
            </div>
          </div>

          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>Rate Limits <span className="text-xs font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>(leave blank = unlimited)</span></h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                { key: 'conversations_per_month' as const, label: 'Conversations / month', placeholder: 'e.g. 500' },
                { key: 'api_calls_per_minute' as const, label: 'API calls / minute', placeholder: 'e.g. 60' },
                { key: 'concurrent_voice_calls' as const, label: 'Concurrent voice calls', placeholder: 'e.g. 5' },
                { key: 'max_branches' as const, label: 'Max branches', placeholder: 'e.g. 3' },
              ].map(limit => (
                <div key={limit.key}>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{limit.label}</label>
                  <input
                    type="number"
                    min="0"
                    className="input-base"
                    placeholder={limit.placeholder}
                    value={form.limits[limit.key]}
                    onChange={e => setForm(f => ({ ...f, limits: { ...f.limits, [limit.key]: e.target.value } }))}
                  />
                </div>
              ))}
            </div>
          </div>

          <div className="card p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.featuresIncluded', 'Features Included')}</h3>
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{form.features.length} of {allFeatures.length} enabled</span>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {allFeatures.map(feat => {
                const enabled = form.features.includes(feat.key);
                return (
                  <div
                    key={feat.key}
                    className="flex items-center justify-between p-3 rounded-xl border cursor-pointer transition-all"
                    style={{
                      borderColor: enabled ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                      backgroundColor: enabled ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                    }}
                    onClick={() => toggleFeature(feat.key)}
                  >
                    <div>
                      <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{feat.label}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{feat.desc}</p>
                    </div>
                    <div className="w-5 h-5 rounded border-2 flex items-center justify-center shrink-0"
                      style={{ borderColor: enabled ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: enabled ? 'hsl(var(--primary))' : 'transparent' }}>
                      {enabled && <Check size={10} className="text-white" />}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div className="space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.planStatus', 'Plan Status')}</h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.activePlan', 'Active Plan')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.visibleToCustomers', 'Visible to new customers')}</p>
              </div>
              <button onClick={() => setForm(f => ({ ...f, active: !f.active }))}>
                {form.active ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
              </button>
            </div>
          </div>

          {form.name && form.priceMonthly && (
            <div className="card p-5">
              <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.planPreview', 'Plan Preview')}</h3>
              <div className="p-4 rounded-xl border-2" style={{ borderColor: 'hsl(var(--primary))', backgroundColor: 'hsl(var(--primary-light))' }}>
                <p className="font-bold text-base" style={{ color: 'hsl(var(--primary))' }}>{form.name}</p>
                {form.description && <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{form.description}</p>}
                <p className="text-2xl font-bold mt-2" style={{ color: 'hsl(var(--foreground))' }}>
                  ${form.priceMonthly}<span className="text-sm font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>/mo</span>
                </p>
                {form.priceAnnual && <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>${form.priceAnnual}/yr</p>}
                <div className="mt-3 space-y-1">
                  {form.limits.conversations_per_month && <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {parseInt(form.limits.conversations_per_month, 10).toLocaleString()} conversations/mo</p>}
                  {form.limits.max_branches && <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {form.limits.max_branches} branches</p>}
                  <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {form.features.length} features</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {form.trialDays}-day trial</p>
                </div>
              </div>
            </div>
          )}

          <div className="card p-5">
            <h3 className="font-semibold mb-2" style={{ color: 'hsl(var(--foreground))' }}>Stripe Sync</h3>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              On save, a Stripe Product and Price will be created or updated automatically if <code className="text-xs">STRIPE_SECRET_KEY</code> is configured. If Stripe is not set up, the plan is saved to the database only.
            </p>
          </div>
        </div>
      </div>
    </>
  );
}
