'use client';

import { useEffect, useState } from 'react';
import { Button } from '@alga-psa/ui/components/Button';
import { Plus, MoreVertical, CornerDownRight } from "lucide-react";
import type { ITicketCategory, DeletionValidationResult } from '@alga-psa/types';
import {
  getAllCategories,
  updateCategory,
  deleteCategory,
  validateCategoryDeletion
} from '@alga-psa/tickets/actions';
import { getAllBoards } from '@alga-psa/tickets/actions';
import type { IBoard } from '@alga-psa/types';
import { getAvailableReferenceData, importReferenceData, checkImportConflicts, type ImportConflict } from '@alga-psa/reference-data/actions';
import { toast } from 'react-hot-toast';
import { handleError } from '@alga-psa/ui/lib/errorHandling';
import { Dialog, DialogContent } from '@alga-psa/ui/components/Dialog';
import { Input } from '@alga-psa/ui/components/Input';
import { Checkbox } from '@alga-psa/ui/components/Checkbox';
import { Label } from '@alga-psa/ui/components/Label';
import { DataTable } from '@alga-psa/ui/components/DataTable';
import type { ColumnDefinition } from '@alga-psa/types';
import { DeleteEntityDialog } from '@alga-psa/ui';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@alga-psa/ui/components/DropdownMenu';
import CustomSelect from '@alga-psa/ui/components/CustomSelect';
import QuickAddCategory from '../QuickAddCategory';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

const CategoriesSettings = (): React.JSX.Element => {
  const { t } = useTranslation('features/tickets');
  const [categories, setCategories] = useState<ITicketCategory[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [deleteDialog, setDeleteDialog] = useState({
    isOpen: false,
    categoryId: '',
    categoryName: ''
  });
  const [deleteValidation, setDeleteValidation] = useState<DeletionValidationResult | null>(null);
  const [isDeleteValidating, setIsDeleteValidating] = useState(false);
  const [isDeleteProcessing, setIsDeleteProcessing] = useState(false);
  
  // State for Add/Edit Dialog
  const [showAddEditDialog, setShowAddEditDialog] = useState(false);
  const [editingCategory, setEditingCategory] = useState<ITicketCategory | null>(null);
  const [formData, setFormData] = useState({
    category_name: '',
    display_order: 0,
    board_id: '',
    parent_category: ''
  });
  
  // State for Import Dialog
  const [showImportDialog, setShowImportDialog] = useState(false);
  const [availableReferenceCategories, setAvailableReferenceCategories] = useState<any[]>([]);
  const [selectedImportCategories, setSelectedImportCategories] = useState<string[]>([]);
  const [importConflicts, setImportConflicts] = useState<ImportConflict[]>([]);
  const [conflictResolutions, setConflictResolutions] = useState<Record<string, { action: 'skip' | 'rename' | 'reorder', newName?: string, newOrder?: number }>>({});
  const [importTargetBoard, setImportTargetBoard] = useState<string>('');
  const [boards, setBoards] = useState<IBoard[]>([]);
  const [boardFilter, setBoardFilter] = useState<string>('all');

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // Handle page size change - reset to page 1
  const handlePageSizeChange = (newPageSize: number) => {
    setPageSize(newPageSize);
    setCurrentPage(1);
  };

  useEffect(() => {
    fetchCategories();
    fetchBoards();
  }, []);

  const fetchCategories = async () => {
    try {
      const allCategories = await getAllCategories();
      // Organize categories hierarchically
      const parentCategories = allCategories
        .filter(cat => !cat.parent_category)
        .sort((a, b) => (a.display_order || 0) - (b.display_order || 0));
      
      const organizedCategories: ITicketCategory[] = [];
      
      parentCategories.forEach(parent => {
        organizedCategories.push(parent);
        // Add children immediately after parent, sorted by their display_order
        const children = allCategories
          .filter(cat => cat.parent_category === parent.category_id)
          .sort((a, b) => (a.display_order || 0) - (b.display_order || 0));
        organizedCategories.push(...children);
      });
      
      setCategories(organizedCategories);
    } catch (error) {
      console.error('Error fetching categories:', error);
      setError(t('settings.categories.fetchFailed', 'Failed to fetch categories'));
    }
  };

  const fetchBoards = async () => {
    try {
      const allBoards = await getAllBoards();
      setBoards(allBoards.filter(ch => !ch.is_inactive));
    } catch (error) {
      console.error('Error fetching boards:', error);
    }
  };

  const startEditing = (category: ITicketCategory) => {
    setEditingCategory(category);
    setFormData({
      category_name: category.category_name,
      display_order: category.display_order || 0,
      board_id: category.board_id || '',
      parent_category: category.parent_category || ''
    });
    setShowAddEditDialog(true);
    setError(null);
  };

  const resetDeleteDialog = () => {
    setDeleteDialog({ isOpen: false, categoryId: '', categoryName: '' });
    setDeleteValidation(null);
    setIsDeleteValidating(false);
    setIsDeleteProcessing(false);
  };

  const openDeleteDialog = async (category: ITicketCategory) => {
    setDeleteDialog({
      isOpen: true,
      categoryId: category.category_id,
      categoryName: category.category_name
    });
    setIsDeleteValidating(true);
    try {
      const validation = await validateCategoryDeletion(category.category_id);
      setDeleteValidation(validation);
    } catch (error) {
      console.error('Error validating category deletion:', error);
        setDeleteValidation({
          canDelete: false,
          code: 'VALIDATION_FAILED',
          message: error instanceof Error
            ? error.message
            : t('settings.categories.validateDeleteFailed', 'Failed to validate category deletion.'),
          dependencies: [],
          alternatives: []
        });
    } finally {
      setIsDeleteValidating(false);
    }
  };

  const handleDeleteCategory = async (force = false) => {
    setIsDeleteProcessing(true);
    try {
      const result = await deleteCategory(deleteDialog.categoryId, force);

      if (result.deleted || result.success) {
        toast.success(result.message || t('settings.categories.deleteSuccess', 'Category deleted successfully'));
        resetDeleteDialog();
        await fetchCategories();
        return;
      }

      setDeleteValidation(result);
    } catch (error) {
      handleError(error, t('settings.categories.deleteFailed', 'Failed to delete category'));
      resetDeleteDialog();
    } finally {
      setIsDeleteProcessing(false);
    }
  };

  const handleDeleteAlternativeAction = async (action: string) => {
    if (action === 'force_delete') {
      await handleDeleteCategory(true);
    }
  };

  const handleSaveCategory = async () => {
    try {
      if (!editingCategory) {
        return;
      }

      if (!formData.category_name.trim()) {
        setError(t('settings.categories.nameRequired', 'Category name is required'));
        return;
      }

      const updateData: any = {
        category_name: formData.category_name,
        display_order: formData.display_order
      };
      
      if (!editingCategory.parent_category) {
        updateData.board_id = formData.board_id;
      }
      
      await updateCategory(editingCategory.category_id, updateData);
      toast.success(t('settings.categories.saveSuccess', 'Category updated successfully'));
      
      setShowAddEditDialog(false);
      setEditingCategory(null);
      setFormData({ category_name: '', display_order: 0, board_id: '', parent_category: '' });
      await fetchCategories();
    } catch (error) {
      console.error('Error saving category:', error);
      setError(error instanceof Error ? error.message : t('settings.categories.saveFailed', 'Failed to save category'));
    }
  };

  const handleImport = async () => {
    try {
      if (!importTargetBoard) {
        toast.error(t('settings.categories.importBoardRequired', 'Please select a board for the imported categories'));
        return;
      }

      // Check if any selected subcategories don't have their parent selected
      const selectedSubcategories = availableReferenceCategories.filter(cat => 
        selectedImportCategories.includes(cat.id) && cat.parent_category_uuid
      );
      
      const missingParents = selectedSubcategories.filter(subcat => {
        const parentId = subcat.parent_category_uuid;
        return !selectedImportCategories.includes(parentId);
      });
      
      if (missingParents.length > 0) {
        const parentNames = missingParents.map(subcat => {
          const parent = availableReferenceCategories.find(c => c.id === subcat.parent_category_uuid);
          return parent?.category_name || t('settings.categories.name', 'Name');
        });
        toast.error(
          t(
            'settings.categories.importMissingParents',
            'Cannot import subcategories without their parent categories. Please also select: {{parents}}',
            { parents: [...new Set(parentNames)].join(', ') }
          )
        );
        return;
      }

      const importOptions = { board_id: importTargetBoard };
      
      if (importConflicts.length > 0) {
        await importReferenceData('categories', selectedImportCategories, importOptions, conflictResolutions);
      } else {
        const conflicts = await checkImportConflicts('categories', selectedImportCategories, importOptions);
        if (conflicts.length > 0) {
          setImportConflicts(conflicts);
          return;
        }
        await importReferenceData('categories', selectedImportCategories, importOptions);
      }
      
      toast.success(t('settings.categories.importSuccess', 'Categories imported successfully'));
      setShowImportDialog(false);
      setSelectedImportCategories([]);
      setImportTargetBoard('');
      setImportConflicts([]);
      setConflictResolutions({});
      await fetchCategories();
    } catch (error) {
      handleError(error, t('settings.categories.importFailed', 'Failed to import categories'));
    }
  };

  // Filter categories based on selected board while maintaining hierarchy
  const getFilteredCategories = () => {
    if (boardFilter === 'all') {
      return categories;
    }
    
    // Filter and reorganize to maintain parent-child structure
    const allFilteredCategories = categories.filter(cat => cat.board_id === boardFilter);
    const filteredParents = allFilteredCategories
      .filter(cat => !cat.parent_category)
      .sort((a, b) => (a.display_order || 0) - (b.display_order || 0));
    
    const organized: ITicketCategory[] = [];
    filteredParents.forEach(parent => {
      organized.push(parent);
      const children = allFilteredCategories
        .filter(cat => cat.parent_category === parent.category_id)
        .sort((a, b) => (a.display_order || 0) - (b.display_order || 0));
      organized.push(...children);
    });
    
    return organized;
  };
  
  const filteredCategories = getFilteredCategories();

  const columns: ColumnDefinition<ITicketCategory>[] = [
    {
      title: t('settings.categories.name', 'Name'),
      dataIndex: 'category_name',
      render: (value: string, record: ITicketCategory) => (
        <div className="flex items-center">
          {record.parent_category && (
            <CornerDownRight className="h-3 w-3 text-muted-foreground mr-2 ml-4" />
          )}
          <span className={`text-gray-700 font-medium ${record.parent_category ? '' : 'font-semibold'}`}>
            {value}
          </span>
          {record.is_from_itil_standard && (
            <span className="ml-2 px-1.5 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 rounded">
              {t('categories.itilBadge')}
            </span>
          )}
        </div>
      ),
    },
    {
      title: t('fields.board', 'Board'),
      dataIndex: 'board_id',
      render: (value: string) => {
        const board = boards.find(ch => ch.board_id === value);
        return <span className="text-gray-600">{board?.board_name || '-'}</span>;
      },
    },
    {
      title: t('settings.categories.orderColumn', 'Order'),
      dataIndex: 'display_order',
      render: (value: number, record: ITicketCategory) => {
        if (!record.parent_category) {
          // For parent categories, show their main order
          return <span className="text-gray-700 font-semibold">{value}</span>;
        } else {
          // For subcategories, show their order within the parent
          const parentCategory = categories.find(cat => cat.category_id === record.parent_category);
          const siblingSubcategories = categories
            .filter(cat => cat.parent_category === record.parent_category)
            .sort((a, b) => (a.display_order || 0) - (b.display_order || 0));
          const orderWithinParent = siblingSubcategories.findIndex(cat => cat.category_id === record.category_id) + 1;
          
          return (
            <div className="flex items-center pl-4">
              <CornerDownRight className="h-3 w-3 text-muted-foreground mr-2" />
              <span className="text-gray-500 dark:text-gray-400 text-sm bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded">
                {orderWithinParent}
              </span>
            </div>
          );
        }
      },
    },
    {
      title: t('settings.display.columns.actions', 'Actions'),
      dataIndex: 'category_id',
      width: '10%',
      render: (value: string, record: ITicketCategory) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button id={`category-${value}-actions-button`} variant="ghost" className="h-8 w-8 p-0">
              <MoreVertical className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              id={`edit-category-${value}-button`}
              onClick={() => startEditing(record)}>
              {t('actions.edit', 'Edit')}
            </DropdownMenuItem>
            <DropdownMenuItem
              id={`delete-category-${value}-button`}
              onClick={() => openDeleteDialog(record)}
              className="text-red-600"
            >
              {t('actions.delete', 'Delete')}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  return (
    <div className="bg-white p-6 rounded-lg shadow-sm">
      <div>
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-semibold text-gray-800">{t('settings.categories.title', 'Categories')}</h3>
          <CustomSelect
            value={boardFilter}
            onValueChange={setBoardFilter}
            options={[
              { value: 'all', label: t('settings.categories.allBoards', 'All Boards') },
              ...boards.map(ch => ({
                value: ch.board_id || '',
                label: ch.board_name || ''
              }))
            ]}
            placeholder={t('settings.categories.filterByBoard', 'Filter by board')}
            className="w-64"
          />
        </div>
        {error && (
          <Alert variant="destructive" className="mb-4">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}
        <DataTable
          id="categories-settings-table"
          data={filteredCategories}
          columns={columns}
          pagination={true}
          currentPage={currentPage}
          onPageChange={setCurrentPage}
          pageSize={pageSize}
          onItemsPerPageChange={handlePageSizeChange}
        />
        <div className="mt-4 flex gap-2">
          <Button 
            id="add-category-button"
            onClick={() => {
              setEditingCategory(null);
              // Start with empty form - order will be calculated based on parent selection
              setFormData({ category_name: '', display_order: 0, board_id: '', parent_category: '' });
              setShowAddEditDialog(true);
              setError(null);
            }} 
            className="bg-primary-500 text-white hover:bg-primary-600"
          >
            <Plus className="h-4 w-4 mr-2" /> {t('settings.categories.addCategory', 'Add Category')}
          </Button>
          <Button 
            id="import-categories-button"
            variant="outline"
            onClick={async () => {
              try {
                const available = await getAvailableReferenceData('categories');
                setAvailableReferenceCategories(available || []);
                setSelectedImportCategories([]);
                setShowImportDialog(true);
              } catch (error) {
                handleError(error, t('settings.categories.fetchAvailableFailed', 'Failed to fetch available categories for import'));
              }
            }}
          >
            {t('settings.categories.importStandardCategories', 'Import from Standard Categories')}
          </Button>
        </div>
      </div>

      <DeleteEntityDialog
        id="delete-category-dialog"
        isOpen={deleteDialog.isOpen}
        onClose={resetDeleteDialog}
        onConfirmDelete={() => handleDeleteCategory(false)}
        onAlternativeAction={handleDeleteAlternativeAction}
        entityName={deleteDialog.categoryName || t('fields.category', 'Category')}
        validationResult={deleteValidation}
        isValidating={isDeleteValidating}
        isDeleting={isDeleteProcessing}
      />

      <QuickAddCategory
        isOpen={showAddEditDialog && !editingCategory}
        onClose={() => {
          setShowAddEditDialog(false);
          setEditingCategory(null);
          setError(null);
        }}
        onCategoryCreated={async () => {
          setShowAddEditDialog(false);
          setEditingCategory(null);
          await fetchCategories();
        }}
        categories={categories}
        boards={boards}
      />

      {editingCategory && (() => {
        const editFooter = (
          <div className="flex justify-end space-x-2">
            <Button
              id="cancel-category-dialog"
              variant="outline"
              onClick={() => {
                setShowAddEditDialog(false);
                setEditingCategory(null);
                setFormData({ category_name: '', display_order: 0, board_id: '', parent_category: '' });
                setError(null);
              }}
            >
              {t('actions.cancel', 'Cancel')}
            </Button>
            <Button id="save-category-button" onClick={handleSaveCategory}>
              {t('actions.update', 'Update')}
            </Button>
          </div>
        );
        return (
        <Dialog
          isOpen={showAddEditDialog}
          onClose={() => {
            setShowAddEditDialog(false);
            setEditingCategory(null);
            setFormData({ category_name: '', display_order: 0, board_id: '', parent_category: '' });
            setError(null);
          }}
          title={t('settings.categories.editTitle', 'Edit Category')}
          footer={editFooter}
        >
          <DialogContent>
            <div className="space-y-4">
              {error && (
                <Alert variant="destructive">
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}
              <div>
                <Label htmlFor="category_name">{t('settings.categories.categoryName', 'Category Name *')}</Label>
                <Input
                  id="category_name"
                  value={formData.category_name}
                  onChange={(e) => setFormData({ ...formData, category_name: e.target.value })}
                  placeholder={t('settings.categories.enterCategoryName', 'Enter category name')}
                />
              </div>
              {!editingCategory.parent_category && (
                <>
                  <div>
                    <Label htmlFor="board_id">{t('fields.board', 'Board')}</Label>
                    <CustomSelect
                      value={formData.board_id}
                      onValueChange={(value) => setFormData({ ...formData, board_id: value })}
                      options={boards
                        .filter(ch => ch.category_type !== 'itil')
                        .map(ch => ({
                          value: ch.board_id || '',
                          label: ch.board_name || ''
                        }))}
                      placeholder={t('settings.categories.selectBoard', 'Select a board')}
                      className="w-full"
                    />
                  </div>
                  {formData.board_id !== editingCategory.board_id && (
                    <Alert>
                      <AlertDescription>
                        {t('settings.categories.boardChangeWarning', 'Changing the board for this parent category will also update all its subcategories to the same board.')}
                      </AlertDescription>
                    </Alert>
                  )}
                </>
              )}
              <div>
                <Label htmlFor="display_order">{t('settings.categories.displayOrder', 'Display Order')}</Label>
                <Input
                  id="display_order"
                  type="number"
                  value={formData.display_order}
                  onChange={(e) => setFormData({ ...formData, display_order: parseInt(e.target.value) || 0 })}
                  placeholder={t('settings.categories.enterDisplayOrder', 'Enter display order')}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  {t('settings.categories.displayOrderHelp', 'Controls the order in which categories appear in dropdown menus throughout the platform. Lower numbers appear first.')}
                </p>
              </div>
            </div>
          </DialogContent>
        </Dialog>
        );
      })()}

      {/* Import Dialog */}
      {(() => {
        const importFooter = (
          <div className="flex justify-end space-x-2">
            <Button
              id="cancel-import-categories-dialog"
              variant="outline"
              onClick={() => {
                setShowImportDialog(false);
                setSelectedImportCategories([]);
                setImportTargetBoard('');
              }}
            >
              {t('actions.cancel', 'Cancel')}
            </Button>
            <Button
              id="import-selected-categories"
              onClick={handleImport}
              disabled={selectedImportCategories.length === 0 || !importTargetBoard}
            >
              {t('settings.categories.importSelected', 'Import Selected')}
            </Button>
          </div>
        );
        return (
      <Dialog
        isOpen={showImportDialog && importConflicts.length === 0}
        onClose={() => {
          setShowImportDialog(false);
          setSelectedImportCategories([]);
          setImportTargetBoard('');
        }}
        title={t('settings.categories.importTitle', 'Import Standard Categories')}
        className="max-w-3xl"
        footer={importFooter}
      >
        <DialogContent>
          <div className="space-y-4">
            {!availableReferenceCategories || availableReferenceCategories.length === 0 ? (
              <p className="text-muted-foreground">{t('settings.categories.noStandardCategories', 'No standard categories available to import.')}</p>
            ) : (
              <>
                <p className="text-sm text-muted-foreground">
                  {t('settings.categories.importDescription', 'Select standard categories to import into your organization:')}
                </p>
                
                <div className="space-y-2">
                  <label className="text-sm font-medium">{t('settings.categories.targetBoard', 'Target Board *')}</label>
                  <CustomSelect
                    value={importTargetBoard}
                    onValueChange={setImportTargetBoard}
                    options={boards
                      .filter(ch => ch.category_type !== 'itil')
                      .map(ch => ({
                        value: ch.board_id || '',
                        label: ch.board_name || ''
                      }))}
                    placeholder={t('settings.categories.targetBoardPlaceholder', 'Select a board for imported categories')}
                    className="w-full"
                  />
                  <p className="text-xs text-muted-foreground">
                    {t('settings.categories.targetBoardHelp', 'All imported categories will be assigned to this board')}
                  </p>
                </div>
                <div className="border rounded-md">
                  <div className="flex items-center space-x-2 p-2 bg-muted/50 font-medium text-sm border-b">
                    <div className="w-8 [&>div]:mb-0">
                      <Checkbox
                        id="select-all-categories-checkbox"
                        checked={availableReferenceCategories.length > 0 && selectedImportCategories.length === availableReferenceCategories.length}
                        onChange={(e) => {
                          if ((e.target as HTMLInputElement).checked) {
                            setSelectedImportCategories(availableReferenceCategories.map(cat => cat.id));
                          } else {
                            setSelectedImportCategories([]);
                          }
                        }}
                      />
                    </div>
                    <div className="flex-1">{t('settings.categories.nameColumn', 'Name')}</div>
                    <div className="flex-1">{t('settings.categories.descriptionColumn', 'Description')}</div>
                    <div className="w-24 text-center">{t('settings.categories.orderColumn', 'Order')}</div>
                  </div>
                  <div className="max-h-[350px] overflow-y-auto">
                    {(() => {
                      // Organize categories hierarchically
                      const parentCategories = availableReferenceCategories.filter(cat => !cat.parent_category_uuid);
                      const organizedCategories: any[] = [];
                      
                      parentCategories.forEach(parent => {
                        organizedCategories.push(parent);
                        // Add children immediately after parent
                        const children = availableReferenceCategories.filter(
                          cat => cat.parent_category_uuid === parent.id
                        );
                        organizedCategories.push(...children);
                      });
                      
                      return organizedCategories.map((category) => {
                        const isSubcategory = !!category.parent_category_uuid;
                        
                        // Calculate order display for subcategories
                        let orderDisplay: React.ReactNode;
                        if (isSubcategory) {
                          const siblingSubcategories = organizedCategories.filter(
                            cat => cat.parent_category_uuid === category.parent_category_uuid
                          );
                          const orderWithinParent = siblingSubcategories.findIndex(cat => cat.id === category.id) + 1;
                          orderDisplay = (
                            <div className="flex items-center justify-end pr-4">
                              <CornerDownRight className="h-3 w-3 text-muted-foreground mr-1" />
                              <span className="text-gray-500 dark:text-gray-400 text-xs bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded">
                                {orderWithinParent}
                              </span>
                            </div>
                          );
                        } else {
                          orderDisplay = (
                            <span className="font-normal">{category.display_order}</span>
                          );
                        }
                        
                        return (
                        <div 
                          key={category.id} 
                          className={`flex items-center space-x-2 p-2 hover:bg-muted/30 border-b ${
                            isSubcategory ? 'pl-8' : ''
                          }`}
                        >
                          <div className="w-8 [&>div]:mb-0">
                            <Checkbox
                              id={`select-category-${category.id}-checkbox`}
                              checked={selectedImportCategories.includes(category.id)}
                              onChange={(e) => {
                                if ((e.target as HTMLInputElement).checked) {
                                  const categoriesToAdd = [category.id];
                                  
                                  // If selecting a subcategory, ensure parent is also selected
                                  if (isSubcategory && !selectedImportCategories.includes(category.parent_category_uuid)) {
                                    categoriesToAdd.push(category.parent_category_uuid);
                                  }
                                  
                                  // If selecting a parent category, also select its children
                                  if (!isSubcategory) {
                                    const children = availableReferenceCategories.filter(
                                      c => c.parent_category_uuid === category.id
                                    );
                                    categoriesToAdd.push(...children.map(c => c.id));
                                  }
                                  
                                  setSelectedImportCategories([
                                    ...selectedImportCategories,
                                    ...categoriesToAdd.filter(id => !selectedImportCategories.includes(id))
                                  ]);
                                } else {
                                  // If deselecting a parent category, also deselect its children
                                  const categoriesToRemove = [category.id];
                                  if (!isSubcategory) {
                                    const children = availableReferenceCategories.filter(
                                      c => c.parent_category_uuid === category.id
                                    );
                                    categoriesToRemove.push(...children.map(c => c.id));
                                  }
                                  setSelectedImportCategories(
                                    selectedImportCategories.filter(id => !categoriesToRemove.includes(id))
                                  );
                                }
                              }}
                            />
                          </div>
                          <div className="flex-1 flex items-center">
                            {isSubcategory && <CornerDownRight className="h-3 w-3 text-muted-foreground mr-2" />}
                            <span className={isSubcategory ? 'text-sm font-normal' : 'text-sm font-semibold'}>
                              {category.category_name}
                            </span>
                          </div>
                          <div className="flex-1 text-sm text-muted-foreground">
                            {category.description || '-'}
                          </div>
                          <div className="w-24 text-center text-sm text-muted-foreground">
                            {orderDisplay}
                          </div>
                        </div>
                      );
                    });
                    })()}
                  </div>
                </div>
              </>
            )}
          </div>
        </DialogContent>
      </Dialog>
        );
      })()}

      {/* Conflict Resolution Dialog */}
      {(() => {
        const conflictFooter = (
          <div className="flex justify-end space-x-2">
            <Button
              id="cancel-categories-conflict-dialog"
              variant="outline"
              onClick={() => {
                setImportConflicts([]);
                setConflictResolutions({});
              }}
            >
              {t('actions.cancel', 'Cancel')}
            </Button>
            <Button id="import-categories-with-resolutions" onClick={handleImport}>
              {t('settings.categories.importWithResolutions', 'Import With Resolutions')}
            </Button>
          </div>
        );
        return (
      <Dialog
        isOpen={importConflicts.length > 0}
        onClose={() => {
          setImportConflicts([]);
          setConflictResolutions({});
        }}
        title={t('settings.categories.conflictsTitle', 'Resolve Import Conflicts')}
        footer={conflictFooter}
      >
        <DialogContent>
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              {t('settings.categories.importConflictDescription', 'The following items have conflicts. Choose how to resolve each:')}
            </p>
            <div className="space-y-4 max-h-[400px] overflow-y-auto">
              {importConflicts.map((conflict) => {
                const itemId = conflict.referenceItem.id;
                const resolution = conflictResolutions[itemId];
                
                return (
                  <div key={itemId} className="border rounded-lg p-4 space-y-3">
                    <div className="font-medium">{conflict.referenceItem.category_name}</div>
                    
                    {conflict.conflictType === 'name' && (
                      <div className="space-y-2">
                        <p className="text-sm text-muted-foreground">
                          {t('settings.categories.categoryNameConflict', 'A category with this name already exists.')}
                        </p>
                        <div className="space-y-2">
                          <label className="flex items-center space-x-2">
                            <input
                              type="radio"
                              name={`conflict-${itemId}`}
                              checked={resolution?.action === 'skip'}
                              onChange={() => setConflictResolutions({
                                ...conflictResolutions,
                                [itemId]: { action: 'skip' }
                              })}
                            />
                            <span>{t('settings.categories.skipItem', 'Skip this item')}</span>
                          </label>
                          <label className="flex items-center space-x-2">
                            <input
                              type="radio"
                              name={`conflict-${itemId}`}
                              checked={resolution?.action === 'rename'}
                              onChange={() => setConflictResolutions({
                                ...conflictResolutions,
                                [itemId]: { action: 'rename', newName: conflict.referenceItem.category_name + ' (2)' }
                              })}
                            />
                            <span>{t('settings.categories.renameTo', 'Import with new name:')}</span>
                          </label>
                          {resolution?.action === 'rename' && (
                            <Input
                              value={resolution.newName || ''}
                              onChange={(e) => setConflictResolutions({
                                ...conflictResolutions,
                                [itemId]: { ...resolution, newName: e.target.value }
                              })}
                              className="ml-6"
                            />
                          )}
                        </div>
                      </div>
                    )}
                    
                    {conflict.conflictType === 'order' && (
                      <div className="space-y-2">
                        <p className="text-sm text-muted-foreground">
                          {t(
                            'settings.categories.displayOrderConflict',
                            'Display order {{order}} is already in use.',
                            { order: conflict.referenceItem.display_order }
                          )}
                        </p>
                        <label className="flex items-center space-x-2">
                          <input
                            type="radio"
                            name={`conflict-${itemId}`}
                            checked={resolution?.action === 'reorder'}
                            onChange={() => setConflictResolutions({
                              ...conflictResolutions,
                              [itemId]: { action: 'reorder', newOrder: conflict.suggestedOrder }
                            })}
                          />
                          <span>
                            {t('settings.categories.importWithOrder', 'Import with order {{order}}', {
                              order: conflict.suggestedOrder,
                            })}
                          </span>
                        </label>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </DialogContent>
      </Dialog>
        );
      })()}
    </div>
  );
};

export default CategoriesSettings;
