import { Search } from 'lucide-react'
import { useScriptGeneratorStore } from '@/store/scriptGeneratorStore'
import { EmptyState } from '@/components/common/EmptyState'
import { ScriptIllustration } from '@/components/common/EmptyStateIllustrations'
import { TemplateCard } from './TemplateCard'

interface Props {
  inputValue: string
  onClearSearch: () => void
  onConfigure: (id: string) => void
}

function TemplateSkeleton() {
  return (
    <div className="px-4 py-3 rounded-xl border border-border animate-pulse">
      <div className="flex justify-between mb-2">
        <div className="h-4 w-2/3 bg-white/10 rounded" />
        <div className="h-4 w-14 bg-white/10 rounded" />
      </div>
      <div className="h-3 w-full bg-white/5 rounded mb-1" />
      <div className="h-3 w-3/4 bg-white/5 rounded" />
    </div>
  )
}

export function ScriptTemplateList({ inputValue, onClearSearch, onConfigure }: Props) {
  const templates = useScriptGeneratorStore(s => s.templates)
  const isLoadingTemplates = useScriptGeneratorStore(s => s.isLoadingTemplates)

  if (isLoadingTemplates) {
    return (
      <div className="flex flex-col gap-2 p-2">
        <TemplateSkeleton />
        <TemplateSkeleton />
        <TemplateSkeleton />
      </div>
    )
  }

  if (templates.length === 0) {
    if (inputValue !== '') {
      return (
        <div className="flex flex-col items-center justify-center gap-3 py-12 text-center px-4">
          <Search size={32} className="text-muted-foreground/40" />
          <p className="text-sm text-muted-foreground">No templates match your search</p>
          <button
            type="button"
            onClick={onClearSearch}
            className="text-xs text-primary hover:underline"
          >
            Clear search
          </button>
        </div>
      )
    }
    return (
      <EmptyState
        illustration={<ScriptIllustration />}
        title="Automate with script templates"
        description="Pre-built and custom scripts your team can reference during sessions. PowerShell, bash, and more."
        learnMoreLink="/guides/script-templates"
        className="px-4"
      />
    )
  }

  return (
    <div className="flex flex-col gap-2 p-2">
      {templates.map(template => (
        <TemplateCard key={template.id} template={template} onConfigure={onConfigure} />
      ))}
    </div>
  )
}
