import { useNavigate } from "react-router-dom";
import { ArrowLeft, Glasses, Box, Ruler, FileText, Upload, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useModelStore } from "@/stores/useModelStore";
import { ModelViewerCanvas } from "@/components/three/ModelViewer";
import { ViewerControls } from "@/components/ViewerControls";
import { InspectionChecklist } from "@/components/InspectionChecklist";
import { FineTuningControls } from "@/components/FineTuningControls";
import { MeasurementsList } from "@/components/MeasurementsList";
import { ScreenshotGallery } from "@/components/ScreenshotGallery";
import { ShareButton } from "@/components/ShareButton";
import { CloudLoader } from "@/components/CloudLoader";
import { SceneModelList } from "@/components/SceneModelList";
import { useEffect, useRef, useCallback, useState } from "react";
import { toast } from "sonner";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { getSupportedExtension, convertToGLB, ACCEPTED_EXTENSIONS } from "@/lib/convertToGLB";
import { convertIFCtoGLB } from "@/lib/convertIFC";

const Viewer = () => {
  const navigate = useNavigate();
  const { model, xrSupported, addModel, models, maxModels } = useModelStore();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [converting, setConverting] = useState(false);

  useEffect(() => {
    if (!model) {
      navigate("/");
    }
  }, [model, navigate]);

  const handleFileUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    e.target.value = '';
    if (!file) return;
    if (models.length >= maxModels) {
      toast.error(`Limite de ${maxModels} peças simultâneas atingido`);
      return;
    }
    const ext = getSupportedExtension(file.name);
    if (!ext) {
      toast.error('Formato inválido. Selecione .GLB, .OBJ, .STL ou .IFC');
      return;
    }
    if (ext === 'glb') {
      const url = URL.createObjectURL(file);
      addModel({ fileName: file.name, fileSize: file.size, url });
      toast.success(`"${file.name}" adicionado à cena`);
      return;
    }
    setConverting(true);
    try {
      const buffer = await file.arrayBuffer();
      const result = ext === 'ifc'
        ? await convertIFCtoGLB(buffer, file.name)
        : await convertToGLB(buffer, ext, file.name);
      const url = URL.createObjectURL(result.blob);
      addModel({ fileName: result.fileName, fileSize: result.fileSize, url });
      toast.success(`"${file.name}" convertido e adicionado!`);
    } catch (err) {
      console.error(err);
      toast.error(`Falha ao converter "${file.name}"`);
    } finally {
      setConverting(false);
    }
  }, [addModel, models.length, maxModels]);

  if (!model) return null;

  const handleEnterXR = async () => {
    if (!xrSupported) {
      toast.error("WebXR não é suportado neste navegador. Use o navegador do Meta Quest 3.");
      return;
    }
    navigate("/xr");
  };

  const canAddMore = models.length < maxModels;

  return (
    <div className="flex h-screen flex-col bg-background">
      <input
        ref={fileInputRef}
        type="file"
        accept={ACCEPTED_EXTENSIONS}
        className="hidden"
        onChange={handleFileUpload}
      />

      {/* Top bar */}
      <header className="flex items-center justify-between border-b bg-card px-4 py-3">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => navigate("/")}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="flex items-center gap-2">
            <Box className="h-5 w-5 text-primary" />
            <h1 className="font-mono text-sm font-semibold text-foreground">
              TrackSteel<span className="text-primary">XR</span>
            </h1>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <ShareButton />
          <Button className="gap-2 glow-primary" disabled={!xrSupported} onClick={handleEnterXR}>
            <Glasses className="h-4 w-4" />
            Entrar em Modo XR
          </Button>
        </div>
      </header>

      <div className="flex flex-1 overflow-hidden">
        {/* 3D Canvas with floating controls */}
        <div className="relative flex-1">
          <ModelViewerCanvas />
          <ViewerControls />
        </div>

        {/* Side panel */}
        <aside className="w-80 shrink-0 border-l bg-card">
          <ScrollArea className="h-full">
            <div className="p-4 space-y-5">
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h2 className="font-mono text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                    Cena · {models.length}/{maxModels} peças
                  </h2>
                </div>
                <SceneModelList />
                <div className="mt-2 grid grid-cols-2 gap-1.5">
                  <Button
                    variant="outline"
                    size="sm"
                    className="h-8 gap-1.5 text-[10px] font-mono"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={!canAddMore || converting}
                    title={canAddMore ? 'Adicionar arquivo local' : 'Limite atingido'}
                  >
                    {converting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Upload className="h-3.5 w-3.5" />}
                    {converting ? 'Convertendo…' : 'Adicionar'}
                  </Button>
                  <CloudLoader compact variant="outline" />
                </div>
              </div>

              <Separator />

              <div>
                <h2 className="mb-2 font-mono text-xs font-semibold uppercase tracking-widest text-muted-foreground">
                  Peça selecionada
                </h2>
                <div className="space-y-3">
                  <InfoItem icon={FileText} label="Arquivo" value={model.fileName} />
                  <InfoItem icon={Box} label="Tamanho" value={`${(model.fileSize / (1024 * 1024)).toFixed(2)} MB`} />
                  <InfoItem icon={Ruler} label="Escala" value="1:1 (mm)" />
                </div>
              </div>

              <Separator />

              <FineTuningControls />

              <Separator />

              <MeasurementsList />

              <Separator />

              <InspectionChecklist />

              <Separator />

              <ScreenshotGallery />
              <div className="rounded-lg border bg-muted/50 p-3">
                <p className="font-mono text-xs text-muted-foreground">
                  Clique em uma peça na cena para selecioná-la — os controles de ajuste fino
                  passam a operar sobre ela. Use "Adicionar" / "Nuvem" para empilhar peças.
                </p>
              </div>
            </div>
          </ScrollArea>
        </aside>
      </div>
    </div>
  );
};

function InfoItem({ icon: Icon, label, value }: { icon: any; label: string; value: string }) {
  return (
    <div className="flex items-start gap-3">
      <Icon className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
      <div className="min-w-0">
        <p className="text-xs text-muted-foreground">{label}</p>
        <p className="truncate font-mono text-sm text-foreground">{value}</p>
      </div>
    </div>
  );
}

export default Viewer;
