import { CircleAlertIcon } from 'lucide-react'
import { Alert, AlertDescription, AlertTitle } from '@cfdm/ui/components/alert'
import { Button } from '@cfdm/ui/components/button'
import { Skeleton } from '@cfdm/ui/components/skeleton'

interface QueryStateProps {
  isLoading?: boolean
  isError?: boolean
  error?: Error | null
  onRetry?: () => void
  skeleton?: React.ReactNode
  children: React.ReactNode
}

function DefaultSkeleton() {
  return (
    <div className="flex flex-col gap-4">
      <Skeleton className="h-8 w-1/3" />
      <Skeleton className="h-40 w-full" />
      <Skeleton className="h-40 w-full" />
    </div>
  )
}

export function QueryState({
  isLoading,
  isError,
  error,
  onRetry,
  skeleton,
  children,
}: QueryStateProps) {
  if (isLoading) {
    return skeleton ?? <DefaultSkeleton />
  }

  if (isError) {
    return (
      <Alert variant="destructive">
        <CircleAlertIcon />
        <AlertTitle>Не удалось загрузить данные</AlertTitle>
        <AlertDescription>
          {error?.message ?? 'Произошла ошибка при загрузке.'}
        </AlertDescription>
        {onRetry && (
          <Button
            variant="outline"
            size="sm"
            className="mt-2"
            onClick={onRetry}
          >
            Повторить
          </Button>
        )}
      </Alert>
    )
  }

  return children
}
