'use client'

import React, { useEffect, useState } from 'react'
import { format } from 'date-fns'
import {
  Avatar,
  Badge,
  Card,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeadCell,
  TableRow,
} from 'flowbite-react'
import { DynamicStringEnumKeysOf, FlowbiteColors } from 'flowbite-react/types'
import { DateType } from 'react-tailwindcss-datepicker'
import { useRouter } from 'next/navigation'

import { paginationDefaultData } from '@/lib/data/pagination'
import { useAuth } from '@/lib/context/AuthContext'
import { leaderboards } from '@/lib/services/affiliate-services'
import tableTheme from '@/lib/themes/table'
import badgeTheme from '@/lib/themes/badge'
import { formatIDR } from '@/lib/utils/currency'
import { getKualaLumpurDate, parseKualaLumpurDate } from '@/lib/utils/date'
import PageHeader from '@/lib/components/PageHeader'
import DatePicker, { FormattedDate } from '@/lib/components/DatePicker'
import PaginationComponent from '@/lib/components/Pagination'
import avatarTheme from '@/lib/themes/avatar'
import GrowthIndicator from '@/lib/components/GrowthIndicator'
import { capitalizeWords } from '@/lib/utils/string'
import { AffiliateLeaderboard } from './types'

export default function MainContent() {
  const router = useRouter()
  const { user } = useAuth()
  const [isLoading, setIsLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [limit, setLimit] = useState(10)
  const [searchDate, setSearchDate] = useState<{
    startDate: DateType
    endDate: DateType
  }>({
    startDate: getKualaLumpurDate(),
    endDate: getKualaLumpurDate(),
  })
  const [affiliateLeaderboards, setAffiliateLeaderboards] = useState<
    Pagination<AffiliateLeaderboard>
  >(paginationDefaultData)
  const [topAffiliates, setTopAffiliates] = useState<AffiliateLeaderboard[]>([])

  useEffect(() => {
    if (!user) return

    async function fetchAffiliateLeaderboards(date: string) {
      setIsLoading(true)

      try {
        const [leaderboardData, topData] = await Promise.all([
          leaderboards({ date, page: currentPage, limit }),
          leaderboards({ date, page: 1, limit: 3 }),
        ])

        setAffiliateLeaderboards(leaderboardData)
        setTopAffiliates(topData.data)
      } catch (error) {
        console.error('Error fetching affiliate leaderboards:', error)
      } finally {
        setIsLoading(false)
      }
    }

    const date = searchDate.startDate
      ? format(getKualaLumpurDate(searchDate.startDate as Date), 'yyyy-MM-dd')
      : format(parseKualaLumpurDate(), 'yyyy-MM-dd')

    fetchAffiliateLeaderboards(date)
  }, [user, currentPage, limit, searchDate])

  function handleChangeDate(formattedDate: FormattedDate) {
    const startDate = formattedDate?.startDate
      ? new Date(formattedDate.startDate)
      : null
    const endDate = formattedDate?.endDate
      ? new Date(formattedDate.endDate)
      : null

    setCurrentPage(1)
    setSearchDate({ startDate, endDate })
  }

  function handleLimitChange(newLimit: number) {
    setLimit(newLimit)
    setCurrentPage(1)
  }

  function handlePageChange(page: number) {
    setCurrentPage(page)
  }

  const getBadgeColor = (
    rank: number,
  ): DynamicStringEnumKeysOf<FlowbiteColors> => {
    switch (rank) {
      case 1:
        return 'yellow'
      case 2:
        return 'gray'
      default:
        return 'lime'
    }
  }

  const getCategoryBadgeColor = (
    category: AffiliateLeaderboard['category'],
  ): DynamicStringEnumKeysOf<FlowbiteColors> => {
    return category === 'business' ? 'blue' : 'purple'
  }

  useEffect(() => {
    if (user && user.role !== 'manager') {
      router.push('/')
      return
    }
  }, [user, router])

  return (
    <React.Fragment>
      <div className="mt-6 w-full max-w-7xl mx-auto">
        <div className="flex justify-between gap-10 items-end flex-wrap">
          <PageHeader
            title="Affiliate Performance"
            description="Monitor the affiliate performance of our partners and identify top performers."
          />
          <div className="w-full xl:max-w-96">
            <DatePicker
              inputId="date"
              displayFormat="MMMM YYYY"
              asSingle
              value={{
                startDate: searchDate.startDate as DateType,
                endDate: searchDate.endDate as DateType,
              }}
              onDateChange={handleChangeDate}
            />
          </div>
        </div>

        <hr className="mt-10" />
      </div>

      <section className="mt-10 max-w-7xl mx-auto">
        <div className="space-y-8">
          {/* Top 3 Affiliates */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {isLoading
              ? Array.from({ length: 3 }).map((_, idx) => (
                  <Card
                    key={`sk-${idx}`}
                    className="shadow-none h-fit animate-pulse"
                  >
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 rounded-full bg-slate-200" />
                      <div className="flex-1">
                        <div className="h-4 w-32 bg-slate-200 rounded mb-2" />
                        <div className="h-3 w-20 bg-slate-200 rounded mb-2" />
                        <div className="h-6 w-16 bg-slate-200 rounded" />
                      </div>
                    </div>
                    <div className="mt-4 grid grid-cols-2 border-t border-gray-200 divide-x divide-gray-200">
                      <div className="p-2">
                        <div className="h-3 w-20 bg-slate-200 rounded mb-2" />
                        <div className="h-6 w-12 bg-slate-200 rounded" />
                      </div>
                      <div className="p-2">
                        <div className="h-3 w-20 bg-slate-200 rounded mb-2" />
                        <div className="h-6 w-24 bg-slate-200 rounded" />
                      </div>
                    </div>
                  </Card>
                ))
              : topAffiliates.map((affiliate, idx) => (
                  <Card key={affiliate.id} className="shadow-none h-fit">
                    <div className="flex items-center gap-4">
                      <Avatar
                        alt={`${affiliate.name} Avatar`}
                        img={`https://api.dicebear.com/9.x/initials/svg?seed=${affiliate.name}&backgroundType=gradientLinear`}
                        rounded
                        size="md"
                      />
                      <div>
                        <h3 className="font-semibold text-base">
                          {affiliate.partner_name}
                        </h3>
                        <div className="flex items-center gap-2 mt-2">
                          <Badge
                            className="w-fit"
                            theme={badgeTheme.badge}
                            color={getBadgeColor(idx + 1)}
                          >
                            Rank #{idx + 1}
                          </Badge>
                          <Badge
                            className="w-fit"
                            theme={badgeTheme.badge}
                            color={getCategoryBadgeColor(affiliate.category)}
                          >
                            {capitalizeWords(affiliate.category)}
                          </Badge>
                        </div>
                      </div>
                    </div>

                    <div className="mt-4 grid grid-cols-2 border-t border-gray-200 divide-x divide-gray-200">
                      <div className="p-2">
                        <span className="text-slate-500 font-medium text-sm">
                          Sales Volume
                        </span>
                        <p className="text-xl font-extrabold">
                          {affiliate.current_month_sales_volume}
                        </p>
                      </div>

                      <div className="p-2">
                        <span className="text-slate-500 font-medium text-sm block mb-1">
                          Total Sales
                        </span>
                        <p className="text-xl font-extrabold">
                          {formatIDR(affiliate.current_month_total_sales)}
                        </p>
                      </div>
                    </div>
                  </Card>
                ))}
          </div>

          {/* Full Leaderboard Table */}
          <div className="overflow-x-auto max-w-7xl mx-auto">
            <Table theme={tableTheme.table} hoverable>
              <TableHead>
                <TableRow>
                  <TableHeadCell className="text-nowrap p-4">
                    Rank
                  </TableHeadCell>
                  <TableHeadCell className="text-nowrap p-4">
                    Partner Name
                  </TableHeadCell>
                  <TableHeadCell className="text-nowrap p-4 text-center">
                    Category
                  </TableHeadCell>
                  <TableHeadCell className="text-nowrap p-4 text-right">
                    Sales Volume
                  </TableHeadCell>
                  <TableHeadCell className="text-nowrap p-4 text-right">
                    Total Sales
                  </TableHeadCell>
                </TableRow>
              </TableHead>

              <TableBody className="divide-y divide-gray-200">
                {isLoading
                  ? Array.from({ length: 6 }).map((_, idx) => (
                      <TableRow
                        key={`sk-${idx}`}
                        className="bg-white animate-pulse"
                      >
                        <TableCell className="p-4">
                          <div className="h-4 w-8 bg-slate-200 rounded" />
                        </TableCell>
                        <TableCell className="p-4">
                          <div className="flex items-center gap-3">
                            <div className="w-8 h-8 rounded-full bg-slate-200" />
                            <div className="h-4 w-32 bg-slate-200 rounded" />
                          </div>
                        </TableCell>
                        <TableCell className="p-4 text-right">
                          <div className="h-4 w-12 bg-slate-200 rounded ml-auto" />
                        </TableCell>
                        <TableCell className="p-4 text-right">
                          <div className="h-4 w-28 bg-slate-200 rounded ml-auto" />
                        </TableCell>
                        <TableCell className="p-4 text-right">
                          <div className="h-4 w-12 bg-slate-200 rounded ml-auto" />
                        </TableCell>
                      </TableRow>
                    ))
                  : affiliateLeaderboards?.data.map((affiliate, idx) => (
                      <TableRow key={affiliate.id} className="bg-white">
                        {/* Rank */}
                        <TableCell className="p-4">
                          <div className="flex items-center gap-2">
                            <span>
                              {(currentPage - 1) *
                                affiliateLeaderboards.per_page +
                                idx +
                                1}
                            </span>
                          </div>
                        </TableCell>

                        {/* Partner Name */}
                        <TableCell className="p-4 text-nowrap">
                          <div className="flex items-center gap-3">
                            <Avatar
                              theme={{
                                ...avatarTheme,
                                root: {
                                  ...avatarTheme.root,
                                  inner: `${avatarTheme.root.inner} h-8 w-8`,
                                },
                              }}
                              alt={`${affiliate.name} Avatar`}
                              img={`https://api.dicebear.com/9.x/initials/svg?seed=${affiliate.name}&backgroundType=gradientLinear`}
                              rounded
                              size="sm"
                              className="w-fit"
                            />
                            <span className="font-medium text-black">
                              {affiliate.partner_name}
                            </span>
                          </div>
                        </TableCell>

                        {/* Category */}
                        <TableCell className="p-4 text-center">
                          <Badge
                            className="w-fit mx-auto"
                            theme={badgeTheme.badge}
                            color={getCategoryBadgeColor(affiliate.category)}
                          >
                            {capitalizeWords(affiliate.category)}
                          </Badge>
                        </TableCell>

                        {/* Current Month Sales Volume */}
                        <TableCell className="p-4 text-right text-nowrap">
                          <div>{affiliate.current_month_sales_volume}</div>
                          <div className="flex justify-end">
                            <GrowthIndicator
                              value={affiliate.sales_volume_growth}
                              label="vs last month"
                            />
                          </div>
                        </TableCell>

                        {/* Current Month Total Sales */}
                        <TableCell className="p-4 text-right text-nowrap">
                          <div>
                            {formatIDR(affiliate.current_month_total_sales)}
                          </div>
                          <div className="flex justify-end">
                            <GrowthIndicator
                              value={affiliate.total_sales_growth}
                              label="vs last month"
                            />
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
              </TableBody>
            </Table>
          </div>

          {/* Pagination */}
          <div className="max-w-7xl mx-auto">
            <PaginationComponent
              from={affiliateLeaderboards.from}
              to={affiliateLeaderboards.to}
              total={affiliateLeaderboards.total}
              currentPage={currentPage}
              lastPage={affiliateLeaderboards.last_page}
              limit={limit}
              handleLimitChange={handleLimitChange}
              handlePageChange={handlePageChange}
            />
          </div>
        </div>
      </section>
    </React.Fragment>
  )
}
