'use client'
import Image from 'next/image'
import { useState } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { useProfileData } from '@/hooks/useProfileData'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Camera, Mail, Calendar, Shield, Copy, Check, Server, Wallet } from 'lucide-react'
import { BalanceDisplay } from '@/components/balance'

export function ProfileCard() {
  const { user } = useAuth()
  const { profileStats, isLoading } = useProfileData()
  const [copied, setCopied] = useState(false)

  if (!user) return null

  // Generate Silicon ID (dummy implementation for UI testing)
  const siliconId = user.siliconId || ''
  // const siliconId = user.email?.split('@')[0]?.toUpperCase() || 'SILICON001'

  const handleCopySiliconId = async () => {
    try {
      await navigator.clipboard.writeText(siliconId)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error('Failed to copy: ', err)
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    })
  }

  const getProviderBadge = (provider: string) => {
    const variants = {
      local: { variant: 'secondary' as const, label: 'Email' },
      google: { variant: 'default' as const, label: 'Google' },
      github: { variant: 'outline' as const, label: 'GitHub' },
    }

    const config = variants[provider as keyof typeof variants] || variants.local

    return (
      <Badge variant={config.variant} className="text-xs">
        {config.label}
      </Badge>
    )
  }

  return (
    <Card>
      <CardHeader className="text-center">
        <div className="relative mx-auto">
          <div className="w-24 h-24 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white text-2xl font-bold mb-4 mx-auto">
            {user.avatar ? (
              <Image
                src={user.avatar}
                alt={user.name}
                width={96}
                height={96}
                className="w-24 h-24 rounded-full object-cover"
              />
            ) : (
              user.name.charAt(0).toUpperCase()
            )}
          </div>
          <Button
            size="sm"
            variant="outline"
            className="absolute bottom-0 right-0 rounded-full w-8 h-8 p-0"
          >
            <Camera className="w-4 h-4" />
          </Button>
        </div>

        <div className="space-y-3">
          <h2 className="text-xl font-semibold">{user.name}</h2>

          <div className="flex items-center justify-center gap-1 text-sm">
            <span className="text-muted-foreground">Silicon ID:</span>
            <code className="px-2 py-1 bg-muted rounded text-sm font-mono">{siliconId}</code>
            <Button size="sm" variant="ghost" className="h-6 w-6 p-0" onClick={handleCopySiliconId}>
              {copied ? <Check className="w-3 h-3 text-green-600" /> : <Copy className="w-3 h-3" />}
            </Button>
          </div>

          <div className="flex items-center justify-center gap-2">
            {getProviderBadge(user.provider)}
            {user.role === 'admin' && (
              <Badge variant="destructive" className="text-xs">
                <Shield className="w-3 h-3 mr-1" />
                Admin
              </Badge>
            )}
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        <div className="flex items-center space-x-3 text-sm">
          <Mail className="w-4 h-4 text-muted-foreground" />
          <span className="text-muted-foreground">{user.email}</span>
        </div>

        <div className="flex items-center space-x-3 text-sm">
          <Calendar className="w-4 h-4 text-muted-foreground" />
          <div className="flex flex-col">
            <span className="text-muted-foreground">Joined {formatDate(user.createdAt)}</span>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4 pt-4 border-t">
          <div className="text-center">
            <div className="flex items-center justify-center gap-1 mb-1">
              <Server className="w-4 h-4 text-muted-foreground" />
              {isLoading ? (
                <Skeleton className="h-6 w-4" />
              ) : (
                <span className="text-lg font-semibold">{profileStats?.activeServices || 3}</span>
              )}
            </div>
            <span className="text-xs text-muted-foreground">Active Services</span>
          </div>
          <div className="text-center">
            <div className="flex items-center justify-center gap-1 mb-1">
              {/* <Wallet className="w-4 h-4 text-muted-foreground" /> */}
              {isLoading ? (
                <Skeleton className="h-6 w-16" />
              ) : (
                <BalanceDisplay
                  className="text-lg font-semibold text-green-600"
                  variant="default"
                />
                // <span className="text-lg font-semibold text-green-600">
                //   ₹
                //   {profileS'tats?.balance?.toLocaleString('en-IN', { minimumFractionDigits: 2 }) ||
                //     '1,250.00'}
                // </span>
              )}
            </div>
            <span className="text-xs text-muted-foreground">Balance</span>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4 pt-3">
          <div className="text-center">
            {isLoading ? (
              <Skeleton className="h-6 w-8 mx-auto mb-1" />
            ) : (
              <div className="text-lg font-semibold text-blue-600">
                {profileStats?.totalTopics || 0}
              </div>
            )}
            <span className="text-xs text-muted-foreground">Total Topics</span>
          </div>
          <div className="text-center">
            {isLoading ? (
              <Skeleton className="h-6 w-12 mx-auto mb-1" />
            ) : (
              <div className="text-lg font-semibold text-purple-600">
                {profileStats?.totalViews
                  ? profileStats.totalViews >= 1000
                    ? `${(profileStats.totalViews / 1000).toFixed(1)}K`
                    : profileStats.totalViews.toLocaleString()
                  : '0'}
              </div>
            )}
            <span className="text-xs text-muted-foreground">Total Views</span>
          </div>
        </div>

        <div className="flex items-center justify-between pt-2">
          <span className="text-sm text-muted-foreground">Account Status</span>
          <Badge variant={user.isVerified ? 'default' : 'secondary'}>
            {user.isVerified ? 'Verified' : 'Unverified'}
          </Badge>
        </div>
      </CardContent>
    </Card>
  )
}
