import { 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 { paginationDefaultData } from '@/lib/data/pagination'
import { useAuth } from '@/lib/context/AuthContext'
import { getLeaderboards } from '@/lib/services/merchant-services'
import tableTheme from '@/lib/themes/table'
import { formatIDR } from '@/lib/utils/currency'
import badgeTheme from '@/lib/themes/badge'
import { MerchantLeaderboard as MerchantLeaderboardTypes } from '../merchants/types'
import { getKualaLumpurDate, parseKualaLumpurDate } from '@/lib/utils/date'
import Pagination from '@/lib/components/Pagination'
import GrowthIndicator from '@/lib/components/GrowthIndicator'

interface MerchantLeaderboardProps {
  date?: DateType
}

export default function MerchantLeaderboard({
  date,
}: MerchantLeaderboardProps) {
  const { user } = useAuth()
  const [isLoading, setIsLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [limit, setLimit] = useState(10)
  const [merchantLeaderboards, setMerchantLeaderboards] = useState<
    Pagination<MerchantLeaderboardTypes>
  >(paginationDefaultData)
  const [topMerchants, setTopMerchants] = useState<MerchantLeaderboardTypes[]>(
    [],
  )

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

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

      try {
        const leaderBoards = await getLeaderboards({
          date,
          page: currentPage,
          limit,
        })
        const topMerchants = await getLeaderboards({
          date,
          page: 1,
          limit: 3,
        })

        setMerchantLeaderboards(leaderBoards)
        setTopMerchants(topMerchants.data.slice(0, 3))
      } catch (error) {
        console.error('Error fetching merchant leaderboards:', error)
      } finally {
        setIsLoading(false)
      }
    }

    fetchMerchantLeaderboards(
      date
        ? format(getKualaLumpurDate(date), 'yyyy-MM-dd')
        : format(parseKualaLumpurDate(), 'yyyy-MM-dd'),
    )
  }, [user, currentPage, date, limit])

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

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

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

  return (
    <section className="mt-16">
      <h2 className="text-2xl font-semibold mb-6">Top Performing Merchants</h2>

      <div className="space-y-8">
        {/* Top 3 Merchants */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-7xl">
          {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-6 w-20 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>
              ))
            : topMerchants.map((merchant, idx) => (
                <Card key={merchant.id} className="shadow-none h-fit">
                  <div className="flex items-center gap-4">
                    <Avatar
                      alt={`${merchant.name} Avatar`}
                      img={`https://api.dicebear.com/9.x/initials/svg?seed=${merchant.name}&backgroundType=gradientLinear`}
                      rounded
                      size="md"
                    />
                    <div>
                      <h3 className="font-semibold text-base">
                        {merchant.name}
                      </h3>
                      <Badge
                        className="w-fit mt-1"
                        theme={badgeTheme.badge}
                        color={getBadgeColor(idx + 1)}
                      >
                        Rank #{idx + 1}
                      </Badge>
                    </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">
                        Total Orders
                      </span>
                      <p className="text-xl font-extrabold">
                        {merchant.total_orders}
                      </p>
                    </div>

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

        {/* Remaining Merchants Table */}
        <div className="overflow-x-auto hidden lg:block">
          <Table theme={tableTheme.table} hoverable>
            <TableHead>
              <TableRow>
                <TableHeadCell className="text-nowrap p-4">Rank</TableHeadCell>
                <TableHeadCell className="text-nowrap p-4">
                  Merchant
                </TableHeadCell>
                <TableHeadCell className="text-nowrap p-4 text-right">
                  Total Orders
                </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-16 bg-slate-200 rounded ml-auto" />
                      </TableCell>
                      <TableCell className="p-4 text-right">
                        <div className="flex flex-col items-end gap-1">
                          <div className="h-4 w-32 bg-slate-200 rounded" />
                          <div className="h-3 w-24 bg-slate-200 rounded" />
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                : merchantLeaderboards?.data.map((merchant, idx) => (
                    <TableRow key={merchant.id} className="bg-white">
                      <TableCell className="p-4">
                        <div className="flex items-center gap-2">
                          <span>
                            {(currentPage - 1) * merchantLeaderboards.per_page +
                              idx +
                              1}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell className="p-4 text-nowrap">
                        <div className="flex items-center gap-3">
                          <Avatar
                            alt={`${merchant.name} Avatar`}
                            img={`https://api.dicebear.com/9.x/initials/svg?seed=${merchant.name}&backgroundType=gradientLinear`}
                            rounded
                            size="sm"
                          />
                          <span className="font-medium">{merchant.name}</span>
                        </div>
                      </TableCell>
                      <TableCell className="p-4 text-right">
                        {merchant.total_orders}
                      </TableCell>
                      <TableCell className="p-4 text-right text-nowrap">
                        <div>{formatIDR(merchant.current_month_sales)}</div>
                        <div className="flex justify-end">
                          <GrowthIndicator
                            value={merchant.sales_growth}
                            label="vs last month"
                          />
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
            </TableBody>
          </Table>
        </div>

        {/* Pagination */}
        <Pagination
          from={merchantLeaderboards.from}
          to={merchantLeaderboards.to}
          total={merchantLeaderboards.total}
          currentPage={currentPage}
          lastPage={merchantLeaderboards.last_page}
          limit={limit}
          handleLimitChange={handleLimitChange}
          handlePageChange={handlePageChange}
        />
      </div>
    </section>
  )
}
