'use client';

import { useState, lazy, Suspense } from 'react';
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from '@/components/ui/resizable';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Play,
  Square,
  Pause,
  RotateCcw,
  Settings,
  Maximize2,
  Minimize2,
  Eye,
  EyeOff,
  Grid3X3,
  Box,
  Sun,
  Terminal,
  Loader2,
} from 'lucide-react';

import { usePreviewStore } from '@/stores/preview-store';
import PreviewConsole from './PreviewConsole';

// Lazy load the 3D viewport
const PreviewViewport = lazy(() => import('./PreviewViewport'));

interface LivePreviewProps {
  code: string;
  onClose?: () => void;
}

export default function LivePreview({ code, onClose }: LivePreviewProps) {
  const {
    isRunning,
    isPaused,
    settings,
    updateSettings,
    runScript,
    stopScript,
    pauseScript,
    resumeScript,
    resetScene,
    scene,
  } = usePreviewStore();

  const [isFullscreen, setIsFullscreen] = useState(false);
  const [showConsole, setShowConsole] = useState(true);

  const handleRun = async () => {
    await runScript(code);
  };

  const handleStop = () => {
    stopScript();
  };

  const handleReset = () => {
    resetScene();
  };

  return (
    <div
      className={`flex flex-col bg-background ${
        isFullscreen ? 'fixed inset-0 z-50' : 'h-full'
      }`}
    >
      {/* Toolbar */}
      <div className="flex items-center justify-between px-3 py-2 border-b bg-card">
        <div className="flex items-center gap-2">
          <span className="font-semibold text-sm">Live Preview</span>
          <Badge variant="secondary" className="text-xs">
            Beta
          </Badge>
        </div>

        <div className="flex items-center gap-1">
          {/* Run controls */}
          {!isRunning ? (
            <Button
              variant="default"
              size="sm"
              onClick={handleRun}
              className="h-8 px-3 gap-1"
            >
              <Play className="h-4 w-4" />
              Run
            </Button>
          ) : (
            <>
              <Button
                variant="outline"
                size="sm"
                onClick={isPaused ? resumeScript : pauseScript}
                className="h-8 px-3 gap-1"
              >
                {isPaused ? (
                  <>
                    <Play className="h-4 w-4" />
                    Resume
                  </>
                ) : (
                  <>
                    <Pause className="h-4 w-4" />
                    Pause
                  </>
                )}
              </Button>
              <Button
                variant="destructive"
                size="sm"
                onClick={handleStop}
                className="h-8 px-3 gap-1"
              >
                <Square className="h-4 w-4" />
                Stop
              </Button>
            </>
          )}

          <Button
            variant="outline"
            size="sm"
            onClick={handleReset}
            className="h-8 px-3 gap-1"
          >
            <RotateCcw className="h-4 w-4" />
            Reset
          </Button>

          <Separator orientation="vertical" className="h-6 mx-1" />

          {/* View toggles */}
          <Button
            variant={showConsole ? 'secondary' : 'ghost'}
            size="icon"
            className="h-8 w-8"
            onClick={() => setShowConsole(!showConsole)}
            title={showConsole ? 'Hide Console' : 'Show Console'}
          >
            <Terminal className="h-4 w-4" />
          </Button>

          {/* Settings popover */}
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="ghost" size="icon" className="h-8 w-8">
                <Settings className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-64" align="end">
              <div className="space-y-4">
                <h4 className="font-medium text-sm">Preview Settings</h4>

                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="showGrid" className="text-xs flex items-center gap-2">
                      <Grid3X3 className="h-3 w-3" />
                      Show Grid
                    </Label>
                    <Switch
                      id="showGrid"
                      checked={settings.showGrid}
                      onCheckedChange={(checked) =>
                        updateSettings({ showGrid: checked })
                      }
                    />
                  </div>

                  <div className="flex items-center justify-between">
                    <Label htmlFor="showAxes" className="text-xs flex items-center gap-2">
                      <Box className="h-3 w-3" />
                      Show Axes
                    </Label>
                    <Switch
                      id="showAxes"
                      checked={settings.showAxes}
                      onCheckedChange={(checked) =>
                        updateSettings({ showAxes: checked })
                      }
                    />
                  </div>

                  <div className="flex items-center justify-between">
                    <Label htmlFor="shadows" className="text-xs flex items-center gap-2">
                      <Sun className="h-3 w-3" />
                      Shadows
                    </Label>
                    <Switch
                      id="shadows"
                      checked={settings.shadowsEnabled}
                      onCheckedChange={(checked) =>
                        updateSettings({ shadowsEnabled: checked })
                      }
                    />
                  </div>

                  <div className="flex items-center justify-between">
                    <Label htmlFor="wireframe" className="text-xs flex items-center gap-2">
                      <Eye className="h-3 w-3" />
                      Wireframe
                    </Label>
                    <Switch
                      id="wireframe"
                      checked={settings.showWireframe}
                      onCheckedChange={(checked) =>
                        updateSettings({ showWireframe: checked })
                      }
                    />
                  </div>

                  <div className="flex items-center justify-between">
                    <Label htmlFor="stats" className="text-xs">
                      Show Stats
                    </Label>
                    <Switch
                      id="stats"
                      checked={settings.showStats}
                      onCheckedChange={(checked) =>
                        updateSettings({ showStats: checked })
                      }
                    />
                  </div>

                  <div className="flex items-center justify-between">
                    <Label htmlFor="autoRotate" className="text-xs">
                      Auto Rotate
                    </Label>
                    <Switch
                      id="autoRotate"
                      checked={settings.autoRotate}
                      onCheckedChange={(checked) =>
                        updateSettings({ autoRotate: checked })
                      }
                    />
                  </div>

                  <Separator />

                  <div className="space-y-2">
                    <Label className="text-xs">Background</Label>
                    <Select
                      value={settings.backgroundColor}
                      onValueChange={(value) =>
                        updateSettings({ backgroundColor: value })
                      }
                    >
                      <SelectTrigger className="h-8 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="#1a1a2e">Dark Blue</SelectItem>
                        <SelectItem value="#0d0d0d">Black</SelectItem>
                        <SelectItem value="#1a1a1a">Dark Gray</SelectItem>
                        <SelectItem value="#2d2d44">Slate</SelectItem>
                        <SelectItem value="#87ceeb">Sky Blue</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            </PopoverContent>
          </Popover>

          {/* Fullscreen toggle */}
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8"
            onClick={() => setIsFullscreen(!isFullscreen)}
          >
            {isFullscreen ? (
              <Minimize2 className="h-4 w-4" />
            ) : (
              <Maximize2 className="h-4 w-4" />
            )}
          </Button>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 min-h-0">
        <ResizablePanelGroup direction="vertical">
          {/* 3D Viewport */}
          <ResizablePanel defaultSize={showConsole ? 70 : 100} minSize={30}>
            <div className="relative h-full">
              <Suspense
                fallback={
                  <div className="flex items-center justify-center h-full bg-muted/50">
                    <div className="flex flex-col items-center gap-2">
                      <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                      <span className="text-sm text-muted-foreground">
                        Loading 3D viewport...
                      </span>
                    </div>
                  </div>
                }
              >
                <PreviewViewport />
              </Suspense>

              {/* Running indicator */}
              {isRunning && (
                <div className="absolute top-3 left-3">
                  <Badge
                    variant="default"
                    className={`gap-1 ${isPaused ? 'bg-yellow-500' : 'bg-green-500'}`}
                  >
                    <span
                      className={`w-2 h-2 rounded-full ${
                        isPaused ? 'bg-yellow-300' : 'bg-green-300 animate-pulse'
                      }`}
                    />
                    {isPaused ? 'Paused' : 'Running'}
                  </Badge>
                </div>
              )}

              {/* Instance count */}
              <div className="absolute bottom-3 left-3">
                <Badge variant="secondary" className="text-xs">
                  {scene.instances.length} objects
                </Badge>
              </div>
            </div>
          </ResizablePanel>

          {/* Console */}
          {showConsole && (
            <>
              <ResizableHandle withHandle />
              <ResizablePanel defaultSize={30} minSize={15} maxSize={50}>
                <PreviewConsole />
              </ResizablePanel>
            </>
          )}
        </ResizablePanelGroup>
      </div>
    </div>
  );
}
