'use client';

import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';
import { PageHeader } from '@/components/ui/page-header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Modal } from '@/components/ui/modal';
import { EmptyState } from '@/components/ui/empty-state';
import { CardSkeleton } from '@/components/ui/skeleton';
import { useToast } from '@/components/ui/toast';

interface Plan {
  id: string;
  name: string;
  description: string | null;
  speedDown: number;
  speedUp: number;
  price: string;
  billingCycle: number;
  isActive: boolean;
  _count: { subscriptions: number };
}

export default function PlansPage() {
  const { toast } = useToast();
  const [plans, setPlans] = useState<Plan[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Plan | null>(null);
  const [deleting, setDeleting] = useState(false);

  const loadPlans = useCallback(async () => {
    try {
      const res = await api.get<{ data: Plan[] }>('/plans');
      setPlans(res.data.data);
    } catch { toast('Failed to load plans', 'error'); }
    finally { setLoading(false); }
  }, [toast]);

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

  async function handleDelete() {
    if (!deleteTarget) return;
    setDeleting(true);
    try {
      await api.delete(`/plans/${deleteTarget.id}`);
      toast(`Plan "${deleteTarget.name}" deleted`, 'success');
      setDeleteTarget(null);
      loadPlans();
    } catch (err: any) { toast(err.response?.data?.error || 'Failed to delete', 'error'); }
    finally { setDeleting(false); }
  }

  return (
    <div>
      <PageHeader title="Plan / Package Management" description="Configure internet plans with speed tiers and pricing"
        action={<Button onClick={() => setShowCreate(!showCreate)} variant={showCreate ? 'secondary' : 'primary'}>{showCreate ? 'Cancel' : 'Add Plan'}</Button>} />

      {showCreate && <CreatePlanForm onCreated={() => { setShowCreate(false); loadPlans(); toast('Plan created', 'success'); }} />}

      {loading ? (
        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">{[1, 2, 3].map((i) => <CardSkeleton key={i} />)}</div>
      ) : plans.length === 0 ? (
        <div className="mt-6"><EmptyState title="No plans yet" description="Create your first internet plan to start onboarding clients."
          icon={<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="3" /><path d="M9 9h6v6H9z" /></svg>}
          action={<Button onClick={() => setShowCreate(true)}>Create First Plan</Button>} /></div>
      ) : (
        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {plans.map((plan) => (
            <article key={plan.id} className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200/80 dark:border-surface-700 p-5 hover:shadow-md hover:shadow-surface-100 transition-all duration-200">
              <div className="flex items-start justify-between">
                <h3 className="font-semibold text-surface-900 dark:text-surface-200">{plan.name}</h3>
                <Badge label={plan.isActive ? 'Active' : 'Inactive'} variant={plan.isActive ? 'success' : 'error'} />
              </div>
              {plan.description && <p className="text-sm text-surface-500 dark:text-surface-400 mt-1">{plan.description}</p>}
              <div className="mt-3 space-y-1.5 text-sm">
                <div className="flex justify-between"><span className="text-surface-500 dark:text-surface-400">Speed</span><span className="font-medium text-surface-900 dark:text-surface-200">{plan.speedDown}/{plan.speedUp} Mbps</span></div>
                <div className="flex justify-between"><span className="text-surface-500 dark:text-surface-400">Price</span><span className="font-medium text-surface-900 dark:text-surface-200">PHP {Number(plan.price).toLocaleString()}</span></div>
                <div className="flex justify-between"><span className="text-surface-500 dark:text-surface-400">Billing Cycle</span><span className="text-surface-700 dark:text-surface-300">{plan.billingCycle} days</span></div>
              </div>
              <div className="mt-4 flex items-center justify-between pt-3 border-t border-surface-100 dark:border-surface-700">
                <span className="text-xs text-surface-500 dark:text-surface-400">{plan._count.subscriptions} subscriber{plan._count.subscriptions !== 1 ? 's' : ''}</span>
                {plan._count.subscriptions === 0 && <Button size="sm" variant="ghost" onClick={() => setDeleteTarget(plan)}>Delete</Button>}
              </div>
            </article>
          ))}
        </div>
      )}

      <Modal open={!!deleteTarget} onClose={() => setDeleteTarget(null)} title="Delete Plan"
        description={`Are you sure you want to delete "${deleteTarget?.name}"? This action cannot be undone.`}
        variant="danger" confirmLabel="Delete Plan" onConfirm={handleDelete} loading={deleting} />
    </div>
  );
}

function CreatePlanForm({ onCreated }: { onCreated: () => void }) {
  const { toast } = useToast();
  const [form, setForm] = useState({ name: '', description: '', speedDown: 25, speedUp: 25, price: 999, billingCycle: 30 });
  const [submitting, setSubmitting] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    try {
      await api.post('/plans', { ...form, description: form.description || undefined });
      onCreated();
    } catch (err: any) { toast(err.response?.data?.error || 'Failed to create plan', 'error'); }
    finally { setSubmitting(false); }
  }

  return (
    <form onSubmit={handleSubmit} className="mt-4 bg-white dark:bg-surface-800 rounded-xl border border-surface-200/80 dark:border-surface-700 p-6 space-y-4 max-w-lg">
      <div>
        <label htmlFor="plan-name" className="block text-sm font-medium text-surface-700 dark:text-surface-300">Plan Name</label>
        <input id="plan-name" type="text" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
          className="mt-1 block w-full rounded-lg border border-surface-200 dark:border-surface-700 px-3.5 py-2.5 text-sm text-surface-900 dark:text-surface-200 placeholder:text-surface-400 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 transition-all duration-200"
          placeholder="e.g. Basic 25" />
      </div>
      <div>
        <label htmlFor="plan-desc" className="block text-sm font-medium text-surface-700 dark:text-surface-300">Description <span className="text-surface-400 font-normal">(optional)</span></label>
        <input id="plan-desc" type="text" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })}
          className="mt-1 block w-full rounded-lg border border-surface-200 dark:border-surface-700 px-3.5 py-2.5 text-sm text-surface-900 dark:text-surface-200 placeholder:text-surface-400 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 transition-all duration-200" />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div><label className="block text-sm font-medium text-surface-700 dark:text-surface-300">Download (Mbps)</label>
          <input type="number" required min={1} value={form.speedDown} onChange={(e) => setForm({ ...form, speedDown: parseInt(e.target.value) || 0 })}
            className="mt-1 block w-full rounded-lg border border-surface-200 dark:border-surface-700 px-3.5 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 transition-all duration-200" /></div>
        <div><label className="block text-sm font-medium text-surface-700 dark:text-surface-300">Upload (Mbps)</label>
          <input type="number" required min={1} value={form.speedUp} onChange={(e) => setForm({ ...form, speedUp: parseInt(e.target.value) || 0 })}
            className="mt-1 block w-full rounded-lg border border-surface-200 dark:border-surface-700 px-3.5 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 transition-all duration-200" /></div>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div><label className="block text-sm font-medium text-surface-700 dark:text-surface-300">Price (PHP)</label>
          <input type="number" required min={1} step={0.01} value={form.price} onChange={(e) => setForm({ ...form, price: parseFloat(e.target.value) || 0 })}
            className="mt-1 block w-full rounded-lg border border-surface-200 dark:border-surface-700 px-3.5 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 transition-all duration-200" /></div>
        <div><label className="block text-sm font-medium text-surface-700 dark:text-surface-300">Billing Cycle (days)</label>
          <input type="number" required min={1} value={form.billingCycle} onChange={(e) => setForm({ ...form, billingCycle: parseInt(e.target.value) || 30 })}
            className="mt-1 block w-full rounded-lg border border-surface-200 dark:border-surface-700 px-3.5 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 transition-all duration-200" /></div>
      </div>
      <Button type="submit" loading={submitting}>Create Plan</Button>
    </form>
  );
}
