
"use client";

import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ArrowRight, Boxes, Timer, Calculator, ShieldAlert, Trash2, UserCog, Loader2, ExternalLink, Printer as ReportIcon, Mail, LayoutGrid, Briefcase } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import React, { useCallback, useState, useEffect } from 'react';
import type { CountInfo } from '@/types';
import { useAuth } from '@/contexts/AuthContext';

const LOCAL_STORAGE_KEY_BREAKDOWN_ITEMS = 'breakdownItems';
const LOCAL_STORAGE_KEY_ESTIMATOR_HISTORY = 'finishEstimatorHistory';
const LOCAL_STORAGE_KEY_ACCURACY_HISTORY = 'scanCheckAccuracyHistory';
const LOCAL_STORAGE_KEY_ERROR_RECORDS = 'countErrorTrackerRecords';
const LOCAL_STORAGE_KEY_COUNT_INFO = 'countToolHubInfo';

export default function HomePage() {
  const { toast } = useToast();
  const { user, isAuthenticated, isLoading: isAuthLoading, login } = useAuth();

  const [countInfo, setCountInfo] = useState<CountInfo>({
    countDate: '',
    clientName: '',
    siteName: '',
    countManagerName: '',
    week1Units: undefined,
    sohUnits: undefined,
  });
  const [isCountInfoInitialized, setIsCountInfoInitialized] = useState(false);

  const breakdownDescription = "Create a breakdown of stock count locations for importing into an existing custom database tool.";
  const scanCheckDescription = "Track quality control metrics in real-time with this accuracy calculator that processes unit counts, checks, and error rates to display precision percentage.";
  const finishEstimatorDescription = "Location-based count time estimator. Calculates completion time factoring in progress and breaks.";
  const countErrorTrackerDescription = "Log and categorize counting errors to identify trends and improve accuracy.";
  const tescoClientDataDescription = "Admin-only section for tools and data related to Tesco.";


  useEffect(() => {
    try {
      const storedInfo = localStorage.getItem(LOCAL_STORAGE_KEY_COUNT_INFO);
      if (storedInfo) {
        const parsedInfo = JSON.parse(storedInfo);
        setCountInfo({
          countDate: parsedInfo.countDate || '',
          clientName: parsedInfo.clientName || '',
          siteName: parsedInfo.siteName || '',
          countManagerName: parsedInfo.countManagerName || '',
          week1Units: parsedInfo.week1Units === null ? undefined : (Number(parsedInfo.week1Units) || undefined),
          sohUnits: parsedInfo.sohUnits === null ? undefined : (Number(parsedInfo.sohUnits) || undefined),
        });
      }
    } catch (error) {
      console.error("Error loading count info from localStorage:", error);
      toast({
        title: "Error Loading Count Info",
        description: "Could not load count information from your browser.",
        variant: "destructive",
      });
    }
    setIsCountInfoInitialized(true);
  }, [toast]);

  useEffect(() => {
    if (isCountInfoInitialized) {
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY_COUNT_INFO, JSON.stringify(countInfo));
      } catch (error) {
        console.error("Error saving count info to localStorage:", error);
        toast({
          title: "Error Saving Count Info",
          description: "Could not save count information to your browser.",
          variant: "destructive",
        });
      }
    }
  }, [countInfo, isCountInfoInitialized, toast]);


  const handleClearAllData = useCallback(() => {
    try {
      localStorage.removeItem(LOCAL_STORAGE_KEY_BREAKDOWN_ITEMS);
      localStorage.removeItem(LOCAL_STORAGE_KEY_ESTIMATOR_HISTORY);
      localStorage.removeItem(LOCAL_STORAGE_KEY_ACCURACY_HISTORY);
      localStorage.removeItem(LOCAL_STORAGE_KEY_ERROR_RECORDS);
      localStorage.removeItem(LOCAL_STORAGE_KEY_COUNT_INFO); 

      setCountInfo({
        countDate: '',
        clientName: '',
        siteName: '',
        countManagerName: '',
        week1Units: undefined,
        sohUnits: undefined,
      }); 
      
      toast({
        title: "All Data Cleared",
        description: "All saved data from tools (Breakdown, Finish Estimator, Scan Check, Error Tracker) and count information has been removed from browser storage.",
      });
    } catch (error) {
      console.error("Error clearing data from localStorage:", error);
      toast({
        title: "Error Clearing Data",
        description: "Could not clear all data from your browser's storage.",
        variant: "destructive",
      });
    }
  }, [toast]);

  const handleCountInfoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type } = e.target;
    if (type === 'number') {
      setCountInfo(prev => ({ ...prev, [name]: value === '' ? undefined : Number(value) }));
    } else {
      setCountInfo(prev => ({ ...prev, [name]: value }));
    }
  };
  
  if (isAuthLoading || !isCountInfoInitialized) {
    return (
      <div className="container mx-auto px-4 py-12 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">Loading application...</p>
      </div>
    );
  }

  if (!isAuthenticated && !isAuthLoading) {
     // This part is handled by AuthContext's redirect for unauthenticated users.
     // If it reaches here, it's likely a brief moment before redirect or if redirect fails.
    return (
      <div className="container mx-auto px-4 py-12 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-lg text-muted-foreground">Redirecting to login...</p>
        {/* Login button is in SiteHeader, but a fallback could be here if needed */}
      </div>
    );
  }


  return (
    <div className="container mx-auto px-4 py-12 flex flex-col items-center text-center min-h-[calc(100vh-150px)] justify-start">
      
      <h1 className="text-4xl md:text-5xl font-bold mb-6 text-primary">
        Welcome to Your Count Tool Hub!
      </h1>
      <p className="text-lg text-muted-foreground mb-10 max-w-2xl">
        This is the central portal for your application tools. Explore the features available below.
        {user && <span className="block text-sm mt-1">Logged in as: {user.name || user.email}</span>}
      </p>

      <div className="w-full max-w-6xl mb-8 grid grid-cols-1 md:grid-cols-3 gap-8">
        <Card className="md:col-span-2 p-6 rounded-lg border bg-card text-card-foreground shadow-lg hover:shadow-xl transition-shadow duration-300 flex flex-col text-left h-full hover:border-primary/50">
          <CardHeader className="p-0 pb-4">
            <CardTitle className="text-xl font-semibold text-primary flex items-center gap-2"><UserCog className="h-6 w-6"/>Count Information & Hub Functions</CardTitle>
            <CardDescription className="text-sm text-muted-foreground">Enter key details about the current count, view reports, or clear all application data.</CardDescription>
          </CardHeader>
          <CardContent className="p-0 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-1">
                <Label htmlFor="countDate">Count Date</Label>
                <Input
                  id="countDate"
                  name="countDate"
                  type="date"
                  value={countInfo.countDate}
                  onChange={handleCountInfoChange}
                  className="bg-background"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="clientName">Client Name</Label>
                <Input
                  id="clientName"
                  name="clientName"
                  type="text"
                  placeholder="Enter client name"
                  value={countInfo.clientName}
                  onChange={handleCountInfoChange}
                  className="bg-background"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="siteName">Site Name</Label>
                <Input
                  id="siteName"
                  name="siteName"
                  type="text"
                  placeholder="Enter site name/number"
                  value={countInfo.siteName}
                  onChange={handleCountInfoChange}
                  className="bg-background"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="countManagerName">Count Manager Name</Label>
                <Input
                  id="countManagerName"
                  name="countManagerName"
                  type="text"
                  placeholder="Enter count manager's name"
                  value={countInfo.countManagerName}
                  onChange={handleCountInfoChange}
                  className="bg-background"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="week1Units">Week-1 Units</Label>
                <Input
                  id="week1Units"
                  name="week1Units"
                  type="number"
                  placeholder="Enter Week-1 Units"
                  value={countInfo.week1Units === undefined ? '' : countInfo.week1Units}
                  onChange={handleCountInfoChange}
                  className="bg-background"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="sohUnits">SOH Units</Label>
                <Input
                  id="sohUnits"
                  name="sohUnits"
                  type="number"
                  placeholder="Enter SOH Units"
                  value={countInfo.sohUnits === undefined ? '' : countInfo.sohUnits}
                  onChange={handleCountInfoChange}
                  className="bg-background"
                />
              </div>
            </div>
            <div className="pt-4 flex flex-col sm:flex-row gap-3">
              <Link href="/report" passHref className="flex-1 block">
                <Button variant="outline" className="w-full">
                  <ReportIcon className="mr-2 h-4 w-4" /> View Consolidated Report
                </Button>
              </Link>
              <AlertDialog>
                <AlertDialogTrigger asChild className="flex-1">
                  <Button variant="destructive" className="w-full">
                    <Trash2 className="mr-2 h-4 w-4" /> Clear All Saved Data
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                      This will permanently delete all saved data for Count Information, the Breakdown tool, Finish Estimator, Scan Check Accuracy Calculator, and Count Error Tracker tools from your browser. This action cannot be undone.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleClearAllData} className="bg-destructive hover:bg-destructive/90">
                      Yes, clear all data
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          </CardContent>
        </Card>

        <Card className="md:col-span-1 p-6 rounded-lg border bg-card text-card-foreground shadow-lg hover:shadow-xl transition-shadow duration-300 flex flex-col text-left h-full hover:border-primary/50">
          <CardHeader className="p-0 pb-4">
            <CardTitle className="text-xl font-semibold text-primary flex items-center gap-2"><ExternalLink className="h-6 w-6" />Helpful Links</CardTitle>
            <CardDescription className="text-sm text-muted-foreground">Quick access to relevant resources.</CardDescription>
          </CardHeader>
          <CardContent className="p-0 flex-grow flex flex-col items-stretch justify-start space-y-3 pt-2">
             <Button asChild variant="outline" className="justify-start text-left">
                <a href="https://clientmatrix.retailassetsolutions.com/login.aspx?ref=/default.aspx" target="_blank" rel="noopener noreferrer">
                    <img src="/clientmatrix-logo.ico" alt="ClientMatrix Logo" className="mr-2 h-4 w-4 object-contain" />
                    ClientMatrix
                </a>
            </Button>
            <Button asChild variant="outline" className="justify-start text-left">
                <a href="https://start2.rasgateway.co.uk/Web/" target="_blank" rel="noopener noreferrer">
                    <ExternalLink className="mr-2 h-4 w-4" /> START2 Central
                </a>
            </Button>
            <Button asChild variant="outline" className="justify-start text-left">
                <a href="http://localhost/RAS-Start/" target="_blank" rel="noopener noreferrer">
                    <ExternalLink className="mr-2 h-4 w-4" /> START2 Local
                </a>
            </Button>
            <Button asChild variant="outline" className="justify-start text-left">
                <a href="https://outlook.office.com/mail/" target="_blank" rel="noopener noreferrer">
                    <Mail className="mr-2 h-4 w-4" /> Email
                </a>
            </Button>
            <Button asChild variant="outline" className="justify-start text-left">
                <a href="https://retailassetsolutions.formstack.com/forms/tesco_dept_signoff" target="_blank" rel="noopener noreferrer">
                    <ExternalLink className="mr-2 h-4 w-4" /> Tesco Walk-Off Form
                </a>
            </Button>
            <Button asChild variant="outline" className="justify-start text-left">
                <a href="https://fieldpower.retailassetsolutions.com/PROST/" target="_blank" rel="noopener noreferrer">
                    <LayoutGrid className="mr-2 h-4 w-4" /> FieldPower
                </a>
            </Button>
          </CardContent>
        </Card>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-7xl w-full mb-8">
        {user?.role !== 'contracts' && (
          <CardLink 
            href="/breakdown"
            icon={<Boxes className="h-8 w-8 mb-3 text-primary" />}
            title="Breakdown Tool"
            description={breakdownDescription}
          />
        )}
        <CardLink 
          href="/tasktimer"
          icon={<Timer className="h-8 w-8 mb-3 text-primary" />}
          title="Finish Estimator"
          description={finishEstimatorDescription}
        />
        <CardLink 
          href="/scan-check-calculator" 
          icon={<Calculator className="h-8 w-8 mb-3 text-primary" />}
          title="Scan Check Accuracy Calculator"
          description={scanCheckDescription}
        />
         <CardLink 
          href="/count-error-tracker"
          icon={<ShieldAlert className="h-8 w-8 mb-3 text-primary" />}
          title="Count Error Tracker"
          description={countErrorTrackerDescription}
        />
        {user?.role === 'admin' && (
          <CardLink 
            href="/tesco-client-data"
            icon={<Briefcase className="h-8 w-8 mb-3 text-primary" />}
            title="Tesco Client Data"
            description={tescoClientDataDescription}
          />
        )}
      </div>
    </div>
  );
}

interface CardLinkProps {
  href: string;
  icon: React.ReactNode;
  title: string;
  description: string;
  disabled?: boolean;
}

function CardLink({ href, icon, title, description, disabled }: CardLinkProps) {
  const content = (
    <div className={`p-6 rounded-lg border bg-card text-card-foreground shadow-lg hover:shadow-xl transition-shadow duration-300 flex flex-col items-center text-center h-full ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:border-primary/50'}`}>
      {icon}
      <h2 className="text-xl font-semibold mb-2 text-primary">{title}</h2>
      <p className="text-sm text-muted-foreground leading-relaxed flex-grow">{description}</p>
      {!disabled && <ArrowRight className="mt-4 h-5 w-5 text-primary self-end" />}
    </div>
  );

  if (disabled) {
    return <div className="cursor-not-allowed h-full">{content}</div>;
  }

  return (
    <Link href={href} className="block h-full">
      {content}
    </Link>
  );
}
    

    

