
"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, CalendarDays, ListFilter } from 'lucide-react';
import { saveAmExecInfo, fetchAmExecInfo, type SaveAmExecInfoOutput, type FetchAmExecInfoOutput } from '@/ai/flows/amExecInfoFlow';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from '@/components/ui/scroll-area';

// Helper function to format header keys for display
function formatDisplayHeaderKey(key: string): string {
  return key
    .replace(/_/g, ' ') // Replace underscores with spaces
    .replace(/\b\w/g, char => char.toUpperCase()); // Capitalize first letter of each word
}

export default function AmExecInfoPage() {
  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<SaveAmExecInfoOutput | null>(null);
  
  const [storedData, setStoredData] = useState<Array<Record<string, any>> | null>(null);
  const [tableHeaders, setTableHeaders] = useState<string[]>([]);
  const [isLoadingTableData, setIsLoadingTableData] = useState(true);

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

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

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

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

      if (result.success) {
        toast({
          title: "AM Exec Information Processed",
          description: result.message || `Successfully processed ${result.itemCount || 0} records.`,
        });
        const now = new Date().toISOString();
        localStorage.setItem('amExecInfoLastUpdated', now);
        window.dispatchEvent(new StorageEvent('storage', {
            key: 'amExecInfoLastUpdated',
            newValue: now
        }));
        loadStoredData(); // Refresh the displayed table
        setPastedData(''); // Clear textarea after successful save
      } else {
        toast({
          title: "Error Processing AM Exec Info",
          description: result.message || "An unknown error occurred.",
          variant: "destructive",
        });
      }
    } catch (error: any) {
      console.error("Error calling saveAmExecInfo flow:", error);
      toast({
        title: "Flow Execution Error",
        description: error.message || "Failed to execute the save AM Exec info 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">
            <CalendarDays className="h-7 w-7" /> AM Exec Information
          </CardTitle>
          <CardDescription>
            Paste the complete AM Exec information from Excel (first line should be headers).
            The tool prioritizes a column named &quot;Count_Date&quot; (with underscore) to derive an &apos;Arrival Date&apos; (Count Date - 1 day).
            If &quot;Count_Date&quot; is not found, it will look for &quot;Arrival_Date&quot; (with underscore) to derive a &apos;Count Date&apos; (Arrival Date + 1 day).
            Both derived dates will be stored in new columns: _Calculated_Count_Date and _Calculated_Arrival_Date. 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 AM Exec data here, including headers as the first line..."
              rows={10}
              className="bg-background text-sm"
              disabled={isSaving}
            />
          </div>
          <Button onClick={handleSaveAmExecInfo} 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 AM Exec Info
          </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-words mt-1">{lastSaveResult.message}</p>
            </div>
          )}
        </CardContent>
      </Card>

      <Card className="w-full max-w-6xl shadow-xl mt-8">
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><ListFilter /> Stored AM Exec Data Overview</CardTitle>
          <CardDescription>
            Currently stored AM Exec information. This table refreshes on page load and after each 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 && tableHeaders.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>
                      {tableHeaders.map((header) => (
                        <TableHead key={header} className="whitespace-nowrap px-3 py-2">{formatDisplayHeaderKey(header)}</TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {storedData.map((row, rowIndex) => (
                      <TableRow key={rowIndex}>
                        {tableHeaders.map((header) => (
                          <TableCell key={`${rowIndex}-${header}`} className="whitespace-nowrap px-3 py-2">
                            {String(row[header] ?? '')}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))}
                  </TableBody>
                </table>
              </div>
            </div>
          ) : (
            <p className="text-center text-muted-foreground p-8">No AM Exec data uploaded yet or table is empty.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
    
