import { useEffect, useState, useRef } from "react";
import { Layout } from './components/layout/Layout';
import { VehicleSelector } from "./components/forms/VehicleSelector";
import { buildCatalog, useVehicleCatalog } from "./stores/useVehicleCatalog";
import { OptimizeButton } from './components/forms/OptimizeButton';
import { EnhancedItemTable } from './components/dashboard/EnhancedItemTable';
import { EditItemDialog } from "./components/forms/EditItemDialog";
import { VehicleSuggestionDialog } from "./components/forms/VehicleSuggestionDialog";
import { LazyLoadVisualization } from './components/three/LazyLoadVisualization';
import { LoadPlanSummary } from './components/dashboard/LoadPlanSummary';
import { CompatibilityMatrix } from './components/compatibility/CompatibilityMatrix';
import { AuditDashboard } from './components/audit/AuditDashboard';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useStore } from './stores/useStore';
import { api } from './services/api';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './components/ui/tabs';
import { Shield, Truck, ClipboardList, Route } from "lucide-react";
import type { Vehicle, Item } from "./types";
import SequenceOptimizer from "./components/sequence/SequenceOptimizer";

const queryClient = new QueryClient();

// AppContent component to use hooks
const AppContent = () => {
  const {
			selectedVehicle,
			loadPlan,
			items,
			repackReason,
			setVehicle,
			removeItem,
			removeBulkItems,
		} = useStore();

  const hasItems = items.length > 0;

  // State for edit dialog
		const [editingItem, setEditingItem] = useState<Item | null>(null);
		const [editDialogOpen, setEditDialogOpen] = useState(false);

		// State for the vehicle suggestion dialog
		const [suggestDialogOpen, setSuggestDialogOpen] = useState(false);

  // Ref for vehicle selector to enable scrolling to it
		const vehicleSelectorRef = useRef<HTMLDivElement>(null);

		// Function to scroll to vehicle selector
		const scrollToVehicleSelector = () => {
			vehicleSelectorRef.current?.scrollIntoView({
				behavior: "smooth",
				block: "center",
			});
		};

  // Pick a default vehicle when the app starts. Items are not preloaded:
  // the user adds their own or loads a sample template.
  useEffect(() => {
    let cancelled = false;

    const loadDefaultVehicle = async () => {
      for (let attempt = 0; attempt < 3; attempt++) {
        try {
          // Built-in list with the user's saved edits and additions applied
          const vehicles: Vehicle[] = buildCatalog(
            await api.getVehicles(),
            useVehicleCatalog.getState(),
          ).map((entry) => entry.vehicle);
          if (cancelled) return;
          if (vehicles.length > 0) {
            if (!useStore.getState().selectedVehicle) setVehicle(vehicles[0]);
            return;
          }
        } catch (err) {
          console.warn(`Vehicle fetch attempt ${attempt + 1} failed, retrying...`);
        }
        await new Promise(r => setTimeout(r, 1000)); // Wait 1s between retries
        if (cancelled) return;
      }
      console.error("Failed to fetch vehicles after multiple attempts");
    };

    loadDefaultVehicle();
    return () => {
      cancelled = true;
    };
  }, [setVehicle]);

  return (
			<Layout>
				<div className="space-y-6">
					<Tabs defaultValue="optimizer" className="w-full">
						<TabsList className="grid w-full grid-cols-4">
							<TabsTrigger
								value="optimizer"
								className="flex items-center gap-2"
							>
								<Truck className="h-4 w-4" />
								Load Optimizer
							</TabsTrigger>
							<TabsTrigger value="sequence" className="flex items-center gap-2">
								<Route className="h-4 w-4" />
								Load Sequence
							</TabsTrigger>
							<TabsTrigger
								value="compatibility"
								className="flex items-center gap-2"
							>
								<Shield className="h-4 w-4" />
								Compatibility Matrix
							</TabsTrigger>
							<TabsTrigger value="audit" className="flex items-center gap-2">
								<ClipboardList className="h-4 w-4" />
								Audit Trail
							</TabsTrigger>
						</TabsList>

						<TabsContent value="optimizer" className="mt-4 flex flex-col">
							{/* Top row: Load Plan Summary. Hidden until there are items,
							    so the first thing a new user sees is how to add them. */}
							<div className={hasItems ? "mb-4" : "hidden"}>
								<LoadPlanSummary
									loadPlan={loadPlan}
									vehicle={selectedVehicle}
									onChangeVehicle={scrollToVehicleSelector}
									onSuggestVehicle={() => setSuggestDialogOpen(true)}
									repackReason={repackReason}
								/>
							</div>

							{/* Main content: Two-column responsive layout with minimal spacing */}
							<div className="grid grid-cols-1 lg:grid-cols-12 gap-4 mb-4">
								{/* Left column: Configuration controls */}
								<div
									className="lg:col-span-4 space-y-2"
									ref={vehicleSelectorRef}
								>
									<VehicleSelector
										onSuggestVehicle={() => setSuggestDialogOpen(true)}
									/>
									<OptimizeButton />
								</div>

								{/* Right column: 3D visualization */}
								<div className="lg:col-span-8">
									<LazyLoadVisualization />
								</div>
							</div>

							{/* Item inventory. With no items yet it moves to the top of the
							    page (visually only, so open dialogs keep their state). */}
							<div className={hasItems ? "" : "order-first mb-4"}>
								<EnhancedItemTable
									onDeleteItem={removeItem}
									onBulkDelete={removeBulkItems}
									onEditItem={(item) => {
										setEditingItem(item);
										setEditDialogOpen(true);
									}}
									onExportItems={() => {
										// Enhanced CSV export with proper formatting
										const csvData = useStore.getState().items.map((item) => ({
											id: item.id,
											name: item.name || item.id,
											length: item.length,
											width: item.width,
											height: item.height,
											weight: item.weight,
											quantity: item.quantity ?? 1,
											destination: item.destination || "",
											stackOnTop: item.canStackOnTop ?? true,
											stackUnder: item.canStackUnder ?? item.stackable ?? true,
											rotationAllowed: item.rotationAllowed ?? true,
											category: item.category || "general",
											hazardLevel: item.hazardLevel || "none",
										}));

										const csvContent = [
											"id,name,length,width,height,weight,quantity,destination,stackOnTop,stackUnder,rotationAllowed,category,hazardLevel",
											...csvData.map(
												(row) =>
													`"${row.id}","${row.name}",${row.length},${row.width},${row.height},${row.weight},${row.quantity},"${row.destination}",${row.stackOnTop},${row.stackUnder},${row.rotationAllowed},"${row.category}","${row.hazardLevel}"`,
											),
										].join("\n");

										const blob = new Blob([csvContent], { type: "text/csv" });
										const url = window.URL.createObjectURL(blob);
										const a = document.createElement("a");
										a.setAttribute("href", url);
										a.setAttribute(
											"download",
											`items-export-${new Date().toISOString().split("T")[0]}.csv`,
										);
										document.body.appendChild(a);
										a.click();
										document.body.removeChild(a);
									}}
								/>

								{/* Vehicle Suggestion Dialog */}
								<VehicleSuggestionDialog
									open={suggestDialogOpen}
									onOpenChange={setSuggestDialogOpen}
								/>

								{/* Edit Item Dialog */}
								<EditItemDialog
									item={editingItem}
									open={editDialogOpen}
									onOpenChange={(open) => {
										setEditDialogOpen(open);
										if (!open) {
											setEditingItem(null);
										}
									}}
								/>
							</div>
						</TabsContent>

						<TabsContent value="sequence" className="mt-4">
							{loadPlan && selectedVehicle ? (
								<SequenceOptimizer
									packedItems={loadPlan.items}
									vehicleId={selectedVehicle.id}
									onSequenceGenerated={(sequence) => {
										console.log("Sequence generated:", sequence);
									}}
									onError={(error) => {
										console.error("Sequence optimization error:", error);
									}}
								/>
							) : (
								<div className="flex items-center justify-center py-12">
									<div className="text-center space-y-3">
										<Route className="h-12 w-12 mx-auto text-muted-foreground" />
										<h3 className="text-lg font-medium">
											No Load Plan Available
										</h3>
										<p className="text-sm text-muted-foreground max-w-md">
											Please optimize a load plan first by adding items and
											running the optimizer in the "Load Optimizer" tab.
										</p>
									</div>
								</div>
							)}
						</TabsContent>

						<TabsContent value="compatibility" className="mt-6">
							<CompatibilityMatrix />
						</TabsContent>

						<TabsContent value="audit" className="mt-6">
							<AuditDashboard />
						</TabsContent>
					</Tabs>
				</div>
			</Layout>
		);
};

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AppContent />
    </QueryClientProvider>
  );
}

export default App;