import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import config from "@/config"
import { formatCurrency } from "@/utils/formatCurrency"

interface Product {
  pid: number;
  sku: string;
  title: string;
  units_sold: number;
  revenue: string;
  profit: string;
}

interface Category {
  cat_id: number;
  name: string;
  categoryPath: string;
  units_sold: number;
  revenue: string;
  profit: string;
}

interface BestSellerBrand {
  brand: string
  units_sold: number
  revenue: string
  profit: string
  growth_rate: string
}

interface BestSellersData {
  products: Product[]
  brands: BestSellerBrand[]
  categories: Category[]
}

function TableSkeleton() {
  return (
    <div className="space-y-3 p-4">
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="h-8 animate-pulse rounded bg-muted" />
      ))}
    </div>
  );
}

export function BestSellers() {
  const { data, isError, isLoading } = useQuery<BestSellersData>({
    queryKey: ["best-sellers"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/best-sellers`)
      if (!response.ok) throw new Error("Failed to fetch best sellers");
      return response.json()
    },
  })

  return (
    <>
      <Tabs defaultValue="products">
        <CardHeader>
          <div className="flex flex-row items-center justify-between">
            <CardTitle className="text-lg font-medium">Best Sellers</CardTitle>
            <TabsList>
              <TabsTrigger value="products">Products</TabsTrigger>
              <TabsTrigger value="brands">Brands</TabsTrigger>
              <TabsTrigger value="categories">Categories</TabsTrigger>
            </TabsList>
          </div>
        </CardHeader>
        <CardContent>
          {isError ? (
            <p className="text-sm text-destructive">Failed to load best sellers</p>
          ) : isLoading ? (
            <TableSkeleton />
          ) : (
            <>
              <TabsContent value="products">
                <ScrollArea className="h-[420px] w-full">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Product</TableHead>
                        <TableHead className="text-right">Units Sold</TableHead>
                        <TableHead className="text-right">Revenue</TableHead>
                        <TableHead className="text-right">Profit</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data?.products.map((product) => (
                        <TableRow key={product.pid}>
                          <TableCell>
                            <a
                              href={`https://backend.acherryontop.com/product/${product.pid}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="hover:underline"
                            >
                              {product.title}
                            </a>
                            <div className="text-sm text-muted-foreground">{product.sku}</div>
                          </TableCell>
                          <TableCell className="text-right">{product.units_sold}</TableCell>
                          <TableCell className="text-right">{formatCurrency(Number(product.revenue))}</TableCell>
                          <TableCell className="text-right">{formatCurrency(Number(product.profit))}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </ScrollArea>
              </TabsContent>

              <TabsContent value="brands">
                <ScrollArea className="h-[400px] w-full">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[40%]">Brand</TableHead>
                        <TableHead className="w-[15%] text-right">Sales</TableHead>
                        <TableHead className="w-[15%] text-right">Revenue</TableHead>
                        <TableHead className="w-[15%] text-right">Profit</TableHead>
                        <TableHead className="w-[15%] text-right">Growth</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data?.brands.map((brand) => (
                        <TableRow key={brand.brand}>
                          <TableCell className="w-[40%]">
                            <p className="font-medium">{brand.brand}</p>
                          </TableCell>
                          <TableCell className="w-[15%] text-right">
                            {brand.units_sold.toLocaleString()}
                          </TableCell>
                          <TableCell className="w-[15%] text-right">
                            {formatCurrency(Number(brand.revenue))}
                          </TableCell>
                          <TableCell className="w-[15%] text-right">
                            {formatCurrency(Number(brand.profit))}
                          </TableCell>
                          <TableCell className="w-[15%] text-right">
                            {brand.growth_rate != null ? (
                              <>{Number(brand.growth_rate) > 0 ? '+' : ''}{Number(brand.growth_rate).toFixed(1)}%</>
                            ) : '-'}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </ScrollArea>
              </TabsContent>

              <TabsContent value="categories">
                <ScrollArea className="h-[400px] w-full">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Category</TableHead>
                        <TableHead className="text-right">Units Sold</TableHead>
                        <TableHead className="text-right">Revenue</TableHead>
                        <TableHead className="text-right">Profit</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data?.categories.map((category) => (
                        <TableRow key={category.cat_id}>
                          <TableCell>
                            <div className="font-medium">{category.name}</div>
                            {category.categoryPath && (
                              <div className="text-sm text-muted-foreground">
                                {category.categoryPath}
                              </div>
                            )}
                          </TableCell>
                          <TableCell className="text-right">{category.units_sold}</TableCell>
                          <TableCell className="text-right">{formatCurrency(Number(category.revenue))}</TableCell>
                          <TableCell className="text-right">{formatCurrency(Number(category.profit))}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </ScrollArea>
              </TabsContent>
            </>
          )}
        </CardContent>
      </Tabs>
    </>
  )
}
