'use client';

import { useState, useEffect } from 'react';
import { Check, Pencil, Plus, Users, Zap, Shield, Crown } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { formatCurrency, formatNumber } from '@/lib/mock-data';
import { apiListUsers, apiUpdatePlan, apiCreatePlan, apiListPlans, type PlanDoc } from '@/lib/api';

const planIcons = {
  Free: Zap,
  Pro: Shield,
  Enterprise: Crown,
};

const planColors = {
  Free: 'border-muted',
  Pro: 'border-blue-200 bg-blue-50/30',
  Enterprise: 'border-violet-200 bg-violet-50/30',
};

interface LocalPlan {
  id: string;
  name: string;
  price: number;
  interval: string;
  features: string[];
  limits: { tokensPerMonth: number; requestsPerDay: number; modelsAllowed: string[] };
  activeUsers: number;
}

function planDocToLocal(p: PlanDoc): LocalPlan {
  return {
    id: p.id,
    name: p.displayName || p.name,
    price: p.price,
    interval: 'monthly',
    features: p.features ?? [],
    limits: {
      tokensPerMonth: p.tokens ?? 0,
      requestsPerDay: p.dictations ?? 0,
      modelsAllowed: ['gpt-4o-mini'],
    },
    activeUsers: 0,
  };
}

export default function SubscriptionsPage() {
  const [plans, setPlans] = useState<LocalPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [newPlanName, setNewPlanName] = useState('');
  const [newPlanPrice, setNewPlanPrice] = useState('');
  const [newPlanTokens, setNewPlanTokens] = useState('');
  const [newPlanRequests, setNewPlanRequests] = useState('');
  const [newPlanYearly, setNewPlanYearly] = useState(false);

  useEffect(() => {
    async function load() {
      try {
        const [plansRes, usersRes] = await Promise.allSettled([apiListPlans(), apiListUsers()]);
        let loadedPlans: LocalPlan[] = [];
        if (plansRes.status === 'fulfilled' && plansRes.value.data?.plans?.length) {
          loadedPlans = plansRes.value.data.plans.filter(p => p.active).map(planDocToLocal);
        }
        if (usersRes.status === 'fulfilled' && usersRes.value.data?.byPlan) {
          const byPlan = usersRes.value.data.byPlan;
          loadedPlans = loadedPlans.map(p => ({
            ...p,
            activeUsers: byPlan[p.name.toLowerCase()] ?? 0,
          }));
        }
        if (loadedPlans.length > 0) setPlans(loadedPlans);
      } catch {
        // use empty
      } finally {
        setLoading(false);
      }
    }
    load();
  }, []);
  const [editingPlan, setEditingPlan] = useState<string | null>(null);
  const [showNewPlan, setShowNewPlan] = useState(false);
  const [editPrice, setEditPrice] = useState('');
  const [editTokens, setEditTokens] = useState('');
  const [editRequests, setEditRequests] = useState('');

  const totalMRR = plans.reduce((sum, p) => sum + p.price * p.activeUsers, 0);
  const totalActiveUsers = plans.reduce((sum, p) => sum + p.activeUsers, 0);

  const startEdit = (planId: string) => {
    const plan = plans.find(p => p.id === planId);
    if (plan) {
      setEditPrice(plan.price.toString());
      setEditTokens(plan.limits.tokensPerMonth.toString());
      setEditRequests(plan.limits.requestsPerDay.toString());
      setEditingPlan(planId);
    }
  };

  const saveEdit = async () => {
    if (!editingPlan) return;
    setSaving(true);
    try {
      await apiUpdatePlan(editingPlan, {
        price: parseFloat(editPrice) || 0,
        tokensPerMonth: parseInt(editTokens) || 0,
        requestsPerDay: parseInt(editRequests) || 0,
      });
      setPlans(prev =>
        prev.map(p =>
          p.id === editingPlan
            ? {
                ...p,
                price: parseFloat(editPrice) || 0,
                limits: {
                  ...p.limits,
                  tokensPerMonth: parseInt(editTokens) || 0,
                  requestsPerDay: parseInt(editRequests) || 0,
                },
              }
            : p
        )
      );
      setEditingPlan(null);
    } catch {
      // API failed — keep dialog open so user can retry
    } finally {
      setSaving(false);
    }
  };

  const handleCreatePlan = async () => {
    if (!newPlanName.trim()) return;
    setSaving(true);
    try {
      const created = await apiCreatePlan({
        name: newPlanName.trim(),
        price: parseFloat(newPlanPrice) || 0,
        tokensPerMonth: parseInt(newPlanTokens) || 0,
        requestsPerDay: parseInt(newPlanRequests) || 0,
        yearlyDiscount: newPlanYearly,
      });
      setPlans(prev => [
        ...prev,
        {
          id: created.data?.plan ?? `plan-${Date.now()}`,
          name: newPlanName.trim(),
          price: parseFloat(newPlanPrice) || 0,
          interval: newPlanYearly ? 'yearly' : 'monthly',
          features: [],
          limits: {
            tokensPerMonth: parseInt(newPlanTokens) || 0,
            requestsPerDay: parseInt(newPlanRequests) || 0,
            modelsAllowed: ['gpt-4o-mini'],
          },
          activeUsers: 0,
        },
      ]);
      setShowNewPlan(false);
      setNewPlanName('');
      setNewPlanPrice('');
      setNewPlanTokens('');
      setNewPlanRequests('');
      setNewPlanYearly(false);
    } catch {
      // keep dialog open on failure
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Subscriptions</h1>
          <p className="text-muted-foreground">Manage pricing plans and subscription tiers</p>
        </div>
        <Button onClick={() => setShowNewPlan(true)}>
          <Plus className="mr-2 h-4 w-4" />
          New Plan
        </Button>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Monthly Recurring Revenue
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(totalMRR)}</div>
            <p className="text-xs text-muted-foreground mt-1">Across {plans.length} plans</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Subscribers
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalActiveUsers}</div>
            <p className="text-xs text-muted-foreground mt-1">Active subscriptions</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Avg Revenue Per User
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {totalActiveUsers > 0 ? formatCurrency(totalMRR / totalActiveUsers) : '$0.00'}
            </div>
            <p className="text-xs text-muted-foreground mt-1">ARPU</p>
          </CardContent>
        </Card>
      </div>

      {/* Plan Cards */}
      <div className="grid gap-6 md:grid-cols-3">
        {plans.map(plan => {
          const Icon = planIcons[plan.name as keyof typeof planIcons] || Zap;
          const borderColor = planColors[plan.name as keyof typeof planColors] || 'border-muted';
          return (
            <Card key={plan.id} className={`relative ${borderColor}`}>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                      <Icon className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-lg">{plan.name}</CardTitle>
                      <div className="flex items-center gap-1">
                        <Users className="h-3 w-3 text-muted-foreground" />
                        <span className="text-xs text-muted-foreground">
                          {plan.activeUsers} active
                        </span>
                      </div>
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    onClick={() => startEdit(plan.id)}
                  >
                    <Pencil className="h-4 w-4" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <span className="text-3xl font-bold">
                    {plan.price === 0 ? 'Free' : formatCurrency(plan.price)}
                  </span>
                  {plan.price > 0 && (
                    <span className="text-muted-foreground text-sm">
                      /{plan.interval === 'monthly' ? 'mo' : 'yr'}
                    </span>
                  )}
                </div>

                <Separator />

                <div className="space-y-2">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Limits
                  </p>
                  <div className="text-sm space-y-1">
                    <p>
                      <span className="font-medium">Tokens: </span>
                      {plan.limits.tokensPerMonth === -1
                        ? 'Unlimited'
                        : formatNumber(plan.limits.tokensPerMonth) + '/mo'}
                    </p>
                    <p>
                      <span className="font-medium">Requests: </span>
                      {plan.limits.requestsPerDay === -1
                        ? 'Unlimited'
                        : formatNumber(plan.limits.requestsPerDay) + '/day'}
                    </p>
                    <p>
                      <span className="font-medium">Models: </span>
                      {plan.limits.modelsAllowed.join(', ')}
                    </p>
                  </div>
                </div>

                <Separator />

                <div className="space-y-2">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Features
                  </p>
                  <ul className="space-y-1.5">
                    {plan.features.map(feature => (
                      <li key={feature} className="flex items-center gap-2 text-sm">
                        <Check className="h-3.5 w-3.5 text-emerald-500 shrink-0" />
                        {feature}
                      </li>
                    ))}
                  </ul>
                </div>

                <div className="pt-2">
                  <Badge variant="secondary" className="w-full justify-center py-1">
                    Revenue: {formatCurrency(plan.price * plan.activeUsers)}/mo
                  </Badge>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Edit Plan Dialog */}
      <Dialog open={!!editingPlan} onOpenChange={() => setEditingPlan(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Edit Plan Pricing</DialogTitle>
            <DialogDescription>
              Update pricing and limits for this subscription tier.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Price (USD / month)</Label>
              <Input type="number" value={editPrice} onChange={e => setEditPrice(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Tokens per Month (-1 for unlimited)</Label>
              <Input
                type="number"
                value={editTokens}
                onChange={e => setEditTokens(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Requests per Day (-1 for unlimited)</Label>
              <Input
                type="number"
                value={editRequests}
                onChange={e => setEditRequests(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditingPlan(null)}>
              Cancel
            </Button>
            <Button onClick={saveEdit} disabled={saving}>
              {saving ? 'Saving…' : 'Save Changes'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* New Plan Dialog */}
      <Dialog open={showNewPlan} onOpenChange={setShowNewPlan}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create New Plan</DialogTitle>
            <DialogDescription>Define a new subscription tier for your platform.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Plan Name</Label>
              <Input
                placeholder="e.g. Team, Business..."
                value={newPlanName}
                onChange={e => setNewPlanName(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Price (USD / month)</Label>
              <Input
                type="number"
                placeholder="49.99"
                value={newPlanPrice}
                onChange={e => setNewPlanPrice(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Tokens per Month</Label>
              <Input
                type="number"
                placeholder="5000000"
                value={newPlanTokens}
                onChange={e => setNewPlanTokens(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Requests per Day</Label>
              <Input
                type="number"
                placeholder="5000"
                value={newPlanRequests}
                onChange={e => setNewPlanRequests(e.target.value)}
              />
            </div>
            <div className="flex items-center gap-2">
              <Switch id="yearly" checked={newPlanYearly} onCheckedChange={setNewPlanYearly} />
              <Label htmlFor="yearly">Offer yearly billing (20% discount)</Label>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowNewPlan(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreatePlan} disabled={saving || !newPlanName.trim()}>
              {saving ? 'Creating…' : 'Create Plan'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
