import { useState } from 'react';
import { Toaster } from '@/components/ui/sonner';
import { CodeEditor } from '@/components/CodeEditor';
import { AIChat } from '@/components/AIChat';
import { Toolbar } from '@/components/Toolbar';
import { TemplatesDrawer } from '@/components/TemplatesDrawer';
import { WelcomeDialog } from '@/components/WelcomeDialog';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import { useKV } from '@github/spark/hooks';
import { useIsMobile } from '@/hooks/use-mobile';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

function App() {
  const [currentCode, setCurrentCode] = useState('');
  const [showTemplates, setShowTemplates] = useState(false);
  const [code, setCode] = useKV('aethex-current-code', '');
  const isMobile = useIsMobile();

  const handleTemplateSelect = (templateCode: string) => {
    setCode(templateCode);
    setCurrentCode(templateCode);
  };

  return (
    <div className="h-screen flex flex-col bg-background text-foreground">
      <Toolbar code={currentCode} onTemplatesClick={() => setShowTemplates(true)} />

      <div className="flex-1 overflow-hidden">
        {isMobile ? (
          <Tabs defaultValue="editor" className="h-full flex flex-col">
            <TabsList className="w-full rounded-none border-b border-border">
              <TabsTrigger value="editor" className="flex-1">Editor</TabsTrigger>
              <TabsTrigger value="ai" className="flex-1">AI Assistant</TabsTrigger>
            </TabsList>
            <TabsContent value="editor" className="flex-1 m-0">
              <CodeEditor onCodeChange={setCurrentCode} />
            </TabsContent>
            <TabsContent value="ai" className="flex-1 m-0">
              <AIChat currentCode={currentCode} />
            </TabsContent>
          </Tabs>
        ) : (
          <ResizablePanelGroup direction="horizontal">
            <ResizablePanel defaultSize={60} minSize={30}>
              <CodeEditor onCodeChange={setCurrentCode} />
            </ResizablePanel>

            <ResizableHandle className="w-1 bg-border hover:bg-accent transition-colors" />

            <ResizablePanel defaultSize={40} minSize={25}>
              <AIChat currentCode={currentCode} />
            </ResizablePanel>
          </ResizablePanelGroup>
        )}
      </div>

      {showTemplates && (
        <TemplatesDrawer
          onSelectTemplate={handleTemplateSelect}
          onClose={() => setShowTemplates(false)}
        />
      )}

      <WelcomeDialog />
      <Toaster position="bottom-right" theme="dark" />
    </div>
  );
}

export default App;