"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 { getCheckinStatus, performCheckin, CheckinData } from "@/api/checkin"


export default function CheckinPage() {
  const [checkinData, setCheckinData] = useState<CheckinData>({
    hasCheckedInToday: false,
    points: 0,
    lastCheckinDate: null,
    pointsHistory: [],
  })
  const [isLoading, setIsLoading] = useState(false)
  const [showTip, setShowTip] = useState(false)
  const [isInitialLoading, setIsInitialLoading] = useState(true)


  /**
   * Fetch checkin status
   */
  const fetchCheckinStatus = async () => {
    try {
      setIsInitialLoading(true)
      const data = await getCheckinStatus()
      setCheckinData(data)
    } catch (error) {
      console.error('Failed to fetch checkin status:', error)
      // Keep default state
    } finally {
      setIsInitialLoading(false)
    }
  }

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

  /**
   * Perform checkin operation
   */
  const handleCheckin = async () => {
    if (checkinData.hasCheckedInToday) return

    try {
      setIsLoading(true)
      const response = await performCheckin()
      
      if (response.success) {
        // Refresh status after successful checkin
        await fetchCheckinStatus()
      }
    } catch (error) {
      console.error('Checkin failed:', error)
    } finally {
      setIsLoading(false)
    }
  }


  if (isInitialLoading) {
    return (
      <div className="mx-auto max-w-md space-y-6">
        <Card className="bg-transparent border-0 shadow-none">
          <CardContent className="flex items-center justify-center py-12">
            <div 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 className="mx-auto max-w-md space-y-6">

      {/* Checkin status card */}
      <Card className="bg-transparent border-0 shadow-none">
        <CardHeader className="text-center pb-4 pt-0">
            <h1 className="text-3xl font-bold text-balance bg-gradient-to-r from-custom-blue to-custom-purple bg-clip-text text-transparent">
            Daily Check-in
          </h1>
          <div className="flex items-center justify-center gap-2">
            <p className="text-muted-foreground">Check in to earn credits, credits valid for 7 days</p>
            <div className="relative">
              <button
                onMouseEnter={() => setShowTip(true)}
                onMouseLeave={() => setShowTip(false)}
                className="p-1 rounded-full hover:bg-muted/50 transition-colors"
              >
                <HelpCircle className="w-4 h-4 text-muted-foreground hover:text-foreground" />
              </button>
              {showTip && (
                <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 w-80 p-3 bg-popover border rounded-lg shadow-lg z-10">
                  <div className="text-sm space-y-1 text-left">
                    <p className="font-medium text-foreground">Check-in Rules</p>
                    <p className="text-muted-foreground">• Daily check-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="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 className="space-y-6">
          <div className="grid grid-cols-1 gap-4">
            <div className="text-center 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">Current Credits</span>
              </div>
              <div className="text-3xl font-bold bg-gradient-to-r from-custom-blue to-custom-purple bg-clip-text text-transparent">
                {checkinData.points}
              </div>
            </div>

          </div>

          {/* Check-in button */}
          <Button
            onClick={handleCheckin}
            disabled={checkinData.hasCheckedInToday || isLoading}
            className="w-full h-12 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" />
                Checking in...
              </div>
            ) : checkinData.hasCheckedInToday ? (
              <div className="flex items-center gap-2 text-white">
                <Trophy className="w-4 h-4" />
                Checked in Today
              </div>
            ) : (
              <div className="flex items-center gap-2 text-white">
                <Coins className="w-4 h-4" />
                Check In Now +100 Credits
              </div>
            )}
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
