
"use client";

import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Calculator, History, Trash2, XCircle, RefreshCcw, PlusSquare, Archive, ArrowUpFromLine, Loader2 } 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 { ScrollArea } from '@/components/ui/scroll-area';
import { useAuth } from '@/contexts/AuthContext'; // Import useAuth
import { useRouter } from 'next/navigation'; // Import useRouter


const LOCAL_STORAGE_KEY_HISTORY = 'scanCheckAccuracyHistory';

interface ScanCheckHistoryEntry {
  id: string;
  timestamp: number;
  inputs: {
    unitsCounted: number;
    unitsChecked: number;
    currentErrors: number;
    newErrors: number;
  };
  outputs: {
    accuracyPercentage: string;
    currentAccuracyPercentage: string;
    checkPercentage: string;
    newCheckPercentage: string;
    totalErrors: number;
    effectiveUnitsCheckedAfterNewErrors: number;
  };
}

export default function ScanCheckAccuracyCalculatorPage() {
  const [unitsCounted, setUnitsCounted] = useState<string>('');
  const [unitsChecked, setUnitsChecked] = useState<string>('');
  const [currentErrors, setCurrentErrors] = useState<string>('');
  const [newErrors, setNewErrors] = useState<string>('');

  const [history, setHistory] = useState<ScanCheckHistoryEntry[]>([]);
  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: ScanCheckHistoryEntry[] = 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 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.",
          variant: "destructive",
        });
      }
    }
  }, [history, isInitialized, toast, isAuthenticated]);


  const numUnitsCounted = useMemo(() => Number(unitsCounted) || 0, [unitsCounted]);
  const numUnitsChecked = useMemo(() => Number(unitsChecked) || 0, [unitsChecked]);
  const numCurrentErrors = useMemo(() => Number(currentErrors) || 0, [currentErrors]);
  const numNewErrors = useMemo(() => Number(newErrors) || 0, [newErrors]);

  const totalErrors = useMemo(() => {
    return numCurrentErrors + numNewErrors;
  }, [numCurrentErrors, numNewErrors]);

  const currentAccuracyPercentage = useMemo(() => {
    if (!numUnitsChecked || numUnitsChecked === 0) return '100.00';
    const accuracy = numCurrentErrors === 0 ? 100 : ((numUnitsChecked - numCurrentErrors) / numUnitsChecked) * 100;
    return Math.max(0, accuracy).toFixed(2);
  }, [numUnitsChecked, numCurrentErrors]);

  const effectiveUnitsCheckedAfterNewErrors = useMemo(() => {
    return numUnitsChecked + numNewErrors;
  }, [numUnitsChecked, numNewErrors]);

  const accuracyPercentage = useMemo(() => {
    if (!effectiveUnitsCheckedAfterNewErrors || effectiveUnitsCheckedAfterNewErrors === 0) return '100.00';
    const accuracy = totalErrors === 0 ? 100 : ((effectiveUnitsCheckedAfterNewErrors - totalErrors) / effectiveUnitsCheckedAfterNewErrors) * 100;
    return Math.max(0, accuracy).toFixed(2);
  }, [effectiveUnitsCheckedAfterNewErrors, totalErrors]);

  const checkPercentage = useMemo(() => {
    if (!numUnitsCounted || numUnitsCounted === 0) return '0.00';
    const checkRate = (numUnitsChecked / numUnitsCounted) * 100;
    return Math.max(0, Math.min(100, checkRate)).toFixed(2);
  }, [numUnitsChecked, numUnitsCounted]);

  const newCheckPercentage = useMemo(() => {
    if (!numUnitsCounted || numUnitsCounted === 0) return '0.00';
    const newCheckRate = (effectiveUnitsCheckedAfterNewErrors / numUnitsCounted) * 100;
    return Math.max(0, Math.min(100, newCheckRate)).toFixed(2);
  }, [effectiveUnitsCheckedAfterNewErrors, numUnitsCounted]);

  const getAccuracyColorClass = (accuracyStr: string): string => {
    const accuracy = parseFloat(accuracyStr);
    if (accuracy >= 99.00) return 'text-green-600 dark:text-green-400';
    if (accuracy > 98.50) return 'text-yellow-600 dark:text-yellow-400';
    return 'text-red-600 dark:text-red-400';
  };

  const currentAccuracyColor = useMemo(() => getAccuracyColorClass(currentAccuracyPercentage), [currentAccuracyPercentage]);
  const newAccuracyColor = useMemo(() => getAccuracyColorClass(accuracyPercentage), [accuracyPercentage]);

  const statusBackgroundClass = useMemo(() => {
    const accuracy = parseFloat(accuracyPercentage);
    if (accuracy >= 99) return 'bg-green-100 dark:bg-green-900/30';
    if (accuracy > 98.50) return 'bg-yellow-100 dark:bg-yellow-900/30';
    return 'bg-red-100 dark:bg-red-900/30';
  }, [accuracyPercentage]);

  const statusMessage = useMemo(() => {
    const accuracy = parseFloat(accuracyPercentage);
    if (accuracy >= 99) return 'Excellent quality control! Keep up the great work!';
    if (accuracy > 98.50) return 'Good accuracy, but there\'s room for improvement.';
    return 'Action required: Quality control needs attention.';
  }, [accuracyPercentage]);

  const handleLogCalculation = useCallback(() => {
    if (numUnitsCounted <= 0) {
        toast({ title: "Cannot Log", description: "Units counted must be greater than 0 to log.", variant: "destructive"});
        return;
    }
    const newEntry: ScanCheckHistoryEntry = {
      id: Date.now().toString(),
      timestamp: Date.now(),
      inputs: {
        unitsCounted: numUnitsCounted,
        unitsChecked: numUnitsChecked,
        currentErrors: numCurrentErrors,
        newErrors: numNewErrors,
      },
      outputs: {
        accuracyPercentage: accuracyPercentage,
        currentAccuracyPercentage: currentAccuracyPercentage,
        checkPercentage: checkPercentage,
        newCheckPercentage: newCheckPercentage,
        totalErrors: totalErrors,
        effectiveUnitsCheckedAfterNewErrors: effectiveUnitsCheckedAfterNewErrors,
      },
    };
    setHistory(prev => [newEntry, ...prev.slice(0, 49)]);
    toast({ title: "Calculation Logged", description: "Current state saved to history."});
  }, [
    numUnitsCounted, numUnitsChecked, numCurrentErrors, numNewErrors,
    accuracyPercentage, currentAccuracyPercentage, checkPercentage, newCheckPercentage,
    totalErrors, effectiveUnitsCheckedAfterNewErrors, toast
  ]);

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

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

  const handleLoadHistoryEntry = useCallback((entry: ScanCheckHistoryEntry) => {
    setUnitsCounted(entry.inputs.unitsCounted.toString());
    setUnitsChecked(entry.inputs.unitsChecked.toString());
    setCurrentErrors(entry.inputs.currentErrors.toString());
    setNewErrors(entry.inputs.newErrors.toString());
    toast({ title: "History Entry Loaded", description: "Values loaded into the calculator."});
    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 Calculator...'}
        </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 flex flex-col items-center min-h-[calc(100vh-120px)] space-y-8">
      <Card className="w-full max-w-md shadow-xl">
        <CardHeader className="text-center">
          <div className="flex justify-center items-center mb-2">
            <Calculator className="h-8 w-8 text-primary" />
          </div>
          <CardTitle className="text-2xl font-bold text-primary">Scan Check Accuracy Calculator</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6 p-6">
          <div>
            <Label htmlFor="unitsCounted" className="block text-sm font-medium mb-1">Units Counted</Label>
            <Input
              id="unitsCounted"
              type="number"
              value={unitsCounted}
              onChange={(e) => setUnitsCounted(e.target.value)}
              min="0"
              className="bg-background"
              placeholder="e.g., 1000"
            />
          </div>

          <div>
            <Label htmlFor="unitsChecked" className="block text-sm font-medium mb-1">Units Checked (Initial)</Label>
            <Input
              id="unitsChecked"
              type="number"
              value={unitsChecked}
              onChange={(e) => setUnitsChecked(e.target.value)}
              min="0"
              className="bg-background"
              placeholder="e.g., 50"
            />
          </div>

          <div>
            <Label htmlFor="currentErrors" className="block text-sm font-medium mb-1">Current Errors (in initial check)</Label>
            <Input
              id="currentErrors"
              type="number"
              value={currentErrors}
              onChange={(e) => setCurrentErrors(e.target.value)}
              min="0"
              className="bg-background"
              placeholder="e.g., 1"
            />
          </div>
          
          <div>
            <Label htmlFor="newErrors" className="block text-sm font-medium mb-1">New Extra Errors Found</Label>
            <Input
              id="newErrors"
              type="number"
              value={newErrors}
              onChange={(e) => setNewErrors(e.target.value)}
              min="0"
              className="bg-background"
              placeholder="e.g., 1"
            />
            <p className="text-xs text-muted-foreground mt-1">Additional errors found after initial check. These also count as additional units checked for the 'New Accuracy'.</p>
          </div>
          
          <Separator />

          <div className="mt-6 text-center space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="p-3 rounded-md bg-muted/50 dark:bg-muted/20">
                <div className="text-2xl font-bold text-primary">{checkPercentage}%</div>
                <div className="text-xs text-muted-foreground">Initial Check Rate</div>
              </div>
              <div className="p-3 rounded-md bg-muted/50 dark:bg-muted/20">
                <div className={`text-2xl font-bold ${currentAccuracyColor}`}>{currentAccuracyPercentage}%</div>
                <div className="text-xs text-muted-foreground">Initial Accuracy</div>
              </div>
              <div className="p-3 rounded-md bg-muted/50 dark:bg-muted/20">
                <div className="text-2xl font-bold text-primary">{newCheckPercentage}%</div>
                <div className="text-xs text-muted-foreground">New Check Rate</div>
                 <p className="text-xs text-muted-foreground/70">(After new errors)</p>
              </div>
              <div className="p-3 rounded-md bg-muted/50 dark:bg-muted/20">
                <div className={`text-2xl font-bold ${newAccuracyColor}`}>{accuracyPercentage}%</div>
                <div className="text-xs text-muted-foreground">New Accuracy</div>
                <p className="text-xs text-muted-foreground/70">(After new errors)</p>
              </div>
            </div>
          </div>
          
          <div className={`mt-4 p-4 rounded-md ${statusBackgroundClass}`}>
            <p className="text-center text-sm font-medium" dangerouslySetInnerHTML={{ __html: statusMessage }}></p>
          </div>
          <Button onClick={handleLogCalculation} variant="outline" className="w-full mt-4">
            <Archive className="mr-2 h-4 w-4" /> Log Current Calculation
          </Button>
        </CardContent>
      </Card>

      {isInitialized && history.length > 0 && (
        <Card className="w-full max-w-2xl shadow-xl">
          <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. Click <ArrowUpFromLine size={14} className="inline-block align-text-bottom" /> to load or <XCircle size={14} className="inline-block align-text-bottom text-destructive" /> to delete.</CardDescription>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-[400px] w-full pr-3">
              <div className="space-y-3">
                {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-xs font-semibold text-primary">{new Date(entry.timestamp).toLocaleString('en-GB')}</p>
                        <p className="text-lg font-bold text-primary">Accuracy: {entry.outputs.accuracyPercentage}%</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={() => handleLoadHistoryEntry(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>Counted: {entry.inputs.unitsCounted}</p>
                      <p>Checked: {entry.inputs.unitsChecked}</p>
                      <p>Initial Err: {entry.inputs.currentErrors}</p>
                      <p>New Err: {entry.inputs.newErrors}</p>
                      <p>Total Err: {entry.outputs.totalErrors}</p>
                      <p>Eff. Checked: {entry.outputs.effectiveUnitsCheckedAfterNewErrors}</p>
                      <p>Initial Acc: {entry.outputs.currentAccuracyPercentage}%</p>
                      <p>Initial Rate: {entry.outputs.checkPercentage}%</p>
                      <p>New Rate: {entry.outputs.newCheckPercentage}%</p>
                    </div>
                  </div>
                ))}
              </div>
            </ScrollArea>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
    
