
"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, CalendarCheck, ListFilter } from 'lucide-react';
import { saveCountPlans, fetchCountPlans, type SaveCountPlansOutput, type FetchCountPlansOutput } from '@/ai/flows/countPlansFlow';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from '@/components/ui/scroll-area';

const DISPLAY_COLUMNS_COUNT_PLANS = [
  { key: "Store_No", label: "Store No" },
  { key: "Store_Name", label: "Store Name" },
  { key: "MST_Date", label: "Original MST Date" },
  { key: "Plan", label: "Plan Type" },
  { key: "_Calculated_Count_Date", label: "Calculated Count Date" },
  { key: "_Calculated_Arrival_Date", label: "Calculated Arrival Date" },
];

export default function CountPlansPage() {
  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<SaveCountPlansOutput | 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 fetchCountPlans();
      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 Count Plans data:", error);
      setStoredData([]);
      toast({
        title: "Error Fetching Data",
        description: error.message || "Could not load stored Count Plans 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 saveCountPlans({ pastedData });
      setLastSaveResult(result);

      if (result.success) {
        toast({
          title: "Count Plans Data Processed",
          description: result.message || `Successfully processed ${result.itemCount || 0} records.`,
        });
        const now = new Date().toISOString();
        localStorage.setItem('countPlansLastUpdated', now);
        window.dispatchEvent(new StorageEvent('storage', {
            key: 'countPlansLastUpdated',
            newValue: now
        }));
        loadStoredData(); // Refresh table
        setPastedData(''); // Clear textarea
      } else {
        toast({
          title: "Error Processing Count Plans",
          description: result.message || "An unknown error occurred.",
          variant: "destructive",
        });
      }
    } catch (error: any) {
      console.error("Error calling saveCountPlans flow:", error);
      toast({
        title: "Flow Execution Error",
        description: error.message || "Failed to execute the save count plans 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">
            <CalendarCheck className="h-7 w-7" /> Tesco Count Plans
          </CardTitle>
          <CardDescription>
            Paste tab-separated data from Excel. Data should be in sections titled &quot;Exclude Fresh Plan&quot; or &quot;Include Fresh Plan&quot;.
            Each section should have headers: Store No, Store Name, MST Date. The tool will treat &quot;MST Date&quot; as the Count Date, derive an &quot;Arrival Date&quot; (MST Date - 1 day), and store both derived dates.
            Any column explicitly named &quot;Supplier&quot; will be ignored. 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 multi-section, tab-separated data here (e.g., Exclude Fresh Plan title, then headers & data, then Include Fresh Plan title, then headers & data)..."
              rows={15}
              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 Count Plans
          </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 Count Plans Data</CardTitle>
          <CardDescription>
            Currently stored Count Plans 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_COUNT_PLANS.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_COUNT_PLANS.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 Count Plans data uploaded yet or table is empty.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
    
