
"use client";

import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { Loader2, ShieldAlert, Save, Info, BarChartHorizontalBig, ListFilter } from 'lucide-react';
import { saveExpectedUnits, fetchExpectedUnits, type SaveExpectedUnitsOutput, type FetchExpectedUnitsOutput } from '@/ai/flows/expectedUnitsFlow';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from '@/components/ui/scroll-area';

const DISPLAY_COLUMNS_EXPECTED_UNITS = [
  { key: "Store_Number", label: "Store Number" },
  { key: "Store_Name", label: "Store Name" },
  { key: "Arrival_Date", label: "Original Input Date" }, 
  { key: "Estimated_units", label: "Estimated Units" },
  { key: "Expected_Counters", label: "Expected Counters" },
  { key: "_Calculated_Count_Date", label: "Calculated Count Date" },
  { key: "_Calculated_Arrival_Date", label: "Calculated Arrival Date" },
];

export default function ExpectedUnitsPage() {
  const { user, isLoading: isAuthLoading, isAuthenticated } = useAuth();
  const router = useRouter();
  const { toast } = useToast();

  const [pastedData, setPastedData] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [lastSaveResult, setLastSaveResult] = useState<SaveExpectedUnitsOutput | null>(null);

  const [storedData, setStoredData] = useState<Array<Record<string, any>> | null>(null);
  const [isLoadingTableData, setIsLoadingTableData] = useState(true);

  const loadStoredData = useCallback(async () => {
    setIsLoadingTableData(true);
    try {
      const result = await fetchExpectedUnits();
      if (result.success && result.results) {
        setStoredData(result.results);
      } else {
        setStoredData([]);
        if (result.message && !result.message.includes("not found")) {
          toast({
            title: "Info",
            description: result.message,
            variant: "default",
          });
        }
      }
    } catch (error: any) {
      console.error("Error fetching Expected Units data:", error);
      setStoredData([]);
      toast({
        title: "Error Fetching Data",
        description: error.message || "Could not load stored Expected Units information.",
        variant: "destructive",
      });
    } finally {
      setIsLoadingTableData(false);
    }
  }, [toast]);

  useEffect(() => {
    if (isAuthenticated && user?.role === 'admin') {
      loadStoredData();
    }
  }, [isAuthenticated, user, loadStoredData]);

  const handleSaveData = async () => {
    if (!pastedData.trim()) {
      toast({
        title: "No Data Provided",
        description: "Please paste data into the text area.",
        variant: "destructive",
      });
      return;
    }

    setIsSaving(true);
    setLastSaveResult(null);
    try {
      const result = await saveExpectedUnits({ pastedData });
      setLastSaveResult(result);

      if (result.success) {
        toast({
          title: "Expected Units Data Processed",
          description: result.message || `Successfully processed ${result.itemCount || 0} records.`,
        });
        const now = new Date().toISOString();
        localStorage.setItem('expectedUnitsLastUpdated', now);
        window.dispatchEvent(new StorageEvent('storage', {
            key: 'expectedUnitsLastUpdated',
            newValue: now
        }));
        loadStoredData(); // Refresh table
        setPastedData(''); // Clear textarea
      } else {
        toast({
          title: "Error Processing Expected Units",
          description: result.message || "An unknown error occurred.",
          variant: "destructive",
        });
      }
    } catch (error: any) {
      console.error("Error calling saveExpectedUnits flow:", error);
      toast({
        title: "Flow Execution Error",
        description: error.message || "Failed to execute the save expected units flow.",
        variant: "destructive",
      });
      setLastSaveResult({ success: false, message: error.message || "Flow execution failed." });
    } finally {
      setIsSaving(false);
    }
  };

  if (isAuthLoading) {
    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">Loading page...</p>
      </div>
    );
  }

  if (!isAuthenticated || user?.role !== 'admin') {
    if (typeof window !== 'undefined') {
      router.push('/auth/denied?reason=admin_only');
    }
    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)]">
        <ShieldAlert className="h-12 w-12 text-destructive animate-pulse mb-4" />
        <p className="text-muted-foreground">Access Denied. Redirecting...</p>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-12 flex flex-col items-center min-h-[calc(100vh-150px)] space-y-8">
      <Card className="w-full max-w-2xl shadow-xl">
        <CardHeader>
          <CardTitle className="text-2xl font-bold text-primary flex items-center gap-2">
            <BarChartHorizontalBig className="h-7 w-7" /> Expected Units Data
          </CardTitle>
          <CardDescription>
             Paste tab-separated data from Excel. Headers like &quot;Store Number&quot;, &quot;Store Name&quot;, &quot;Arrival Date&quot;, &quot;Estimated units&quot;, &quot;Expected Counters&quot; are expected.
             The tool will look for a column named &quot;Count_Date&quot; or &quot;Arrival_Date&quot; (with underscores first, then with spaces) to derive the alternative date and store both.
             Each submission overwrites existing data.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div>
            <Textarea
              id="pastedData"
              value={pastedData}
              onChange={(e) => setPastedData(e.target.value)}
              placeholder="Paste tab-separated data here..."
              rows={10}
              className="bg-background text-sm"
              disabled={isSaving}
            />
          </div>
          <Button onClick={handleSaveData} disabled={isSaving || !pastedData.trim()} className="w-full">
            {isSaving ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            Process and Save Expected Units
          </Button>

          {lastSaveResult && !lastSaveResult.success && (
             <div className="mt-4 p-3 rounded-md text-sm bg-destructive/10 text-destructive">
              <p className="font-semibold flex items-center gap-2"><Info className="h-4 w-4" /> Processing Error</p>
              <p className="break-all mt-1">{lastSaveResult.message}</p>
            </div>
          )}
        </CardContent>
      </Card>

      <Card className="w-full max-w-4xl shadow-xl mt-8">
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><ListFilter /> Stored Expected Units Data</CardTitle>
          <CardDescription>
            Currently stored Expected Units information. Refreshes on load and after successful save.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {isLoadingTableData ? (
             <div className="flex justify-center items-center p-8">
              <Loader2 className="h-8 w-8 text-primary animate-spin" />
              <p className="ml-3 text-muted-foreground">Loading stored data...</p>
            </div>
          ) : storedData && storedData.length > 0 ? (
            <div className="max-h-[600px] overflow-y-auto rounded-md border">
              <div className="overflow-x-auto">
                <table className="min-w-full text-xs">
                  <TableHeader className="bg-muted/50 z-10">
                    <TableRow>
                      {DISPLAY_COLUMNS_EXPECTED_UNITS.map((col) => (
                        <TableHead key={col.key} className="whitespace-nowrap px-3 py-2">{col.label}</TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {storedData.map((record, index) => (
                      <TableRow key={index}>
                        {DISPLAY_COLUMNS_EXPECTED_UNITS.map((col) => (
                           <TableCell key={col.key} className="whitespace-nowrap px-3 py-2">{String((record as any)[col.key] ?? '')}</TableCell>
                        ))}
                      </TableRow>
                    ))}
                  </TableBody>
                </table>
              </div>
            </div>
          ) : (
            <p className="text-center text-muted-foreground p-8">No Expected Units data uploaded yet or table is empty.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

    
