/**
 * ValidationToolbar Component
 *
 * Provides filtering, template selection, and action buttons.
 *
 * PERFORMANCE NOTE: This component must NOT subscribe to the rows array!
 * Using useRows() or hooks that depend on it (like useValidationActions,
 * useSelectedRowIndices) causes re-render on EVERY cell change, making
 * dropdowns extremely slow. Instead, use getState() for one-time reads.
 */

import { useMemo, useCallback, useState } from 'react';
import { Search, Plus, FolderPlus, Edit3, X } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { useValidationStore } from '../store/validationStore';
import {
  useFilters,
  useFields,
} from '../store/selectors';
import { CreateProductCategoryDialog, type CreatedCategoryInfo } from '../../../CreateProductCategoryDialog';
import { SearchProductTemplateDialog } from '@/components/templates/SearchProductTemplateDialog';
import { useTemplateManagement } from '../hooks/useTemplateManagement';
import { SaveSessionButton } from '../../../components/SaveSessionDialog';

interface ValidationToolbarProps {
  rowCount: number;
  errorCount: number;
  rowsWithErrors: number;
}

export const ValidationToolbar = ({
  rowCount,
  errorCount,
  rowsWithErrors,
}: ValidationToolbarProps) => {
  const filters = useFilters();
  const fields = useFields();

  // Compute filtered count when filtering is active
  const filteredCount = useMemo(() => {
    const isFiltering = filters.searchText || filters.showErrorsOnly;
    if (!isFiltering) return rowCount;

    const { rows, errors } = useValidationStore.getState();
    let count = 0;

    rows.forEach((row, index) => {
      // Apply search filter
      if (filters.searchText) {
        const searchLower = filters.searchText.toLowerCase();
        const matches = Object.values(row).some((value) =>
          String(value ?? '').toLowerCase().includes(searchLower)
        );
        if (!matches) return;
      }

      // Apply errors-only filter
      if (filters.showErrorsOnly) {
        const rowErrors = errors.get(index);
        if (!rowErrors || Object.keys(rowErrors).length === 0) return;
      }

      count++;
    });

    return count;
  }, [filters.searchText, filters.showErrorsOnly, rowCount]);

  const isFiltering = filters.searchText || filters.showErrorsOnly;

  // State for the product search template dialog
  const [isSearchDialogOpen, setIsSearchDialogOpen] = useState(false);

  // Get template management hook for reloading templates
  const { loadTemplates } = useTemplateManagement();

  // Store actions - get directly, no subscription needed
  const setSearchText = useValidationStore((state) => state.setSearchText);
  const setShowErrorsOnly = useValidationStore((state) => state.setShowErrorsOnly);
  const setProductLines = useValidationStore((state) => state.setProductLines);
  const setSublines = useValidationStore((state) => state.setSublines);

  // Extract companies from field options
  const companyOptions = useMemo(() => {
    const companyField = fields.find((f) => f.key === 'company');
    if (!companyField || companyField.fieldType.type !== 'select') return [];
    const opts = companyField.fieldType.options || [];
    return opts.map((opt) => ({
      label: opt.label,
      value: opt.value,
    }));
  }, [fields]);

  // PERFORMANCE: Get addRow at action time
  const handleAddRow = useCallback(() => {
    useValidationStore.getState().addRow();
  }, []);

  // Handle category creation - refresh the cache
  const handleCategoryCreated = useCallback(
    async (info: CreatedCategoryInfo) => {
      if (info.type === 'line') {
        // A new product line was created under a company
        // Refresh the productLinesCache for that company
        const companyId = info.parentId;
        const { productLinesCache } = useValidationStore.getState();
        const existingLines = productLinesCache.get(companyId) || [];

        // Add the new line to the cache
        const newOption = {
          label: info.name,
          value: info.id || info.name,
        };
        setProductLines(companyId, [...existingLines, newOption]);
      } else {
        // A new subline was created under a line
        // Refresh the sublinesCache for that line
        const lineId = info.parentId;
        const { sublinesCache } = useValidationStore.getState();
        const existingSublines = sublinesCache.get(lineId) || [];

        // Add the new subline to the cache
        const newOption = {
          label: info.name,
          value: info.id || info.name,
        };
        setSublines(lineId, [...existingSublines, newOption]);
      }
    },
    [setProductLines, setSublines]
  );

  return (
    <div className="border-b bg-background px-4 py-3">
      {/* Top row: Search, product count, and action buttons */}
      <div className="flex items-center gap-4 mb-3">
        {/* Search */}
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Filter products..."
            value={filters.searchText}
            onChange={(e) => setSearchText(e.target.value)}
            className={filters.searchText ? "pl-9 pr-8" : "pl-9"}
          />
          {filters.searchText && (
            <button
              type="button"
              onClick={() => setSearchText('')}
              className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
              aria-label="Clear search"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>

        {/* Product count */}
        <span className="text-sm text-muted-foreground">
          {isFiltering ? `${filteredCount} of ${rowCount} products shown` : `${rowCount} products`}
        </span>

        {/* Action buttons */}
        <div className="flex items-center gap-2 ml-auto">
          {/* Save session */}
          <SaveSessionButton />

          {/* Add row */}
          <Button variant="outline" size="sm" onClick={() => handleAddRow()}>
            <Plus className="h-4 w-4 mr-1" />
            Add Blank Row
          </Button>

          {/* Create template from existing product */}
          <Button
            variant="outline"
            size="sm"
            onClick={() => setIsSearchDialogOpen(true)}
          >
            <Edit3 className="h-4 w-4 mr-1" />
            New Template
          </Button>

          {/* Create product line/subline */}
          <CreateProductCategoryDialog
            trigger={
              <Button variant="outline" size="sm">
                <FolderPlus className="h-4 w-4 mr-1" />
                New Line/Subline
              </Button>
            }
            companies={companyOptions}
            onCreated={handleCategoryCreated}
          />
        </div>
      </div>

      {/* Bottom row: Error badge and filter toggle */}
      {errorCount > 0 && (
      <div className="flex items-center justify-center gap-3 text-sm text-muted-foreground border border-destructive rounded-md p-2 bg-destructive/10">
        <div className="flex items-center gap-12">
          
            <Badge variant="destructive">
              {errorCount} issues in {rowsWithErrors} rows
            </Badge>
       
          {/* Error filter toggle */}
          <div className="flex items-center gap-2">
            <Switch
              id="show-errors"
              checked={filters.showErrorsOnly}
              onCheckedChange={setShowErrorsOnly}
              className="data-[state=checked]:bg-destructive data-[state=unchecked]:bg-destructive/20"
            />
            <Label htmlFor="show-errors" className="text-sm cursor-pointer text-destructive">
              Show errors only
            </Label>
          </div>
        </div>
      </div>
         )}

      {/* Product Search Template Dialog */}
      <SearchProductTemplateDialog
        isOpen={isSearchDialogOpen}
        onClose={() => setIsSearchDialogOpen(false)}
        onTemplateCreated={loadTemplates}
      />
    </div>
  );
};
