'use client'

import React, { useEffect, useState } from 'react'
import PricingCard from './PricingCard'
import { PricingCardProps } from '@/app/types'
import useUserStore from '@/app/store/userStore'
import Loader from '@/components/ui/Loader'

const AdminPayments = () => {
  const { user } = useUserStore()
  const [plans, setPlans] = useState<PricingCardProps[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchPlans = async () => {
      try {
        const response = await fetch('/api/account/membership')
        if (!response.ok) {
          throw new Error('Failed to fetch plans')
        }
        const data = await response.json()
        setPlans(data)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load pricing plans')
      } finally {
        setIsLoading(false)
      }
    }

    fetchPlans()
  }, [])

  if (isLoading) {
    return <Loader />
  }

  if (error) {
    return <div className="p-8 text-center text-red-500">{error}</div>
  }

  return (
    <div className="container mx-auto translate-y-5 animate-[fadeIn_1.1s_ease-out_forwards] space-y-6">
      <h2 className="mb-6 text-center text-3xl font-bold">Тарифные планы</h2>
      <div className="grid grid-cols-1 gap-8 rounded-lg bg-white p-8 md:grid-cols-3">
        {plans.map(plan => (
          <PricingCard
            key={plan.plan}
            {...plan}
            isActive={user?.account_type?.toLowerCase() === plan.plan.toLowerCase()}
          />
        ))}
      </div>
    </div>
  )
}

export default AdminPayments
