"use client"

import { useEffect, useState } from "react"
import { useDuplicates, useResolveDuplicate } from "@/hooks/use-duplicates"
import { getTokens } from "@/lib/auth"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Spinner } from "@/components/ui/spinner"
import { toast } from "sonner"

function AssetThumb({ assetId }: { assetId: string }) {
  const [src, setSrc] = useState<string | null>(null)

  useEffect(() => {
    let revoke: string | null = null
    const { access } = getTokens()
    const headers: HeadersInit = access ? { Authorization: `Bearer ${access}` } : {}
    fetch(`/api/v1/assets/${assetId}/derivatives/thumbnail_square`, { headers })
      .then((r) => (r.ok ? r.blob() : Promise.reject()))
      .catch(() =>
        fetch(`/api/v1/assets/${assetId}/file`, { headers }).then((r) =>
          r.ok ? r.blob() : Promise.reject(),
        ),
      )
      .then((blob) => {
        revoke = URL.createObjectURL(blob)
        setSrc(revoke)
      })
      .catch(() => {})
    return () => {
      if (revoke) URL.revokeObjectURL(revoke)
    }
  }, [assetId])

  return src ? (
    <img
      src={src}
      alt=""
      className="h-20 w-20 shrink-0 rounded object-cover"
    />
  ) : (
    <Skeleton className="h-20 w-20 shrink-0 rounded" />
  )
}

export default function DuplicatesPage() {
  const { data: groups, isLoading } = useDuplicates()
  const resolve = useResolveDuplicate()

  return (
    <div className="flex flex-col gap-4">
      <h1 className="text-lg font-semibold">Duplicate Resolution</h1>

      {isLoading ? (
        <Spinner />
      ) : (groups ?? []).length === 0 ? (
        <p className="text-sm text-muted-foreground">
          No duplicate groups found.
        </p>
      ) : (
        (groups ?? []).map((group) => (
          <Card key={group.group_id}>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-sm">
                <span className="font-mono">
                  {group.group_id.slice(0, 8)}...
                </span>
                <Badge variant="secondary">{group.detection_method}</Badge>
                <Badge
                  variant={
                    group.status === "Pending" ? "default" : "secondary"
                  }
                >
                  {group.status}
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                {group.candidates.map((c) => (
                  <div
                    key={c.asset_id}
                    className="flex gap-3 rounded border p-2"
                  >
                    <AssetThumb assetId={c.asset_id} />
                    <div className="flex flex-1 flex-col justify-between">
                      <div>
                        <p className="font-mono text-xs">
                          {c.asset_id.slice(0, 12)}...
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {(c.similarity_score * 100).toFixed(1)}% match
                        </p>
                      </div>
                      <Button
                        size="sm"
                        variant="outline"
                        className="h-6 self-start text-xs"
                        disabled={resolve.isPending}
                        onClick={async () => {
                          try {
                            await resolve.mutateAsync({
                              groupId: group.group_id,
                              keepAssetId: c.asset_id,
                            })
                            toast.success("Resolved — kept this asset")
                          } catch {
                            toast.error("Failed to resolve")
                          }
                        }}
                      >
                        Keep
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        ))
      )}
    </div>
  )
}
