'use client'

import * as React from 'react'
import type { DevModeCodeLanguage, DevModeSnippetCodeTab } from './dev-mode-types'
import { Button } from '@admin/components/ui/button'
import { Card, CardContent, CardHeader } from '@admin/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@admin/components/ui/tabs'
import { useCopyToClipboard } from '@admin/hooks/use-copy-to-clipboard'
import { Check, Copy } from 'lucide-react'
import { PlainCodeFallback } from './plain-code-fallback'

const LazyCodeMirror = React.lazy(() => import('./dev-mode-code-mirror'))

interface CopyableCodeBlockProps {
  label: string
  code: string
  language: DevModeCodeLanguage
  tabs?: DevModeSnippetCodeTab[]
}

export function CopyableCodeBlock({ label, code, language, tabs }: CopyableCodeBlockProps) {
  const [copy, isCopied] = useCopyToClipboard()
  const fallbackTab: DevModeSnippetCodeTab = {
    id: 'code',
    label,
    language,
    code
  }
  const codeTabs = tabs && tabs.length > 0 ? tabs : [fallbackTab]
  const [activeTabId, setActiveTabId] = React.useState(codeTabs[0]?.id ?? fallbackTab.id)
  const activeTab = codeTabs.find((tab) => tab.id === activeTabId) ?? codeTabs[0] ?? fallbackTab
  const hasTabs = codeTabs.length > 1

  return (
    <Card className="flex w-full flex-col gap-0 p-0">
      {hasTabs ? (
        <Tabs value={activeTab.id} onValueChange={setActiveTabId} className="min-h-0 flex-1 gap-0">
          <CardHeader className="flex items-center justify-between gap-2 border-b border-border bg-background pt-[5px]! pr-1 pb-2! pl-3.5!">
            <div className="flex min-w-0 flex-1 items-center gap-2">
              <span className="min-w-0 truncate text-sm font-medium text-muted-foreground">
                {label}
              </span>
              <TabsList className="h-fit! shrink-0">
                {codeTabs.map((tab) => (
                  <TabsTrigger key={tab.id} value={tab.id} className="h-7 px-3 text-xs">
                    {tab.label}
                  </TabsTrigger>
                ))}
              </TabsList>
            </div>
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              aria-label={`Copy ${label} ${activeTab.label}`}
              onClick={() => {
                void copy(activeTab.code)
              }}
            >
              {isCopied ? <Check /> : <Copy />}
            </Button>
          </CardHeader>

          {codeTabs.map((tab) => (
            <TabsContent key={tab.id} value={tab.id} className="min-h-0 overflow-auto">
              <CardContent className="h-full overflow-auto p-0">
                <React.Suspense fallback={<PlainCodeFallback code={tab.code} />}>
                  <LazyCodeMirror code={tab.code} language={tab.language} />
                </React.Suspense>
              </CardContent>
            </TabsContent>
          ))}
        </Tabs>
      ) : (
        <>
          <CardHeader className="flex items-center justify-between gap-2 border-b border-border bg-background pt-[5px]! pr-1 pb-2! pl-3.5!">
            <span className="min-w-0 truncate text-sm font-medium text-muted-foreground">
              {label}
            </span>
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              aria-label={`Copy ${label}`}
              onClick={() => {
                void copy(activeTab.code)
              }}
            >
              {isCopied ? <Check /> : <Copy />}
            </Button>
          </CardHeader>
          <CardContent className="overflow-auto p-0">
            <React.Suspense fallback={<PlainCodeFallback code={code} />}>
              <LazyCodeMirror code={code} language={language} />
            </React.Suspense>
          </CardContent>
        </>
      )}
    </Card>
  )
}
