
"use client";

import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Loader2, TimerIcon, Trash2, History, XCircle, ArrowUpFromLine } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { useAuth } from '@/contexts/AuthContext'; // Import useAuth
import { useRouter } from 'next/navigation'; // Import useRouter


const LOCAL_STORAGE_KEY_HISTORY = 'finishEstimatorHistory'; 

interface HistoryEntry {
  id: string;
  timestamp: number;
  totalLocations: number;
  completedLocations: number;
  locationsToSkip: number;
  startTime: string;
  breakDuration: number;
  currentTimeInput?: string;
  endTime: string;
  calculatedTimePerLocation: number;
  progressPercentage: number;
  remainingLocationsToCount: number;
}

export default function FinishEstimatorPage() {
  const [totalLocations, setTotalLocations] = useState<number | string>('');
  const [completedLocations, setCompletedLocations] = useState<number | string>('');
  const [locationsToSkip, setLocationsToSkip] = useState<number | string>('');
  const [startTime, setStartTime] = useState<string>('');
  const [breakDuration, setBreakDuration] = useState<number | string>('');
  const [currentTimeInput, setCurrentTimeInput] = useState<string>('');
  
  const [loading, setLoading] = useState(false);
  const [endTime, setEndTime] = useState<string | null>(null);
  const [calculatedTimePerLocation, setCalculatedTimePerLocation] = useState<number>(0);

  const [history, setHistory] = useState<HistoryEntry[]>([]);
  const [isInitialized, setIsInitialized] = useState(false);
  const { toast } = useToast();
  
  const { user, isLoading: isAuthLoading, isAuthenticated } = useAuth();
  const router = useRouter();


  useEffect(() => {
    if (!isAuthLoading && !isAuthenticated) {
        router.push('/'); // Or a login page
    } else if (!isAuthLoading && isAuthenticated) {
        try {
          const storedHistory = localStorage.getItem(LOCAL_STORAGE_KEY_HISTORY);
          if (storedHistory) {
            const parsedHistory: HistoryEntry[] = JSON.parse(storedHistory);
            parsedHistory.sort((a, b) => b.timestamp - a.timestamp);
            setHistory(parsedHistory);
          }
        } catch (error) {
          console.error("Error loading history from localStorage:", error);
          toast({
            title: "Error Loading History",
            description: "Could not load previously saved calculation history.",
            variant: "destructive",
          });
        }
        setIsInitialized(true);
    }
  }, [toast, isAuthLoading, isAuthenticated, router]);

  useEffect(() => {
    if (isInitialized && isAuthenticated) { // Only save if initialized and authenticated
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY_HISTORY, JSON.stringify(history));
      } catch (error) {
        console.error("Error saving history to localStorage:", error);
        toast({
          title: "Error Saving History",
          description: "Could not save calculation history to your browser's storage.",
          variant: "destructive",
        });
      }
    }
  }, [history, toast, isInitialized, isAuthenticated]);


  const progressPercentage = useMemo(() => {
    const total = Number(totalLocations);
    const completed = Number(completedLocations);
    const skipped = Number(locationsToSkip);
    const effectiveTotalActiveLocations = Math.max(0, total - skipped);
    if (effectiveTotalActiveLocations <= 0) return completed > 0 ? 100 : (total > 0 ? 100 : 0);
    if (completed <= 0) return 0;
    return Math.min(100, Math.max(0, Math.round((completed / effectiveTotalActiveLocations) * 100)));
  }, [totalLocations, completedLocations, locationsToSkip]);

  const remainingLocationsToCount = useMemo(() => {
    return Math.max(0, Number(totalLocations) - Number(completedLocations) - Number(locationsToSkip));
  }, [totalLocations, completedLocations, locationsToSkip]);

  const parseTime = (timeStr: string): Date | null => {
    if (!timeStr) return null;
    const [hours, minutes] = timeStr.split(':').map(Number);
    if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;
    const date = new Date();
    date.setHours(hours, minutes, 0, 0);
    return date;
  };

  const calculateEndTime = (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setEndTime(null); 

    const numTotal = Number(totalLocations);
    const numCompleted = Number(completedLocations);
    const numSkipped = Number(locationsToSkip);
    const numBreak = Number(breakDuration || 0);

    if (numTotal <= 0) {
      toast({ title: "Invalid Input", description: "Total locations must be greater than 0.", variant: "destructive"});
      setLoading(false);
      return;
    }
    if (numCompleted < 0 || numSkipped < 0 || numBreak < 0) {
      toast({ title: "Invalid Input", description: "Completed, skipped locations, or break duration cannot be negative.", variant: "destructive"});
      setLoading(false);
      return;
    }
     if (numCompleted + numSkipped > numTotal) {
      toast({ title: "Invalid Input", description: "Completed plus skipped locations cannot exceed total locations.", variant: "destructive"});
      setLoading(false);
      return;
    }

    setTimeout(() => {
      const parsedStartTimeDate = parseTime(startTime);
      if (!parsedStartTimeDate) {
        toast({ title: "Invalid Start Time", description: "Please enter a valid start time.", variant: "destructive"});
        setLoading(false);
        return;
      }
      
      let currentDateForCalculationBase: Date;
      if (currentTimeInput) {
        const parsedCurrentTime = parseTime(currentTimeInput);
        if (!parsedCurrentTime) {
          toast({ title: "Invalid Current Time", description: "Please enter a valid current time or leave it empty.", variant: "destructive"});
          setLoading(false);
          return;
        }
        currentDateForCalculationBase = parsedCurrentTime;
        if (currentDateForCalculationBase.getTime() < parsedStartTimeDate.getTime()) {
          currentDateForCalculationBase.setDate(currentDateForCalculationBase.getDate() + 1);
        }
      } else {
        currentDateForCalculationBase = new Date(); 
      }
      
      const elapsedMinutes = (currentDateForCalculationBase.getTime() - parsedStartTimeDate.getTime()) / 60000;
      
      if (elapsedMinutes < 0 && numCompleted > 0) {
        toast({ title: "Logical Time Error", description: "Current time cannot be before Start Time if locations have been completed.", variant: "destructive"});
        setLoading(false);
        return;
      }
      
      let timePerLoc = 10; // Default time per location
      if (numCompleted > 0 && elapsedMinutes >= 0) { 
        timePerLoc = elapsedMinutes / numCompleted;
      } else if (numCompleted === 0 && (numTotal - numSkipped > 0)) { 
        toast({ title: "Calculation Note", description: "No locations completed. Using default time (10 mins/loc).", variant: "default" });
      }

      const currentCalculatedTimePerLocation = parseFloat(timePerLoc.toFixed(1));
      setCalculatedTimePerLocation(currentCalculatedTimePerLocation);
      
      const currentRemainingLocations = Math.max(0, numTotal - numCompleted - numSkipped);
      
      let finalEndTimeString: string;

      if (currentRemainingLocations <= 0) {
        finalEndTimeString = currentDateForCalculationBase.toLocaleTimeString('en-GB', { 
            hour: '2-digit', 
            minute: '2-digit'
        });
        toast({ title: "Already Completed!", description: `All locations accounted for as of ${finalEndTimeString}.`});
      } else {
        const totalMinutesNeeded = (currentRemainingLocations * timePerLoc) + numBreak;
        const estimatedEndTimeDate = new Date(currentDateForCalculationBase.getTime() + totalMinutesNeeded * 60000);
        finalEndTimeString = estimatedEndTimeDate.toLocaleTimeString('en-GB', { 
            hour: '2-digit', 
            minute: '2-digit'
        });
        toast({ title: "Calculation Complete", description: `Estimated end time: ${finalEndTimeString}`});
      }
      setEndTime(finalEndTimeString);

      const effectiveTotalActiveLocs = Math.max(0, numTotal - numSkipped); 
      const currentProgressPercentage = effectiveTotalActiveLocs > 0 ? Math.min(100, Math.max(0, Math.round((numCompleted / effectiveTotalActiveLocs) * 100))) : (numTotal > 0 ? 100 : 0);

      const newHistoryEntry: HistoryEntry = {
        id: Date.now().toString(),
        timestamp: Date.now(),
        totalLocations: numTotal,
        completedLocations: numCompleted,
        locationsToSkip: numSkipped,
        startTime,
        breakDuration: numBreak,
        currentTimeInput: currentTimeInput || undefined,
        endTime: finalEndTimeString,
        calculatedTimePerLocation: currentCalculatedTimePerLocation,
        progressPercentage: currentProgressPercentage,
        remainingLocationsToCount: currentRemainingLocations
      };
      setHistory(prevHistory => [newHistoryEntry, ...prevHistory.slice(0, 49)]);
      
      setLoading(false);
    }, 500);
  };

  const handleClearAllHistory = useCallback(() => {
    setHistory([]);
    toast({ title: "History Cleared", description: "All calculation history has been cleared." });
  }, [toast]);

  const handleDeleteHistoryEntry = useCallback((idToDelete: string) => {
    setHistory(prevHistory => prevHistory.filter(entry => entry.id !== idToDelete));
    toast({ title: "History Entry Deleted", description: "The selected entry has been removed from history." });
  }, [toast]);

  const loadHistoryEntryIntoForm = useCallback((entry: HistoryEntry) => {
    setTotalLocations(entry.totalLocations.toString());
    setCompletedLocations(entry.completedLocations.toString());
    setLocationsToSkip(entry.locationsToSkip.toString());
    setStartTime(entry.startTime);
    setBreakDuration(entry.breakDuration.toString());
    setCurrentTimeInput(entry.currentTimeInput || '');
    
    setEndTime(null);
    setCalculatedTimePerLocation(0);
    
    toast({ title: "History Entry Loaded", description: "Adjust values and recalculate if needed." });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [toast]);

  if (isAuthLoading || !isInitialized) {
    return (
      <div className="container mx-auto px-4 py-8 flex justify-center items-center min-h-[calc(100vh-120px)]">
        <Loader2 className="h-12 w-12 text-primary animate-spin" />
        <p className="ml-4 text-muted-foreground">
          {isAuthLoading ? 'Loading authentication...' : 'Initializing Finish Estimator...'}
        </p>
      </div>
    );
  }
  
  if (!isAuthenticated) {
    // This should ideally be caught by AuthProvider and redirected, but as a fallback:
    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)]">
            <p className="text-lg text-muted-foreground">Redirecting to login...</p>
        </div>
    );
  }


  return (
    <div className="container mx-auto px-4 py-8 min-h-[calc(100vh-120px)] flex flex-col items-center space-y-8">
      <header className="text-center">
        <h1 className="text-3xl md:text-4xl font-bold text-primary flex items-center justify-center gap-2">
          <TimerIcon className="h-8 w-8 md:h-10 md:w-10" /> Finish Estimator
        </h1>
        <p className="text-muted-foreground mt-1">Location-Based Count Time Estimator</p>
      </header>

      <Card className="w-full max-w-md shadow-xl bg-card">
        <CardContent className="p-6 bg-primary/5">
          <form onSubmit={calculateEndTime} className="space-y-4">
            <div>
              <Label htmlFor="totalLocations">Total Locations to Count</Label>
              <Input id="totalLocations" type="number" value={totalLocations} onChange={e => setTotalLocations(e.target.value)} className="bg-background" required min="1" />
            </div>
            
            <div>
              <Label htmlFor="completedLocations">Locations Completed</Label>
              <Input id="completedLocations" type="number" value={completedLocations} onChange={e => setCompletedLocations(e.target.value)} className="bg-background" required placeholder="0" min="0" />
            </div>
            
            <div>
              <Label htmlFor="locationsToSkip">Locations to Not Count</Label>
              <Input id="locationsToSkip" type="number" value={locationsToSkip} onChange={e => setLocationsToSkip(e.target.value)} className="bg-background" placeholder="0" min="0" />
            </div>

            <div>
              <Label htmlFor="startTime">Start Time</Label>
              <Input id="startTime" type="time" value={startTime} onChange={e => setStartTime(e.target.value)} className="bg-background" required />
            </div>
            
            <div>
              <Label htmlFor="breakDuration">Break Duration (minutes)</Label>
              <Input id="breakDuration" type="number" value={breakDuration} onChange={e => setBreakDuration(e.target.value)} min="0" className="bg-background" placeholder="0" />
            </div>
            
            <div>
              <Label htmlFor="currentTimeInput">Current Time (optional)</Label>
              <Input id="currentTimeInput" type="time" value={currentTimeInput} onChange={e => setCurrentTimeInput(e.target.value)} className="bg-background" />
              <p className="text-xs text-muted-foreground mt-1">Leave empty to use current local time</p>
            </div>

            <Button type="submit" className="w-full" disabled={loading}>
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Calculate End Time
            </Button>
          </form>

          {loading && (
            <div className="mt-6 text-center">
              <Loader2 className="h-8 w-8 text-primary animate-spin mx-auto" />
              <p className="text-muted-foreground mt-2">Calculating...</p>
            </div>
          )}

          {endTime && !loading && (
            <div className="mt-6 p-4 bg-background/70 rounded-md border">
              <h2 className="text-lg font-semibold mb-2 text-primary-foreground bg-primary -mx-4 -mt-4 px-4 py-2 rounded-t-md">Estimated Completion:</h2>
              <p className="text-3xl font-bold text-primary text-center py-2">{endTime}</p>
              <p className="text-sm text-muted-foreground text-center">Avg. time per counted location: {calculatedTimePerLocation} mins</p>
              
              <div className="mt-4">
                <Progress value={progressPercentage} aria-label={`${progressPercentage}% Complete`} />
                <div className="flex justify-between text-sm text-muted-foreground mt-1">
                    <span>{progressPercentage}% Complete</span>
                    <span>{remainingLocationsToCount} remaining</span>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {isInitialized && history.length > 0 && (
        <Card className="w-full max-w-2xl shadow-xl bg-card">
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle className="text-xl flex items-center gap-2"><History size={20}/> Calculation History</CardTitle>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="outline" size="sm" className="text-xs">
                    <Trash2 className="mr-1 h-3 w-3" /> Clear History
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                      This will permanently delete all calculation history. This action cannot be undone.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleClearAllHistory} className="bg-destructive hover:bg-destructive/90">
                      Yes, clear history
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
            <CardDescription>Review of past calculations. Newest entries are at the top. Click the <ArrowUpFromLine size={14} className="inline-block align-text-bottom" /> icon to load an entry into the form.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4 max-h-[500px] overflow-y-auto p-4">
            {history.map((entry) => (
              <div key={entry.id} className="p-3 border rounded-md bg-background/50 hover:shadow-md transition-shadow">
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <p className="text-sm font-semibold text-primary">{new Date(entry.timestamp).toLocaleString('en-GB')}</p>
                    <p className="text-lg font-bold text-primary">{entry.endTime}</p>
                  </div>
                  <div className="flex items-center space-x-1">
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      className="text-blue-600 hover:bg-blue-600/10 h-7 w-7"
                      onClick={() => loadHistoryEntryIntoForm(entry)}
                      aria-label="Load history entry into form"
                    >
                      <ArrowUpFromLine className="h-4 w-4" />
                    </Button>
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      className="text-destructive hover:bg-destructive/10 h-7 w-7"
                      onClick={() => handleDeleteHistoryEntry(entry.id)}
                      aria-label="Delete history entry"
                    >
                      <XCircle className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-x-4 gap-y-1 text-xs text-muted-foreground">
                  <p>Total: {entry.totalLocations}</p>
                  <p>Completed: {entry.completedLocations}</p>
                  <p>Skipped: {entry.locationsToSkip}</p>
                  <p>Start: {entry.startTime} {entry.currentTimeInput ? `(Manual Current: ${entry.currentTimeInput})` : ''}</p>
                  <p>Break: {entry.breakDuration} mins</p>
                  <p>Avg Time: {entry.calculatedTimePerLocation} mins/loc</p>
                  <p>Progress: {entry.progressPercentage}%</p>
                  <p>Remaining: {entry.remainingLocationsToCount}</p>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
