
"use client";

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import Link from 'next/link';
import { Loader2, ShieldAlert, ArrowRight, DatabaseZap, Info, CalendarDays, BarChartHorizontalBig, CalendarCheck, Home, ListFilter, Search, Briefcase } from 'lucide-react';
import { format, isValid, parseISO } from 'date-fns';
import { fetchConsolidatedTescoData, type FetchConsolidatedDataOutput, type FetchConsolidatedDataInput } from '@/ai/flows/fetchConsolidatedDataFlow';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Table, TableHeader, TableRow, TableHead, TableCell, TableBody } from "@/components/ui/table";
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';

interface ToolCardProps {
  href: string;
  icon: React.ReactNode;
  title: string;
  description: string;
  lastUpdated?: string | null;
}

function ToolCard({ href, icon, title, description, lastUpdated }: ToolCardProps) {
  return (
    <Link href={href} className="block h-full">
      <Card className="shadow-lg hover:shadow-xl transition-shadow duration-300 flex flex-col text-center h-full hover:border-primary/50">
        <CardHeader className="pt-6 pb-3">
          {icon}
          <CardTitle className="text-xl font-semibold text-primary">{title}</CardTitle>
        </CardHeader>
        <CardContent className="flex-grow pb-3">
          <CardDescription>
            {description}
            {lastUpdated !== undefined && (
              <span className="block text-xs text-muted-foreground/80 mt-2">
                Last updated: <em className="italic">{lastUpdated || "Not yet updated"}</em>
              </span>
            )}
          </CardDescription>
        </CardContent>
        <CardFooter className="pb-4 pt-0 justify-center">
          <ArrowRight className="h-5 w-5 text-primary" />
        </CardFooter>
      </Card>
    </Link>
  );
}

interface RegionOption {
  label: string;
  value: string; // Actual region name
}

const DISPLAY_CONSOLIDATED_HEADERS_CONFIG = [
  { key: "Directory_Store_Number", label: "Store No." },
  { key: "Directory_Store_Name", label: "Store Name" },
  {
    key: "Event_Arrival_Date",
    label: "Arrival Date",
    formatter: (value: any) => {
        if (!value) return '-';
        try {
            let dateToFormat: Date | null = null;
            if (typeof value === 'string') {
                if (/^\d{4}-\d{2}-\d{2}/.test(value)) { 
                    dateToFormat = parseISO(value.substring(0, 10));
                } else if (/^\d{2}\/\d{2}\/\d{4}/.test(value)) { 
                    const parts = value.split('/');
                    dateToFormat = parseISO(`${parts[2]}-${parts[1]}-${parts[0]}`);
                }
            } else if (value instanceof Date) {
                dateToFormat = value;
            }

            if (dateToFormat && isValid(dateToFormat)) {
                return format(dateToFormat, 'dd/MM/yy');
            }
            return String(value); 
        } catch (e) {
            console.warn(`Error formatting date value '${value}':`, e);
            return String(value); 
        }
    }
  },
  { 
    key: "Count_Plans_Plan", 
    label: "Plan", 
    accessor: (row: Record<string, any>) => {
      const plan = row.Count_Plans_Plan;
      if (typeof plan === 'string') {
        if (plan.endsWith(" Fresh Plan")) {
            return plan.replace(" Fresh Plan", "").trim();
        }
      }
      return plan || '-';
    }
  },
  { key: "Expected_Units_Estimated", label: "Expected Units", accessor: (row: Record<string, any>) => row.Expected_Units_Estimated !== null && row.Expected_Units_Estimated !== undefined ? String(row.Expected_Units_Estimated) : '-' },
  { key: "Expected_Units_Counters", label: "Expected Counters", accessor: (row: Record<string, any>) => row.Expected_Units_Counters !== null && row.Expected_Units_Counters !== undefined ? String(row.Expected_Units_Counters) : '-' },
  {
    key: "Exec",
    label: "Exec",
    accessor: (row: Record<string, any>) => row.AM_Exec_Morning_Exec || '-'
  },
  {
    key: "Directory_MST_Supplier_Region",
    label: "Region",
    accessor: (row: Record<string, any>) => row.Directory_MST_Supplier_Region || '-'
  },
];


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

  const [storeDirectoryLastUpdatedTimestamp, setStoreDirectoryLastUpdatedTimestamp] = useState<string | null>(null);
  const [amExecInfoLastUpdatedTimestamp, setAmExecInfoLastUpdatedTimestamp] = useState<string | null>(null);
  const [expectedUnitsLastUpdatedTimestamp, setExpectedUnitsLastUpdatedTimestamp] = useState<string | null>(null);
  const [countPlansLastUpdatedTimestamp, setCountPlansLastUpdatedTimestamp] = useState<string | null>(null);

  const [consolidatedData, setConsolidatedData] = useState<Array<Record<string, any>> | null>(null);
  const [isLoadingConsolidatedData, setIsLoadingConsolidatedData] = useState(true);
  const [consolidatedDataError, setConsolidatedDataError] = useState<string | null>(null);
  
  const [searchStoreNumberInput, setSearchStoreNumberInput] = useState('');
  const [rawUniqueRegions, setRawUniqueRegions] = useState<string[]>([]);
  const [selectedRegionValue, setSelectedRegionValue] = useState<string>("All Regions");

  const displayableRegionOptions: RegionOption[] = useMemo(() => {
    const options: RegionOption[] = [{ label: "All Regions", value: "All Regions" }];
    rawUniqueRegions.slice(0, 6).forEach((regionName) => { // Show up to first 6 actual regions
      options.push({
        label: `Region ${regionName}`, // Label includes "Region" and actual name
        value: regionName,
      });
    });
    return options;
  }, [rawUniqueRegions]);

  const selectedRegionDisplayLabel = useMemo(() => {
    if (selectedRegionValue === "All Regions") return "All Regions";
    const foundOption = displayableRegionOptions.find(opt => opt.value === selectedRegionValue);
    return foundOption ? foundOption.label : "All Regions"; // Fallback
  }, [selectedRegionValue, displayableRegionOptions]);


  const loadTimestampsAndData = useCallback(async () => {
    const formatTs = (ts: string | null) => {
      if (!ts) return null;
      try {
        const date = parseISO(ts);
        return isValid(date) ? format(date, "dd/MM/yy HH:mm") : null;
      } catch (e) { console.warn("Error formatting timestamp:", e); return null; }
    };

    if (typeof window !== 'undefined') {
      setStoreDirectoryLastUpdatedTimestamp(formatTs(localStorage.getItem('tescoStoreDirectoryLastUpdated')));
      setAmExecInfoLastUpdatedTimestamp(formatTs(localStorage.getItem('amExecInfoLastUpdated')));
      setExpectedUnitsLastUpdatedTimestamp(formatTs(localStorage.getItem('expectedUnitsLastUpdated')));
      setCountPlansLastUpdatedTimestamp(formatTs(localStorage.getItem('countPlansLastUpdated')));
    }

    setIsLoadingConsolidatedData(true);
    setConsolidatedDataError(null);
    try {
      const filterInput: FetchConsolidatedDataInput = {};
      if (searchStoreNumberInput.trim()) filterInput.searchStoreNumber = searchStoreNumberInput.trim();
      if (selectedRegionValue && selectedRegionValue !== "All Regions") {
          filterInput.selectedRegion = selectedRegionValue;
      }
      
      const result = await fetchConsolidatedTescoData(filterInput);
      if (result.success) {
        setConsolidatedData(result.results || []);
        if (result.uniqueRegions && JSON.stringify(rawUniqueRegions) !== JSON.stringify(result.uniqueRegions)) {
            setRawUniqueRegions(result.uniqueRegions);
        }
        if ((result.results || []).length === 0 && (searchStoreNumberInput.trim() || (selectedRegionValue && selectedRegionValue !== "All Regions"))) {
            toast({ title: "No Results", description: "No consolidated data found matching your filters.", variant: "default"});
        }
      } else {
        setConsolidatedData([]);
        const errorMsg = result.message || "Failed to fetch consolidated data.";
        setConsolidatedDataError(errorMsg);
        toast({ title: "Error Loading Consolidated Data", description: errorMsg, variant: "destructive"});
      }
    } catch (error: any) {
      console.error("Error fetching consolidated data:", error);
      setConsolidatedData([]);
      const errorMsg = error.message || "An unexpected error occurred while loading consolidated data.";
      setConsolidatedDataError(errorMsg);
      toast({ title: "Fetch Error", description: errorMsg, variant: "destructive" });
    } finally {
      setIsLoadingConsolidatedData(false);
    }
  }, [toast, searchStoreNumberInput, selectedRegionValue, rawUniqueRegions]);

  useEffect(() => {
    if (isAuthenticated && user?.role === 'admin') {
      loadTimestampsAndData();
    } else if (!isAuthLoading && (!isAuthenticated || user?.role !== 'admin')) {
      if (typeof window !== 'undefined') { 
        router.push('/auth/denied?reason=admin_only');
      }
    }

    const handleStorageChange = (event: StorageEvent) => {
      const relevantKeys = [
          'tescoStoreDirectoryLastUpdated', 'amExecInfoLastUpdated', 
          'expectedUnitsLastUpdated', 'countPlansLastUpdated'
      ];
      if ((event.key && relevantKeys.includes(event.key)) || event.key === null) { 
        loadTimestampsAndData();
      }
    };
    if (typeof window !== 'undefined') {
      window.addEventListener('storage', handleStorageChange);
      return () => window.removeEventListener('storage', handleStorageChange);
    }
  }, [loadTimestampsAndData, isAuthenticated, user, isAuthLoading, router]);

  const handleFilterChange = () => {
    loadTimestampsAndData();
  };


  const tools = [
    { 
      href: "/tesco-client-data/store-directory", 
      icon: <ListFilter className="h-10 w-10 mb-3 text-primary mx-auto" />, 
      title: "Store Directory Management", 
      description: "Upload and search the Tesco store directory data.", 
      lastUpdated: storeDirectoryLastUpdatedTimestamp 
    },
    { 
      href: "/tesco-client-data/am-exec-info", 
      icon: <CalendarDays className="h-10 w-10 mb-3 text-primary mx-auto" />, 
      title: "AM Exec Information", 
      description: "Manage AM Exec schedules. Derives Arrival/Count Date.", 
      lastUpdated: amExecInfoLastUpdatedTimestamp 
    },
    { 
      href: "/tesco-client-data/expected-units", 
      icon: <BarChartHorizontalBig className="h-10 w-10 mb-3 text-primary mx-auto" />, 
      title: "Expected Units", 
      description: "Manage expected units and counters. Derives Arrival/Count Date.", 
      lastUpdated: expectedUnitsLastUpdatedTimestamp 
    },
    { 
      href: "/tesco-client-data/count-plans", 
      icon: <CalendarCheck className="h-10 w-10 mb-3 text-primary mx-auto" />, 
      title: "Count Plans", 
      description: "Manage count plans. Arrival Date derived from MST Date.", 
      lastUpdated: countPlansLastUpdatedTimestamp 
    }
  ];

  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 or checking permissions...</p>
      </div>
    );
  }
  
  if (!isAuthenticated || user?.role !== 'admin') {
    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.</p>
      </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 space-y-8">
      <div className="flex items-center justify-center gap-2">
        <Briefcase className="h-10 w-10 text-primary" />
        <h1 className="text-4xl md:text-5xl font-bold text-primary">
          Tesco Client Data Hub
        </h1>
      </div>
      <p className="text-lg text-muted-foreground mb-6 max-w-2xl">
        Admin-only section for tools related to Tesco data management. Data is stored in <code className="font-mono text-sm bg-muted px-1 py-0.5 rounded">tesco_master_data.db</code>.
      </p>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl w-full">
        {tools.map(tool => (
          <ToolCard 
            key={tool.href}
            href={tool.href}
            icon={tool.icon}
            title={tool.title}
            description={tool.description}
            lastUpdated={tool.lastUpdated}
          />
        ))}
      </div>

      <Card className="w-full max-w-7xl shadow-xl mt-8">
        <CardHeader>
          <CardTitle className="text-2xl font-bold text-primary flex items-center gap-2"><DatabaseZap /> Weekly Data Overview</CardTitle>
          <CardDescription>Consolidated view of store activities. Only stores with entries in AM Exec, Expected Units, or Count Plans are shown. Sorted by Arrival Date, then Region, then Store No.</CardDescription>
           <div className="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
            <div>
              <Label htmlFor="searchStoreNumberInput" className="text-left block mb-1 text-sm font-medium">Search Store Number</Label>
              <Input
                id="searchStoreNumberInput"
                type="text"
                placeholder="Enter store number..."
                value={searchStoreNumberInput}
                onChange={(e) => setSearchStoreNumberInput(e.target.value)}
                className="bg-background"
              />
            </div>
            <div>
              <Label htmlFor="selectedRegion" className="text-left block mb-1 text-sm font-medium">Filter by Region</Label>
              <Select 
                value={selectedRegionValue} 
                onValueChange={(value) => setSelectedRegionValue(value)}
                disabled={rawUniqueRegions.length === 0 && selectedRegionValue === "All Regions"} // Disable if no raw regions and "All Regions" is selected
              >
                <SelectTrigger className="bg-background">
                  <SelectValue placeholder="Select region">
                    {selectedRegionDisplayLabel}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent>
                  {displayableRegionOptions.map(option => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Button onClick={handleFilterChange} className="self-end">
              <Search className="mr-2 h-4 w-4" /> Apply Filters / Refresh
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {isLoadingConsolidatedData ? (
            <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 consolidated data...</p>
            </div>
          ) : consolidatedDataError ? (
             <Alert variant="destructive">
              <Info className="h-4 w-4" />
              <AlertTitle>Error Loading Data</AlertTitle>
              <AlertDescription>{consolidatedDataError}</AlertDescription>
            </Alert>
          ) : consolidatedData && consolidatedData.length > 0 ? (
                <div className="max-h-[600px] overflow-y-auto rounded-md border"> {/* Vertical scroll container */}
                    <div className="overflow-x-auto"> {/* Horizontal scroll container */}
                        <table className="min-w-full text-xs">{/* Table itself */}
                        <TableHeader className="bg-muted/50 backdrop-blur-sm z-10">
                            <TableRow>
                            {DISPLAY_CONSOLIDATED_HEADERS_CONFIG.map((headerConfig) => (
                                <TableHead key={headerConfig.key} className="whitespace-nowrap px-3 py-2 text-left">{headerConfig.label}</TableHead>
                            ))}
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {consolidatedData.map((row, rowIndex) => (
                            <TableRow key={rowIndex}>
                                {DISPLAY_CONSOLIDATED_HEADERS_CONFIG.map((headerConfig) => (
                                <TableCell key={`${rowIndex}-${headerConfig.key}`} className="whitespace-nowrap px-3 py-2 text-left">
                                    {headerConfig.formatter
                                    ? headerConfig.formatter(row[headerConfig.key])
                                    : headerConfig.accessor
                                    ? headerConfig.accessor(row)
                                    : String(row[headerConfig.key] ?? '-')}
                                </TableCell>
                                ))}
                            </TableRow>
                            ))}
                        </TableBody>
                        </table>
                    </div>
                </div>
          ) : (
            <p className="text-center text-muted-foreground p-8">No consolidated data available for the current filters. Ensure data has been uploaded to the individual tools.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
