
"use client";

import React, { useState, useEffect, useCallback } from 'react';
import { DataInputForm, type RangeFormInputData } from '@/components/Breakdown/DataInputForm';
import { ManualBulkInput } from '@/components/Breakdown/ManualBulkInput';
import { CollectedDataTable } from '@/components/Breakdown/CollectedDataTable';
import { ActionsSection } from '@/components/Breakdown/ActionsSection';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import type { DataItem, ItemTypeValue } from '@/types';
import { generateCsv } from '@/lib/csvUtils';
import { useToast } from '@/hooks/use-toast';
import { Keyboard, ListChecks, UploadCloud, Info, Loader2 } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { parseLocationRange } from '@/lib/locationUtils';
import { useAuth } from '@/contexts/AuthContext'; // Import useAuth
import { useRouter } from 'next/navigation'; // Import useRouter

const LOCAL_STORAGE_KEY_ITEMS = 'breakdownItems';

export default function BreakdownPage() {
  const [dataItems, setDataItems] = useState<DataItem[]>([]);
  const [generatedCsvContent, setGeneratedCsvContent] = useState<string | null>(null);
  const [isProcessingCsv, setIsProcessingCsv] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  
  const { user, isLoading: isAuthLoading, isAuthenticated } = useAuth(); // Use useAuth
  const router = useRouter(); // Use useRouter

  const { toast } = useToast();

  useEffect(() => {
    if (!isAuthLoading && isAuthenticated && user?.role === 'contracts') {
      toast({ title: "Access Denied", description: "You do not have permission to access this tool.", variant: "destructive" });
      router.push('/'); // Redirect contracts users
    }
  }, [isAuthLoading, isAuthenticated, user, router, toast]);

  useEffect(() => {
    // Only initialize if authenticated and not a contracts user
    if (isAuthenticated && user?.role !== 'contracts') {
      try {
        const storedItems = localStorage.getItem(LOCAL_STORAGE_KEY_ITEMS);
        if (storedItems) {
          setDataItems(JSON.parse(storedItems));
        }
      } catch (error) {
        console.error("Error loading data from localStorage:", error);
        toast({
          title: "Error Loading Data",
          description: "Could not load previously saved data from your browser's storage.",
          variant: "destructive",
        });
      }
      setIsInitialized(true);
    } else if (!isAuthLoading && !isAuthenticated) {
        // If not authenticated (and not loading), redirect or handle appropriately
        // This case might be handled globally by AuthProvider, but good to be defensive
        router.push('/'); // Or a login page
    } else {
      setIsInitialized(false); // Explicitly set to false if conditions not met
    }
  }, [toast, isAuthenticated, user, isAuthLoading, router]);

  useEffect(() => {
    if (isInitialized && typeof window !== 'undefined' && isAuthenticated && user?.role !== 'contracts') {
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY_ITEMS, JSON.stringify(dataItems));
      } catch (error) {
        console.error("Error saving data to localStorage:", error);
        toast({
          title: "Error Saving Data",
          description: "Could not save data to your browser's storage. Changes might not persist.",
          variant: "destructive",
        });
      }
    }
  }, [dataItems, isInitialized, toast, isAuthenticated, user]);

  const makeId = () => Math.random().toString(36).substring(2, 9);

  const handleAddDataItem = (formData: RangeFormInputData) => {
    const trimmedLocationRange = formData.locationRange?.trim();
    let locationsToProcess: (string | number | undefined)[] = [];

    if (trimmedLocationRange) {
        locationsToProcess = parseLocationRange(trimmedLocationRange);
        if (locationsToProcess.length === 0 && trimmedLocationRange !== "") {
            toast({
                title: "Invalid Range",
                description: `Location range "${trimmedLocationRange}" is invalid or not supported. Use formats like 1-5, A1, or B10-B12.`,
                variant: "destructive"
            });
            return;
        }
    }

    if (locationsToProcess.length === 0 && (!trimmedLocationRange || trimmedLocationRange === "")) {
        locationsToProcess = [undefined]; // Represents "no specific location"
    }

    const newItems: DataItem[] = [];
    const originalInputForGroup = trimmedLocationRange || ""; // Store the raw input for grouping

    for (const loc of locationsToProcess) {
      newItems.push({
        id: makeId(),
        location: loc,
        sisel: '',
        dept: '',
        aisle: formData.aisle,
        type: formData.type as ItemTypeValue,
        description: formData.description,
        originalRangeInput: originalInputForGroup,
      });
    }

    if (newItems.length > 0) {
      setDataItems(prev => [...prev, ...newItems]);
      setGeneratedCsvContent(null);

      let toastMessage: string;
      if (trimmedLocationRange && !(locationsToProcess.length === 1 && locationsToProcess[0] === undefined)) {
          toastMessage = `${newItems.length} item(s) for location/range "${trimmedLocationRange}" added.`;
      } else {
          toastMessage = `Item with no specified location added.`;
      }
      toast({ title: "Item(s) Added", description: toastMessage });
    } else if (trimmedLocationRange && locationsToProcess.length === 0) {
      toast({
          title: "No Items Added",
          description: `Location range "${trimmedLocationRange}" did not result in any items.`,
          variant: "default"
      });
    }
  };

  const handleBulkAddDataItems = (items: Partial<DataItem>[]) => {
    const newItems: DataItem[] = items.map(item => ({
      id: makeId(),
      location: item.location,
      sisel: '',
      dept: '',
      aisle: item.aisle,
      description: item.description,
      type: item.type as ItemTypeValue,
      originalRangeInput: item.originalRangeInput || (item.location ? String(item.location) : ""),
    } as DataItem)); 
    setDataItems(prev => [...prev, ...newItems]);
    setGeneratedCsvContent(null);
    toast({ title: "Bulk Data Added", description: `${newItems.length} items added to the list.` });
  };

  const handleDeleteItem = (id: string) => {
    setDataItems(prev => prev.filter(item => item.id !== id));
    setGeneratedCsvContent(null);
    toast({ title: "Item Removed", description: "The item has been removed from the list." });
  };

  const handleUpdateItem = (id: string, updatedData: Partial<Omit<DataItem, 'id' | 'originalRangeInput'>>) => {
    setDataItems(prev => prev.map(item => item.id === id ? { ...item, ...updatedData } : item));
    setGeneratedCsvContent(null);
    toast({ title: "Item Updated", description: "The item has been updated." });
  };

  const handleClearAllData = useCallback(() => {
    setDataItems([]);
    setGeneratedCsvContent(null);
    if (typeof window !== 'undefined') {
      localStorage.removeItem(LOCAL_STORAGE_KEY_ITEMS);
    }
    toast({ title: "Data Cleared", description: "All collected data has been cleared." });
  }, [toast]);

  const handleGenerateCsv = async (): Promise<string> => {
    setIsProcessingCsv(true);
    try {
      const csv = generateCsv(dataItems);
      setGeneratedCsvContent(csv);
      toast({ title: "CSV Generated", description: "CSV content is ready for preview or upload." });
      return csv;
    } catch (error: any) {
      console.error("CSV Generation Error:", error);
      toast({ variant: "destructive", title: "CSV Generation Failed", description: `Could not generate CSV: ${error.message}` });
      return "";
    } finally {
      setIsProcessingCsv(false);
    }
  };

  if (isAuthLoading || (!isAuthenticated && !isAuthLoading) || (isAuthenticated && user?.role === 'contracts')) {
    return (
        <div className="container mx-auto p-4 sm:p-6 lg:p-8 flex flex-col items-center justify-center min-h-[calc(100vh-150px)]">
            {isAuthLoading && <Loader2 className="h-12 w-12 text-primary animate-spin mb-4" />}
            <p className="text-muted-foreground">
                {isAuthLoading ? 'Loading authentication...' : (user?.role === 'contracts' ? 'Access to this tool is restricted.' : 'Redirecting...')}
            </p>
        </div>
    );
  }
  
  if (!isInitialized) {
     return (
        <div className="container mx-auto p-4 sm:p-6 lg:p-8 flex flex-col items-center justify-center min-h-[calc(100vh-150px)]">
            <Loader2 className="h-12 w-12 text-primary animate-spin mb-4" />
            <p className="text-muted-foreground">Initializing Breakdown Tool...</p>
        </div>
    );
  }


  return (
    <div className="container mx-auto p-4 sm:p-6 lg:p-8 flex flex-col items-center min-h-screen">
      <main className="w-full max-w-6xl space-y-8 mt-8">
        <Alert className="bg-primary/10 border-primary/30">
          <Info className="h-4 w-4 text-primary" />
          <AlertTitle className="text-primary font-semibold">Welcome to Breakdown Tool!</AlertTitle>
          <AlertDescription className="text-primary/80">
            Use the sections below to input data. Enter a location range (e.g., 1-5 or A1-A3) to create items for multiple locations at once.
            Sisel and Dept fields are automatically blank. The final description in the CSV will be a combination of Type, Aisle (if provided), and your input Description. Data is saved in your browser.
          </AlertDescription>
        </Alert>

        <div className="space-y-6">
            <Card className="shadow-lg">
              <CardHeader>
                <CardTitle className="text-xl">Add Data Item(s)</CardTitle>
                <CardDescription>Enter details. Use location range for multiple items. Sisel and Dept are blank.</CardDescription>
              </CardHeader>
              <CardContent>
                <DataInputForm onSubmit={handleAddDataItem} />
              </CardContent>
            </Card>

            <Card className="shadow-lg">
              <CardHeader>
                <CardTitle className="text-xl flex items-center gap-2"><Keyboard size={20} /> Manual Bulk Input (Tab-Separated)</CardTitle>
              </CardHeader>
              <CardContent>
                <ManualBulkInput onBulkAdd={handleBulkAddDataItems} />
              </CardContent>
            </Card>
        </div>

        <Separator />

        <div className="space-y-6">
            <Card className="shadow-xl w-full">
              <CardHeader>
                <CardTitle className="text-xl flex items-center gap-2"><ListChecks size={20} /> Collected Data ({dataItems.length} items)</CardTitle>
                <CardDescription>Review items before generating the CSV. CSV description will be formatted. Click pencil to edit. Data persists in browser.</CardDescription>
              </CardHeader>
              <CardContent>
                <CollectedDataTable items={dataItems} onDeleteItem={handleDeleteItem} onUpdateItem={handleUpdateItem} />
              </CardContent>
            </Card>
            <Card className="shadow-xl w-full">
              <CardHeader>
                <CardTitle className="text-xl flex items-center gap-2"><UploadCloud size={20} /> Export & Manage</CardTitle>
                <CardDescription>Generate your CSV, upload to OneDrive, or clear all data for this tool.</CardDescription>
              </CardHeader>
              <CardContent>
                <ActionsSection
                    onGenerateCsv={handleGenerateCsv}
                    onClearAllData={handleClearAllData}
                    isProcessing={isProcessingCsv || isUploading}
                    csvPreview={generatedCsvContent}
                    hasData={dataItems.length > 0}
                />
              </CardContent>
            </Card>
        </div>
      </main>
    </div>
  );
}
