'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'motion/react'
import { LexiconContent } from '@/app/components'
import type { LexiconSchema, ParsedField } from '@/app/lib/lexicon'
import { FileIcon } from 'lucide-react'

interface LexiconTabConfig {
    nsid: string;
    schema: LexiconSchema;
    fields: ParsedField[];
}

interface TabbedLexiconViewerProps {
    tabs: LexiconTabConfig[];
    allSchemas: Record<string, LexiconSchema>;
}

export function TabbedLexiconViewer({ tabs, allSchemas }: TabbedLexiconViewerProps) {
    const [activeIndex, setActiveIndex] = useState(0)

    if (tabs.length === 0) {
        return null
    }

    const activeTab = tabs[activeIndex]

    return (
        <div className="flex flex-col rounded-2xl border border-border bg-base-200 overflow-hidden">
            {/* Tabs */ }
            <div className="overflow-x-auto border-b border-border">
                <div className="flex">
                { tabs.map((tab, index) => (
                    <button
                        key={ tab.nsid }
                        onClick={ () => setActiveIndex(index) }
                        className="flex items-center gap-2 border-r border-border px-4 py-2.5 last:border-r-0 whitespace-nowrap hover:cursor-pointer"
                    >
                        <FileIcon
                            className={ `size-4 ${ index === activeIndex ? 'text-base-content' : 'text-muted' }` }
                        />
                        <span
                            className={ `text-base leading-snug tracking-tight ${
                                index === activeIndex ? 'font-medium text-base-content' : 'text-muted'
                            }` }
                        >
                            { tab.nsid }
                        </span>
                    </button>
                )) }
                </div>
            </div>

            {/* Content */ }
            <AnimatePresence mode="wait">
                <motion.div
                    key={ activeTab.nsid }
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.2, ease: [0.25, 0.1, 0.25, 1] }}
                >
                    <LexiconContent
                        schema={ activeTab.schema }
                        fields={ activeTab.fields }
                        allSchemas={ allSchemas }
                    />
                </motion.div>
            </AnimatePresence>
        </div>
    )
}
