'use client'

import React, { useState, useEffect } from 'react';
import { Button } from '@alga-psa/ui/components/Button';
import { Plus, MoreVertical } from "lucide-react";
import { IServiceCategory, IStandardServiceCategory } from '@alga-psa/types';
import { 
  getServiceCategories, 
  createServiceCategory,
  updateServiceCategory,
  deleteServiceCategory
} from '@alga-psa/billing/actions';
import { getAvailableReferenceData, importReferenceData, checkImportConflicts, ImportConflict } from '@alga-psa/reference-data/actions';
import { toast } from 'react-hot-toast';
import { handleError } from '@alga-psa/ui/lib/errorHandling';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import { Dialog, DialogContent } from '@alga-psa/ui/components/Dialog';
import { Input } from '@alga-psa/ui/components/Input';
import { Label } from '@alga-psa/ui/components/Label';
import { Checkbox } from '@alga-psa/ui/components/Checkbox';
import { DataTable } from '@alga-psa/ui/components/DataTable';
import { ColumnDefinition } from '@alga-psa/types';
import { ConfirmationDialog } from '@alga-psa/ui/components/ConfirmationDialog';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@alga-psa/ui/components/DropdownMenu';

const ServiceCategoriesSettings: React.FC = () => {
  const { t } = useTranslation('msp/billing-settings');
  const [categories, setCategories] = useState<IServiceCategory[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [deleteDialog, setDeleteDialog] = useState<{
    isOpen: boolean;
    categoryId: string;
    categoryName: string;
  }>({
    isOpen: false,
    categoryId: '',
    categoryName: ''
  });
  
  // State for Add/Edit Dialog
  const [showAddEditDialog, setShowAddEditDialog] = useState(false);
  const [editingCategory, setEditingCategory] = useState<IServiceCategory | null>(null);
  const [formData, setFormData] = useState({
    category_name: '',
    description: '',
    display_order: 0
  });
  
  // State for Import Dialog
  const [showImportDialog, setShowImportDialog] = useState(false);
  const [availableReferenceCategories, setAvailableReferenceCategories] = useState<IStandardServiceCategory[]>([]);
  const [selectedImportCategories, setSelectedImportCategories] = useState<string[]>([]);
  const [importConflicts, setImportConflicts] = useState<ImportConflict[]>([]);
  const [conflictResolutions, setConflictResolutions] = useState<Record<string, { action: 'skip' | 'rename' | 'reorder', newName?: string, newOrder?: number }>>({});

  // 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();
  }, []);

  const fetchCategories = async () => {
    try {
      const allCategories = await getServiceCategories();
      setCategories(allCategories);
    } catch (error) {
      console.error('Error fetching service categories:', error);
      setError(t('serviceCategories.errors.fetch', { defaultValue: 'Failed to fetch service categories' }));
    }
  };

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

  const handleDeleteCategory = async () => {
    try {
      if (!deleteDialog.categoryId) {
        toast.error(t('serviceCategories.errors.missingId', { defaultValue: 'Category ID is missing' }));
        return;
      }
      await deleteServiceCategory(deleteDialog.categoryId);
      toast.success(t('serviceCategories.toast.deleted', {
        defaultValue: 'Service category deleted successfully'
      }));
      await fetchCategories();
    } catch (error) {
      handleError(error, t('serviceCategories.errors.delete', {
        defaultValue: 'Failed to delete service category'
      }));
    } finally {
      setDeleteDialog({ isOpen: false, categoryId: '', categoryName: '' });
    }
  };

  const handleSaveCategory = async () => {
    try {
      if (!formData.category_name.trim()) {
        setError(t('serviceCategories.errors.nameRequired', { defaultValue: 'Category name is required' }));
        return;
      }

      if (editingCategory) {
        if (!editingCategory.category_id) {
          setError(t('serviceCategories.errors.missingId', { defaultValue: 'Category ID is missing' }));
          return;
        }
        await updateServiceCategory(editingCategory.category_id, formData);
        toast.success(t('serviceCategories.toast.updated', {
          defaultValue: 'Service category updated successfully'
        }));
      } else {
        await createServiceCategory(formData);
        toast.success(t('serviceCategories.toast.created', {
          defaultValue: 'Service category created successfully'
        }));
      }
      
      setShowAddEditDialog(false);
      setEditingCategory(null);
      setFormData({ category_name: '', description: '', display_order: 0 });
      await fetchCategories();
    } catch (error) {
      console.error('Error saving service category:', error);
      setError(
        error instanceof Error
          ? error.message
          : t('serviceCategories.errors.save', { defaultValue: 'Failed to save service category' })
      );
    }
  };

  const handleImport = async () => {
    try {
      if (importConflicts.length > 0) {
        await importReferenceData('service_categories', selectedImportCategories, undefined, conflictResolutions);
      } else {
        const conflicts = await checkImportConflicts('service_categories', selectedImportCategories);
        if (conflicts.length > 0) {
          setImportConflicts(conflicts);
          return;
        }
        await importReferenceData('service_categories', selectedImportCategories);
      }
      
      toast.success(t('serviceCategories.toast.imported', {
        defaultValue: 'Service categories imported successfully'
      }));
      setShowImportDialog(false);
      setSelectedImportCategories([]);
      setImportConflicts([]);
      setConflictResolutions({});
      await fetchCategories();
    } catch (error) {
      handleError(error, t('serviceCategories.errors.import', {
        defaultValue: 'Failed to import service categories'
      }));
    }
  };

  const columns: ColumnDefinition<IServiceCategory>[] = [
    {
      title: t('common.columns.name', { defaultValue: 'Name' }),
      dataIndex: 'category_name',
      render: (value: string) => (
        <span className="text-[rgb(var(--color-text-700))] font-medium">{value}</span>
      ),
    },
    {
      title: t('common.columns.description', { defaultValue: 'Description' }),
      dataIndex: 'description',
      render: (value: string | null) => (
        <span className="text-muted-foreground">{value || t('common.emptyValue', { defaultValue: '-' })}</span>
      ),
    },
    {
      title: t('common.columns.order', { defaultValue: 'Order' }),
      dataIndex: 'display_order',
      render: (value: number) => (
        <span className="text-muted-foreground">{value}</span>
      ),
    },
    {
      title: t('common.columns.actions', { defaultValue: 'Actions' }),
      dataIndex: 'category_id',
      width: '10%',
      render: (value: string | null, record: IServiceCategory) => {
        if (!value) {
          return null;
        }
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button id="service-category-actions" variant="ghost" className="h-8 w-8 p-0">
                <MoreVertical className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => startEditing(record)}>
                {t('common.actions.edit', { defaultValue: 'Edit' })}
              </DropdownMenuItem>
              <DropdownMenuItem 
                onClick={() => setDeleteDialog({
                  isOpen: true,
                  categoryId: value,
                  categoryName: record.category_name
                })}
                className="text-red-600"
              >
                {t('common.actions.delete', { defaultValue: 'Delete' })}
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];

  return (
    <div className="bg-card p-6 rounded-lg shadow-sm">
      <div>
        <h3 className="text-lg font-semibold mb-4 text-[rgb(var(--color-text-800))]">
          {t('serviceCategories.title', { defaultValue: 'Service Categories' })}
        </h3>
        {error && (
          <Alert variant="destructive" className="mb-4">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}
        <DataTable
          id="service-categories-table"
          data={categories}
          columns={columns}
          pagination={true}
          currentPage={currentPage}
          onPageChange={setCurrentPage}
          pageSize={pageSize}
          onItemsPerPageChange={handlePageSizeChange}
        />
        <div className="mt-4 flex gap-2">
          <Button 
            id="add-service-category"
            onClick={() => {
              setEditingCategory(null);
              setFormData({ category_name: '', description: '', display_order: categories.length + 1 });
              setShowAddEditDialog(true);
            }} 
            className="bg-primary-500 text-white hover:bg-primary-600"
          >
            <Plus className="h-4 w-4 mr-2" />
            {t('serviceCategories.actions.add', { defaultValue: 'Add Service Category' })}
          </Button>
          <Button 
            id="import-service-categories"
            variant="outline"
            onClick={async () => {
              try {
                const available = await getAvailableReferenceData('service_categories');
                setAvailableReferenceCategories(available || []);
                setSelectedImportCategories([]);
                setShowImportDialog(true);
              } catch (error) {
                handleError(error, t('serviceCategories.import.fetchError', {
                  defaultValue: 'Failed to fetch available service categories for import'
                }));
              }
            }}
          >
            {t('serviceCategories.actions.importFromStandard', {
              defaultValue: 'Import from Standard Categories'
            })}
          </Button>
        </div>
      </div>

      <ConfirmationDialog
        isOpen={deleteDialog.isOpen}
        onClose={() => setDeleteDialog({ isOpen: false, categoryId: '', categoryName: '' })}
        onConfirm={handleDeleteCategory}
        title={t('serviceCategories.dialog.deleteTitle', { defaultValue: 'Delete Service Category' })}
        message={t('serviceCategories.delete.message', {
          defaultValue: 'Are you sure you want to delete "{{name}}"? This action cannot be undone.',
          name: deleteDialog.categoryName
        })}
        confirmLabel={t('common.actions.delete', { defaultValue: 'Delete' })}
      />

      {/* Add/Edit Dialog */}
      <Dialog
        isOpen={showAddEditDialog}
        onClose={() => {
          setShowAddEditDialog(false);
          setEditingCategory(null);
          setFormData({ category_name: '', description: '', display_order: 0 });
          setError(null);
        }}
        title={editingCategory
          ? t('serviceCategories.dialog.editTitle', { defaultValue: 'Edit Service Category' })
          : t('serviceCategories.dialog.addTitle', { defaultValue: 'Add Service Category' })}
        footer={(
          <div className="flex justify-end space-x-2">
            <Button
              id="cancel-service-category"
              variant="outline"
              onClick={() => {
                setShowAddEditDialog(false);
                setEditingCategory(null);
                setFormData({ category_name: '', description: '', display_order: 0 });
                setError(null);
              }}
            >
              {t('common.actions.cancel', { defaultValue: 'Cancel' })}
            </Button>
            <Button id="save-service-category" onClick={handleSaveCategory}>
              {editingCategory
                ? t('serviceCategories.actions.update', { defaultValue: 'Update' })
                : t('serviceCategories.actions.create', { defaultValue: 'Create' })}
            </Button>
          </div>
        )}
      >
        <DialogContent>
          <div className="space-y-4">
            {error && (
              <Alert variant="destructive">
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}
            <div>
              <Label htmlFor="category_name">
                {t('serviceCategories.fields.categoryName.label', { defaultValue: 'Category Name *' })}
              </Label>
              <Input
                id="category_name"
                value={formData.category_name}
                onChange={(e) => setFormData({ ...formData, category_name: e.target.value })}
                placeholder={t('serviceCategories.fields.categoryName.placeholder', {
                  defaultValue: 'Enter category name'
                })}
              />
            </div>
            <div>
              <Label htmlFor="description">
                {t('serviceCategories.fields.description.label', { defaultValue: 'Description' })}
              </Label>
              <Input
                id="description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder={t('serviceCategories.fields.description.placeholder', {
                  defaultValue: 'Enter description'
                })}
              />
            </div>
            <div>
              <Label htmlFor="display_order">
                {t('serviceCategories.fields.displayOrder.label', { defaultValue: '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('serviceCategories.fields.displayOrder.placeholder', {
                  defaultValue: 'Enter display order'
                })}
              />
              <p className="text-xs text-muted-foreground mt-1">
                {t('serviceCategories.fields.displayOrder.help', {
                  defaultValue: 'Controls the order in which service categories appear in dropdown menus throughout the platform. Lower numbers appear first.'
                })}
              </p>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Import Dialog */}
      <Dialog
        isOpen={showImportDialog && importConflicts.length === 0}
        onClose={() => {
          setShowImportDialog(false);
          setSelectedImportCategories([]);
        }}
        title={t('serviceCategories.import.title', { defaultValue: 'Import Standard Service Categories' })}
        footer={(
          <div className="flex justify-end space-x-2">
            <Button
              id="cancel-import"
              variant="outline"
              onClick={() => {
                setShowImportDialog(false);
                setSelectedImportCategories([]);
              }}
            >
              {t('common.actions.cancel', { defaultValue: 'Cancel' })}
            </Button>
            <Button
              id="import-selected"
              onClick={handleImport}
              disabled={selectedImportCategories.length === 0}
            >
              {t('common.actions.importSelected', { defaultValue: 'Import Selected' })}
            </Button>
          </div>
        )}
      >
        <DialogContent>
          <div className="space-y-4">
            {!availableReferenceCategories || availableReferenceCategories.length === 0 ? (
              <p className="text-muted-foreground">
                {t('serviceCategories.import.empty', {
                  defaultValue: 'No standard service categories available to import.'
                })}
              </p>
            ) : (
              <>
                <p className="text-sm text-muted-foreground">
                  {t('serviceCategories.import.description', {
                    defaultValue: 'Select standard service categories to import into your organization:'
                  })}
                </p>
                <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"
                        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('common.columns.name', { defaultValue: 'Name' })}</div>
                    <div className="flex-1">{t('common.columns.description', { defaultValue: 'Description' })}</div>
                    <div className="w-20 text-center">{t('common.columns.order', { defaultValue: 'Order' })}</div>
                  </div>
                  <div className="max-h-[300px] overflow-y-auto">
                    {availableReferenceCategories.map((category) => (
                      <div
                        key={category.id}
                        className="flex items-center space-x-2 p-2 hover:bg-muted/30 border-b"
                      >
                        <div className="w-8 [&>div]:mb-0">
                          <Checkbox
                            id={`import-category-${category.id}`}
                            checked={selectedImportCategories.includes(category.id)}
                            onChange={(e) => {
                              if ((e.target as HTMLInputElement).checked) {
                                setSelectedImportCategories([...selectedImportCategories, category.id]);
                              } else {
                                setSelectedImportCategories(selectedImportCategories.filter(id => id !== category.id));
                              }
                            }}
                          />
                        </div>
                        <div className="flex-1">{category.category_name}</div>
                        <div className="flex-1 text-sm text-muted-foreground">
                          {category.description || t('common.emptyValue', { defaultValue: '-' })}
                        </div>
                        <div className="w-20 text-center text-sm text-muted-foreground">
                          {category.display_order}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>
        </DialogContent>
      </Dialog>

      {/* Conflict Resolution Dialog */}
      <Dialog
        isOpen={importConflicts.length > 0}
        onClose={() => {
          setImportConflicts([]);
          setConflictResolutions({});
        }}
        title={t('import.title', { defaultValue: 'Resolve Import Conflicts' })}
        footer={(
          <div className="flex justify-end space-x-2">
            <Button
              id="cancel-conflicts"
              variant="outline"
              onClick={() => {
                setImportConflicts([]);
                setConflictResolutions({});
              }}
            >
              {t('common.actions.cancel', { defaultValue: 'Cancel' })}
            </Button>
            <Button id="import-with-resolutions" onClick={handleImport}>
              {t('common.actions.importWithResolutions', { defaultValue: 'Import with Resolutions' })}
            </Button>
          </div>
        )}
      >
        <DialogContent>
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              {t('serviceCategories.conflicts.description', {
                defaultValue: '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 referenceItem = conflict.referenceItem as IStandardServiceCategory;
                const itemId = referenceItem.id;
                const resolution = conflictResolutions[itemId];
                
                return (
                  <div key={itemId} className="border rounded-lg p-4 space-y-3">
                    <div className="font-medium">{referenceItem.category_name}</div>
                    
                    {conflict.conflictType === 'name' && (
                      <div className="space-y-2">
                        <p className="text-sm text-muted-foreground">
                          {t('serviceCategories.conflicts.nameExists', {
                            defaultValue: '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('import.skipItem', { defaultValue: '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: referenceItem.category_name + ' (2)' }
                              })}
                            />
                            <span>{t('serviceCategories.conflicts.rename', { defaultValue: '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('serviceCategories.conflicts.orderInUse', {
                            defaultValue: 'Display order {{displayOrder}} is already in use.',
                            displayOrder: 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('serviceCategories.conflicts.reorder', {
                              defaultValue: 'Import with order {{order}}',
                              order: conflict.suggestedOrder
                            })}
                          </span>
                        </label>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default ServiceCategoriesSettings;
