'use client';

import { SignInListOutput } from '@/services/home/types';
import { CheckInCard } from './CheckInCard';
import { useEffect } from 'react';
import { useSignIn } from '@/hooks/services/signin';

export function CheckInGrid() {
  const { signInListData, fetchSignInListLoading, handleSignIn, signInLoading } = useSignIn();

  useEffect(() => {
    if (signInListData?.list?.length) {
      handleSignIn();
    }
  }, [signInListData?.list?.length]);

  if (fetchSignInListLoading) {
    return (
      <div className="grid h-[328px] grid-cols-3 grid-rows-2 gap-4">
        {Array.from({ length: 6 }).map((_, index) => (
          <div
            key={index}
            className="animate-pulse rounded-2xl border border-[rgba(251,222,255,0.2)] bg-[#282233]"
          />
        ))}
      </div>
    );
  }

  const signList = signInListData?.list || [];
  const today = new Date();
  const todayStr = today.toISOString().split('T')[0]; // yyyy-MM-dd 格式

  // 确保有7天的数据，如果不足则补充默认数据
  const fullSignList: (SignInListOutput & { day: number })[] = Array.from(
    { length: 7 },
    (_, index) => {
      const day = index + 1;
      const existingData = signList.find((item, itemIndex) => itemIndex === index);

      return {
        day,
        coinNum: existingData?.coinNum || [5, 10, 15, 20, 30, 50, 80][index],
        dayStr: existingData?.dayStr || '',
        signIn: existingData?.signIn || false,
      };
    }
  );

  // 找到今天应该签到的是第几天
  const todayIndex = fullSignList.findIndex((item) => {
    if (!item.dayStr) return false;
    return item.dayStr === todayStr;
  });

  // 如果没有找到今天的数据，假设是按顺序签到，找到第一个未签到的
  const currentDayIndex =
    todayIndex >= 0 ? todayIndex : fullSignList.findIndex((item) => !item.signIn);

  const day7 = fullSignList[6];

  return (
    <div className="flex flex-col gap-4 sm:flex-row">
      <div className="grid flex-1 sm:flex-[3] grid-cols-3 gap-4">
        {fullSignList.slice(0, 6).map((item, index) => {
          return (
            <CheckInCard
              key={item.day}
              day={item.day}
              coinNum={item.coinNum || 0}
              signIn={item.signIn || false}
              isToday={index === currentDayIndex}
              loading={signInLoading}
              className="col-span-1 row-span-1"
            />
          );
        })}
      </div>
      <CheckInCard
        key={day7.day}
        day={day7.day}
        coinNum={day7.coinNum || 0}
        signIn={day7.signIn || false}
        isToday={day7.dayStr === todayStr}
        loading={signInLoading}
        className="col-span-1 sm:flex-1 row-span-1"
      />
    </div>
  );
}

export default CheckInGrid;
