'use client'

import { useState, useEffect } from 'react'
import { useAuthUser } from '@/hooks/useAuthUser'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Trash2, Edit, Plus, Save, X } from 'lucide-react'

interface SubscriptionPlan {
  id: string
  name: string
  displayName: string
  description?: string
  price: number
  currency: string
  interval: string
  stripePriceId?: string
  isActive: boolean
  sortOrder: number
  costMultiplier: number
  features: Record<string, unknown>
  limits: Record<string, unknown>
  createdAt: string
  updatedAt: string
  _count?: {
    users: number
    subscriptions: number
    models: number
  }
}

export default function AdminPlansPage() {
  const { userData, loading: authLoading } = useAuthUser()
  const [plans, setPlans] = useState<SubscriptionPlan[]>([])
  const [loading, setLoading] = useState(true)
  const [editingPlan, setEditingPlan] = useState<SubscriptionPlan | null>(null)
  const [isCreating, setIsCreating] = useState(false)
  const [formData, setFormData] = useState({
    id: '',
    name: '',
    displayName: '',
    description: '',
    price: 0,
    currency: 'usd',
    interval: 'month',
    stripePriceId: '',
    isActive: true,
    sortOrder: 0,
    costMultiplier: 1.0,
    features: '{}',
    limits: '{}'
  })

  useEffect(() => {
    // AdminLayout已经处理了权限验证，这里只需要在认证完成后获取数据
    if (!authLoading && userData && userData.isAdmin) {
      fetchPlans()
    }
  }, [userData, authLoading])

  const fetchPlans = async () => {
    try {
      const response = await fetch('/api/admin/subscription-plans')
      if (!response.ok) {
        throw new Error('Failed to fetch plans')
      }
      const data = await response.json()
      setPlans(data.plans || [])
    } catch (error) {
      alert('Failed to fetch subscription plans')
    } finally {
      setLoading(false)
    }
  }

  const resetForm = () => {
    setFormData({
      id: '',
      name: '',
      displayName: '',
      description: '',
      price: 0,
      currency: 'usd',
      interval: 'month',
      stripePriceId: '',
      isActive: true,
      sortOrder: 0,
      costMultiplier: 1.0,
      features: '{}',
      limits: '{}'
    })
  }

  const handleEdit = (plan: SubscriptionPlan) => {
    setEditingPlan(plan)
    setFormData({
      id: plan.id,
      name: plan.name,
      displayName: plan.displayName,
      description: plan.description || '',
      price: plan.price,
      currency: plan.currency,
      interval: plan.interval,
      stripePriceId: plan.stripePriceId || '',
      isActive: plan.isActive,
      sortOrder: plan.sortOrder,
      costMultiplier: plan.costMultiplier,
      features: JSON.stringify(plan.features, null, 2),
      limits: JSON.stringify(plan.limits, null, 2)
    })
    setIsCreating(false)
  }

  const handleCreate = () => {
    setIsCreating(true)
    setEditingPlan(null)
    resetForm()
  }

  const handleCancel = () => {
    setEditingPlan(null)
    setIsCreating(false)
    resetForm()
  }

  const handleSave = async () => {
    try {
      // 验证 JSON 格式
      let features, limits
      try {
        features = JSON.parse(formData.features)
        limits = JSON.parse(formData.limits)
      } catch {
        alert('Invalid JSON format in features or limits')
        return
      }

      const planData = {
        ...formData,
        features,
        limits
      }

      const url = isCreating 
        ? '/api/admin/subscription-plans' 
        : `/api/admin/subscription-plans?id=${editingPlan?.id}`
      
      const method = isCreating ? 'POST' : 'PUT'
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(planData)
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || 'Failed to save plan')
      }

      alert(isCreating ? 'Plan created successfully' : 'Plan updated successfully')

      fetchPlans()
      handleCancel()
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to save plan')
    }
  }

  const handleDelete = async (planId: string) => {
    if (!confirm('Are you sure you want to delete this plan?')) {
      return
    }

    try {
      const response = await fetch(`/api/admin/subscription-plans?id=${planId}`, {
        method: 'DELETE'
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || 'Failed to delete plan')
      }

      alert('Plan deleted successfully')

      fetchPlans()
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to delete plan')
    }
  }

  // AdminLayout已经处理了认证和权限检查
  if (authLoading || loading) {
    return (
      <div className="container mx-auto py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto"></div>
      </div>
    )
  }

  // 如果没有权限，AdminLayout会重定向，这里不需要额外处理
  if (!userData || !userData.isAdmin) {
    return null
  }

  return (
    <div className="container mx-auto py-8 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Subscription Plans</h1>
          <p className="text-muted-foreground">Manage subscription plans and pricing</p>
        </div>
        <Button onClick={handleCreate} className="flex items-center gap-2">
          <Plus className="h-4 w-4" />
          Create Plan
        </Button>
      </div>

      {/* Plan Editor Form */}
      {(isCreating || editingPlan) && (
        <Card>
          <CardHeader>
            <CardTitle>{isCreating ? 'Create New Plan' : 'Edit Plan'}</CardTitle>
            <CardDescription>
              {isCreating ? 'Create a new subscription plan' : 'Update subscription plan details'}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="id">Plan ID</Label>
                <Input
                  id="id"
                  value={formData.id}
                  onChange={(e) => setFormData(prev => ({ ...prev, id: e.target.value }))}
                  placeholder="e.g., free, pro, premium"
                  disabled={!isCreating}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="name">Internal Name</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                  placeholder="Internal plan name"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="displayName">Display Name</Label>
                <Input
                  id="displayName"
                  value={formData.displayName}
                  onChange={(e) => setFormData(prev => ({ ...prev, displayName: e.target.value }))}
                  placeholder="User-facing plan name"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="price">Price</Label>
                <Input
                  id="price"
                  type="number"
                  step="0.01"
                  value={formData.price}
                  onChange={(e) => setFormData(prev => ({ ...prev, price: parseFloat(e.target.value) || 0 }))}
                  placeholder="0.00"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="currency">Currency</Label>
                <Input
                  id="currency"
                  value={formData.currency}
                  onChange={(e) => setFormData(prev => ({ ...prev, currency: e.target.value }))}
                  placeholder="usd"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="interval">Billing Interval</Label>
                <Input
                  id="interval"
                  value={formData.interval}
                  onChange={(e) => setFormData(prev => ({ ...prev, interval: e.target.value }))}
                  placeholder="month, year"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="costMultiplier">Cost Multiplier</Label>
                <Input
                  id="costMultiplier"
                  type="number"
                  step="0.1"
                  value={formData.costMultiplier}
                  onChange={(e) => setFormData(prev => ({ ...prev, costMultiplier: parseFloat(e.target.value) || 1.0 }))}
                  placeholder="1.0"
                />
                <p className="text-sm text-muted-foreground">AI usage cost multiplier (e.g., 10.0 for free, 3.0 for pro)</p>
              </div>
              <div className="space-y-2">
                <Label htmlFor="sortOrder">Sort Order</Label>
                <Input
                  id="sortOrder"
                  type="number"
                  value={formData.sortOrder}
                  onChange={(e) => setFormData(prev => ({ ...prev, sortOrder: parseInt(e.target.value) || 0 }))}
                  placeholder="0"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                placeholder="Plan description"
                rows={3}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="stripePriceId">Stripe Price ID</Label>
              <Input
                id="stripePriceId"
                value={formData.stripePriceId}
                onChange={(e) => setFormData(prev => ({ ...prev, stripePriceId: e.target.value }))}
                placeholder="price_..."
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="features">Features (JSON)</Label>
              <Textarea
                id="features"
                value={formData.features}
                onChange={(e) => setFormData(prev => ({ ...prev, features: e.target.value }))}
                placeholder='{"promptLimit": 20, "versionLimit": 3}'
                rows={4}
                className="font-mono text-sm"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="limits">Limits (JSON)</Label>
              <Textarea
                id="limits"
                value={formData.limits}
                onChange={(e) => setFormData(prev => ({ ...prev, limits: e.target.value }))}
                placeholder='{"maxPromptsPerDay": 100, "maxAPICallsPerMonth": 1000}'
                rows={4}
                className="font-mono text-sm"
              />
            </div>

            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="isActive"
                checked={formData.isActive}
                onChange={(e) => setFormData(prev => ({ ...prev, isActive: e.target.checked }))}
                className="rounded border-gray-300"
              />
              <Label htmlFor="isActive">Active</Label>
            </div>

            <div className="flex gap-2 pt-4">
              <Button onClick={handleSave} className="flex items-center gap-2">
                <Save className="h-4 w-4" />
                {isCreating ? 'Create' : 'Update'}
              </Button>
              <Button onClick={handleCancel} variant="outline" className="flex items-center gap-2">
                <X className="h-4 w-4" />
                Cancel
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Plans List */}
      <div className="grid gap-4">
        {plans.map((plan) => (
          <Card key={plan.id} className="relative">
            <CardHeader>
              <div className="flex justify-between items-start">
                <div>
                  <CardTitle className="flex items-center gap-2">
                    {plan.displayName}
                    <Badge variant={plan.isActive ? 'default' : 'secondary'}>
                      {plan.isActive ? 'Active' : 'Inactive'}
                    </Badge>
                  </CardTitle>
                  <CardDescription>{plan.description}</CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => handleEdit(plan)}>
                    <Edit className="h-4 w-4" />
                  </Button>
                  <Button 
                    size="sm" 
                    variant="destructive" 
                    onClick={() => handleDelete(plan.id)}
                    disabled={plan._count && (plan._count.users > 0 || plan._count.subscriptions > 0)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <p className="font-medium">ID</p>
                  <p className="text-muted-foreground">{plan.id}</p>
                </div>
                <div>
                  <p className="font-medium">Price</p>
                  <p className="text-muted-foreground">
                    {plan.price === 0 ? 'Free' : `$${plan.price}/${plan.interval}`}
                  </p>
                </div>
                <div>
                  <p className="font-medium">Cost Multiplier</p>
                  <p className="text-muted-foreground">{plan.costMultiplier}x</p>
                </div>
                <div>
                  <p className="font-medium">Sort Order</p>
                  <p className="text-muted-foreground">{plan.sortOrder}</p>
                </div>
                {plan._count && (
                  <>
                    <div>
                      <p className="font-medium">Users</p>
                      <p className="text-muted-foreground">{plan._count.users}</p>
                    </div>
                    <div>
                      <p className="font-medium">Subscriptions</p>
                      <p className="text-muted-foreground">{plan._count.subscriptions}</p>
                    </div>
                    <div>
                      <p className="font-medium">Models</p>
                      <p className="text-muted-foreground">{plan._count.models}</p>
                    </div>
                  </>
                )}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}