import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Terminal, Settings, Wand2 } from 'lucide-react'
import { useScriptGeneratorStore } from '@/store/scriptGeneratorStore'
import { usePermissions } from '@/hooks/usePermissions'
import { ScriptFilterBar } from '@/components/scripts/ScriptFilterBar'
import { ScriptTemplateList } from '@/components/scripts/ScriptTemplateList'
import { ScriptConfigurePane } from '@/components/scripts/ScriptConfigurePane'
import { ScriptPreview } from '@/components/scripts/ScriptPreview'

type LibraryTab = 'mine' | 'team'

export default function ScriptLibraryPage() {
  const [paneMode, setPaneMode] = useState<'browse' | 'configure'>('browse')
  // inputValue owned here so it survives Configure ↔ Browse transitions
  const [inputValue, setInputValue] = useState('')
  const [activeTab, setActiveTab] = useState<LibraryTab>('mine')

  const loadCategories = useScriptGeneratorStore(s => s.loadCategories)
  const loadTemplates = useScriptGeneratorStore(s => s.loadTemplates)
  const setSearch = useScriptGeneratorStore(s => s.setSearch)
  const selectTemplate = useScriptGeneratorStore(s => s.selectTemplate)
  const clearOutput = useScriptGeneratorStore(s => s.clearOutput)
  const selectedTemplate = useScriptGeneratorStore(s => s.selectedTemplate)

  const { isEngineer } = usePermissions()
  const canGenerate = isEngineer

  useEffect(() => {
    loadCategories().then(() => {
      const filters = activeTab === 'mine' ? { mine: true } : { shared: true }
      loadTemplates(filters)
    })
  }, [loadCategories, loadTemplates, activeTab])

  const onTabChange = (tab: LibraryTab) => {
    setActiveTab(tab)
    setInputValue('')
    setSearch('')
    setPaneMode('browse')
  }

  const onClearSearch = () => {
    setInputValue('')
    setSearch('')
  }

  const onConfigure = (id: string) => {
    selectTemplate(id)
    setPaneMode('configure')
  }

  const onBack = () => {
    clearOutput()
    setPaneMode('browse')
  }

  const tabClass = (tab: LibraryTab) =>
    tab === activeTab
      ? 'border-b-2 border-primary text-foreground'
      : 'text-muted-foreground hover:text-foreground'

  return (
    <div className="flex flex-col gap-4 p-6 h-full">
      {/* Page header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-heading font-bold text-foreground">Script Library</h1>
          <p className="text-sm text-muted-foreground mt-1">
            Browse PowerShell templates, fill in parameters, and generate ready-to-run scripts.
          </p>
          {isEngineer && (
            <Link
              to="/scripts/manage"
              className="inline-flex items-center gap-1.5 text-xs text-primary bg-primary/10 hover:bg-primary/15 px-2.5 py-1 rounded-full transition-colors mt-2 group"
            >
              <Settings size={12} className="group-hover:rotate-90 transition-transform duration-300" />
              Manage Templates
            </Link>
          )}
        </div>
        <Link
          to="/script-builder"
          className="inline-flex items-center gap-2 bg-gradient-brand text-[#101114] font-semibold rounded-[10px] px-4 py-2 shadow-lg shadow-primary/20 hover:opacity-90 active:scale-[0.97] transition-all"
        >
          <Wand2 size={16} />
          Build a New Script
        </Link>
      </div>

      {/* Tab bar */}
      <div className="flex gap-6 border-b border-border">
        <button
          type="button"
          onClick={() => onTabChange('mine')}
          className={`pb-2 text-sm font-medium transition-colors ${tabClass('mine')}`}
        >
          My Scripts
        </button>
        <button
          type="button"
          onClick={() => onTabChange('team')}
          className={`pb-2 text-sm font-medium transition-colors ${tabClass('team')}`}
        >
          Team Scripts
        </button>
      </div>

      {/* Two-column layout */}
      <div className="grid grid-cols-[320px_1fr] gap-4 flex-1 min-h-0">
        {/* Left pane — Browse or Configure mode */}
        {paneMode === 'browse' ? (
          <div className="glass-card-static flex flex-col overflow-hidden">
            <div className="p-2 pb-0">
              <ScriptFilterBar inputValue={inputValue} setInputValue={setInputValue} />
            </div>
            <div className="flex-1 overflow-y-auto">
              <ScriptTemplateList
                inputValue={inputValue}
                onClearSearch={onClearSearch}
                onConfigure={onConfigure}
              />
            </div>
          </div>
        ) : (
          <ScriptConfigurePane canGenerate={canGenerate} onBack={onBack} />
        )}

        {/* Right pane — read-only ScriptPreview */}
        {selectedTemplate === null ? (
          <div className="glass-card-static h-full flex flex-col items-center justify-center gap-3 text-center p-8">
            <Terminal size={40} className="text-muted-foreground/40" />
            <p className="text-sm text-muted-foreground">Select a template to get started</p>
          </div>
        ) : (
          <div className="glass-card-static h-full overflow-y-auto p-4">
            <ScriptPreview />
          </div>
        )}
      </div>
    </div>
  )
}
