import { Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet'
import { StatusBadge, type StatusTone } from './status-badge'

export type DetailField = {
  label: React.ReactNode
  value: React.ReactNode
  wide?: boolean
}

export type DetailSection = {
  title: React.ReactNode
  description?: React.ReactNode
  fields?: DetailField[]
  content?: React.ReactNode
}

export type DetailAction = {
  label: React.ReactNode
  icon?: React.ElementType
  variant?: React.ComponentProps<typeof Button>['variant']
  onClick: () => void
  disabled?: boolean
}

type EntityDetailSheetProps = {
  open: boolean
  onOpenChange: (open: boolean) => void
  title: React.ReactNode
  description?: React.ReactNode
  status?: {
    label: React.ReactNode
    tone?: StatusTone
  }
  meta?: React.ReactNode
  sections: DetailSection[]
  actions?: DetailAction[]
  isLoading?: boolean
  className?: string
}

function renderValue(value: React.ReactNode) {
  if (value === null || value === undefined || value === '') {
    return <span className='text-muted-foreground'>-</span>
  }

  return value
}

export function EntityDetailSheet({
  open,
  onOpenChange,
  title,
  description,
  status,
  meta,
  sections,
  actions,
  isLoading,
  className,
}: EntityDetailSheetProps) {
  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        className={cn(
          'w-[calc(100vw-1rem)] max-w-none gap-0 overflow-hidden p-0 sm:w-[min(92vw,960px)] sm:max-w-none lg:w-[min(86vw,1040px)]',
          className
        )}
      >
        <SheetHeader className='border-b bg-muted/30 px-6 py-5'>
          <div className='flex items-start justify-between gap-4 pe-8'>
            <div className='min-w-0 space-y-2'>
              <SheetTitle className='truncate text-xl'>{title}</SheetTitle>
              {description && (
                <SheetDescription className='line-clamp-2 leading-6 [overflow-wrap:anywhere] break-all'>
                  {description}
                </SheetDescription>
              )}
            </div>
            {status && <StatusBadge label={status.label} tone={status.tone} />}
          </div>
          {meta && (
            <div className='text-xs [overflow-wrap:anywhere] break-all text-muted-foreground'>
              {meta}
            </div>
          )}
        </SheetHeader>

        <ScrollArea className='min-h-0 min-w-0 flex-1 overflow-x-hidden'>
          <div className='min-w-0 space-y-5 px-6 py-5'>
            {isLoading ? (
              <div className='flex h-48 items-center justify-center gap-2 text-sm text-muted-foreground'>
                <Loader2 className='size-4 animate-spin' />
                Loading details...
              </div>
            ) : (
              sections.map((section, index) => (
                <section
                  key={index}
                  className='min-w-0 overflow-hidden rounded-lg border bg-card/60 p-4 shadow-xs'
                >
                  <div className='mb-3 min-w-0 space-y-1'>
                    <h3 className='text-sm font-semibold'>{section.title}</h3>
                    {section.description && (
                      <p className='text-xs leading-5 [overflow-wrap:anywhere] break-all text-muted-foreground'>
                        {section.description}
                      </p>
                    )}
                  </div>
                  {section.fields && (
                    <dl className='grid min-w-0 gap-3 sm:grid-cols-2'>
                      {section.fields.map((field, fieldIndex) => (
                        <div
                          key={fieldIndex}
                          className={cn(
                            'min-w-0 overflow-hidden rounded-md bg-muted/35 px-3 py-2.5',
                            field.wide && 'sm:col-span-2'
                          )}
                        >
                          <dt className='text-xs text-muted-foreground'>
                            {field.label}
                          </dt>
                          <dd className='mt-1 min-w-0 text-sm leading-6 font-medium [overflow-wrap:anywhere] break-all whitespace-pre-wrap'>
                            {renderValue(field.value)}
                          </dd>
                        </div>
                      ))}
                    </dl>
                  )}
                  {section.content && (
                    <div className='min-w-0 overflow-x-auto'>
                      {section.content}
                    </div>
                  )}
                </section>
              ))
            )}
          </div>
        </ScrollArea>

        {actions && actions.length > 0 && (
          <SheetFooter className='border-t bg-background px-6 py-4 sm:flex-row sm:justify-end'>
            {actions.map((action, index) => {
              const Icon = action.icon
              return (
                <Button
                  key={index}
                  type='button'
                  variant={action.variant ?? 'outline'}
                  disabled={action.disabled}
                  onClick={action.onClick}
                >
                  {Icon && <Icon className='size-4' />}
                  {action.label}
                </Button>
              )
            })}
          </SheetFooter>
        )}
      </SheetContent>
    </Sheet>
  )
}
