"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Coins, Trophy, HelpCircle } from "lucide-react"
import { getSigninStatus, performSignin, SigninData } from "@/api/signin"


export default function SigninPage({ onSuccess }: { onSuccess?: () => void } = {}) {
  const [signinData, setSigninData] = useState<SigninData>({
    has_signin: false,
    credits: 0
  })
  const [isLoading, setIsLoading] = useState(false)
  const [showTip, setShowTip] = useState(false)
  const [isInitialLoading, setIsInitialLoading] = useState(true)


  /**
   * Fetch signin status
   */
  const fetchSigninStatus = async () => {
    try {
      setIsInitialLoading(true)
      const data = await getSigninStatus()
      setSigninData(data.data as SigninData)
    } catch (error) {
      console.error('Failed to fetch signin status:', error)
      // Keep default state
    } finally {
      setIsInitialLoading(false)
    }
  }

  useEffect(() => {
    fetchSigninStatus()
  }, [])

  /**
   * Perform signin operation
   */
  const handleSignin = async () => {
    if (signinData.has_signin) return

    try {
      setIsLoading(true)
      const response = await performSignin()
      
      if (response.successful) {
        // Refresh status after successful signin
        await fetchSigninStatus()
        // Notify parent to refresh credits
        try { onSuccess && onSuccess() } catch {}
      }
    } catch (error) {
      console.error('Signin failed:', error)
    } finally {
      setIsLoading(false)
    }
  }


  if (isInitialLoading) {
    return (
      <div data-alt="signin-container" className="mx-auto w-full max-w-sm space-y-6">
        <Card data-alt="loading-card" className="bg-transparent border-0 shadow-none">
          <CardContent data-alt="loading-content" className="flex items-center justify-center py-12">
            <div data-alt="loading-indicator" className="flex items-center gap-2 text-muted-foreground">
              <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
              Loading...
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div data-alt="signin-container" className="mx-auto w-full max-w-sm space-y-6">

      {/* Signin status card */}
      <Card data-alt="signin-card" className="bg-transparent border-0 shadow-none">
        <CardHeader data-alt="signin-header" className="text-center pb-4 pt-0">
            <h1 data-alt="signin-title" className="text-2xl sm:text-3xl font-bold text-balance bg-gradient-to-r from-custom-blue to-custom-purple bg-clip-text text-transparent">
            Daily Sign-in
          </h1>
          <div className="flex items-center justify-center gap-2">
            <p className="text-sm sm:text-base text-muted-foreground">Sign in to earn credits. Credits are valid for 7 days</p>
            <div className="relative" data-alt="signin-help-wrapper">
              <button
                data-alt="signin-help-button"
                onMouseEnter={() => setShowTip(true)}
                onMouseLeave={() => setShowTip(false)}
                onClick={() => setShowTip((v: boolean) => !v)}
                className="p-2 rounded-full hover:bg-muted/50 transition-colors"
              >
                <HelpCircle className="w-4 h-4 text-muted-foreground hover:text-foreground" />
              </button>
              {showTip && (
                <div
                  data-alt="signin-help-popover"
                  className="fixed left-1/2 -translate-x-1/2 bottom-16 inset-x-4 sm:inset-auto sm:absolute sm:bottom-full sm:left-1/2 sm:-translate-x-1/2 sm:mb-2
                  w-[92vw] max-w-sm sm:w-80 p-3 bg-popover border rounded-lg shadow-lg z-50 max-h-[60vh] overflow-auto"
                >
                  <div className="text-sm space-y-1 text-left">
                    <p className="font-medium text-foreground">Sign-in Rules</p>
                    <p className="text-muted-foreground">• Daily sign-in earns 100 credits</p>
                    <p className="text-muted-foreground">• Credits are valid for 7 days</p>
                    <p className="text-muted-foreground">• Expired credits will be automatically cleared</p>
                  </div>
                  <div className="hidden sm:block absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-l-transparent border-r-transparent border-t-popover"></div>
                </div>
              )}
            </div>
          </div>
        </CardHeader>

        <CardContent data-alt="signin-content" className="space-y-6">
          <div className="grid grid-cols-1 gap-4">
            <div data-alt="credits-card" className="text-center p-4 sm:p-6 rounded-lg bg-gradient-to-br from-custom-blue/20 via-custom-purple/20 to-custom-blue/10 border border-custom-blue/30">
              <div className="flex items-center justify-center gap-2 mb-2">
                <Coins className="w-6 h-6 text-primary" />
                <span className="text-sm text-muted-foreground">Earned Credits</span>
              </div>
              <div className="text-3xl sm:text-4xl font-bold bg-gradient-to-r from-custom-blue to-custom-purple bg-clip-text text-transparent">
                {signinData.credits || 0}
              </div>
            </div>

          </div>

          {/* Sign-in button */}
          <Button
            data-alt="signin-button"
            onClick={handleSignin}
            disabled={signinData.has_signin || isLoading}
            className="w-full h-11 text-base sm:h-12 sm:text-lg font-semibold bg-gradient-to-r from-custom-blue to-custom-purple hover:from-custom-blue/90 hover:to-custom-purple/90 text-white"
            size="lg"
          >
            {isLoading ? (
              <div className="flex items-center gap-2 text-white">
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  Signing in...
                </div>
            ) : signinData.has_signin ? (
              <div className="flex items-center gap-2 text-white">
                <Trophy className="w-4 h-4" />
                Signed in Today
              </div>
            ) : (
              <div className="flex items-center gap-2 text-white">
                <Coins className="w-4 h-4" />
                Sign In Now +100 Credits
              </div>
            )}
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
