'use client';


import React, { useState, useEffect } from 'react';
import { Button } from '@alga-psa/ui/components/Button';
import { Plus, MoreVertical } from "lucide-react";
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import { getStatuses, deleteStatus, updateStatus } from '@alga-psa/reference-data/actions';
import { importReferenceData, getAvailableReferenceData, checkImportConflicts, type ImportConflict } from '@alga-psa/reference-data/actions';
import { IStatus, IStandardStatus } from '@alga-psa/types';
import { getCurrentUser } from '@alga-psa/user-composition/actions';
import { Switch } from '@alga-psa/ui/components/Switch';
import { DataTable } from '@alga-psa/ui/components/DataTable';
import { ColumnDefinition } from '@alga-psa/types';
import { toast } from 'react-hot-toast';
import { handleError } from '@alga-psa/ui/lib/errorHandling';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@alga-psa/ui/components/DropdownMenu';
import { StatusDialog } from '@alga-psa/reference-data/components';
import { StatusImportDialog } from '@alga-psa/ui/components/settings/dialogs/StatusImportDialog';
import { ConflictResolutionDialog } from '@alga-psa/reference-data/components';
import { DeleteConfirmationDialog } from '@alga-psa/ui/components/settings/dialogs/DeleteConfirmationDialog';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

/**
 * InteractionStatusSettings - Manages interaction statuses
 * This is for interaction statuses only
 */
const InteractionStatusSettings = (): React.JSX.Element => {
  const { t } = useTranslation('msp/settings');
  const STATUS_TYPE = 'interaction'; // Fixed to interaction type

  const [statuses, setStatuses] = useState<IStatus[]>([]);
  const [userId, setUserId] = useState<string>('');
  const [showStatusDialog, setShowStatusDialog] = useState(false);
  const [editingStatus, setEditingStatus] = useState<IStatus | null>(null);
  const [showStatusImportDialog, setShowStatusImportDialog] = useState(false);
  const [availableReferenceStatuses, setAvailableReferenceStatuses] = useState<IStandardStatus[]>([]);
  const [selectedImportStatuses, setSelectedImportStatuses] = useState<string[]>([]);

  // Conflict resolution state
  const [importConflicts, setImportConflicts] = useState<ImportConflict[]>([]);
  const [showConflictDialog, setShowConflictDialog] = useState(false);
  const [conflictResolutions, setConflictResolutions] = useState<Record<string, { action: 'skip' | 'rename' | 'reorder', newName?: string, newOrder?: number }>>({});

  // Delete confirmation state
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [statusToDelete, setStatusToDelete] = useState<IStatus | null>(null);

  // 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(() => {
    const initUser = async () => {
      const user = await getCurrentUser();
      if (user) {
        setUserId(user.user_id);
      }
    };
    initUser();
  }, []);

  useEffect(() => {
    fetchStatuses();
  }, []);

  const fetchStatuses = async (): Promise<void> => {
    try {
      const fetchedStatuses = await getStatuses(STATUS_TYPE);
      setStatuses(fetchedStatuses);
    } catch (error) {
      console.error('Error fetching statuses:', error);
    }
  };

  const updateStatusItem = async (updatedStatus: IStatus): Promise<void> => {
    // Prevent removing the last closed status
    const currentStatus = statuses.find(s => s.status_id === updatedStatus.status_id);
    if (currentStatus?.is_closed && !updatedStatus.is_closed) {
      const otherClosedStatuses = statuses.filter(s =>
        s.status_id !== updatedStatus.status_id && s.is_closed
      );
      if (otherClosedStatuses.length === 0) {
        toast.error(t('interactions.statuses.messages.error.lastClosed'));
        return;
      }
    }

    try {
      await updateStatus(updatedStatus.status_id!, updatedStatus);
      setStatuses(statuses.map((status): IStatus =>
        status.status_id === updatedStatus.status_id ? updatedStatus : status
      ));
      toast.success(t('interactions.statuses.messages.success.updated'));
    } catch (error) {
      handleError(error, 'Failed to update status');
    }
  };

  const handleDeleteStatusRequest = (statusId: string): void => {
    const status = statuses.find(s => s.status_id === statusId);
    if (status) {
      if (status.is_closed) {
        const otherClosedStatuses = statuses.filter(s =>
          s.status_id !== statusId && s.is_closed && s.status_type === status.status_type
        );
        if (otherClosedStatuses.length === 0) {
          toast.error(t('interactions.statuses.messages.error.deleteLastClosed'));
          return;
        }
      }
      setStatusToDelete(status);
      setShowDeleteDialog(true);
    }
  };

  const confirmDeleteStatus = async (): Promise<void> => {
    if (!statusToDelete) return;

    try {
      await deleteStatus(statusToDelete.status_id);
      setStatuses(statuses.filter(s => s.status_id !== statusToDelete.status_id));
      toast.success(t('interactions.statuses.messages.success.deleted'));
    } catch (error) {
      handleError(error, 'Failed to delete status');
    } finally {
      setShowDeleteDialog(false);
      setStatusToDelete(null);
    }
  };

  const handleImportStatuses = async () => {
    const available = await getAvailableReferenceData('statuses', { item_type: STATUS_TYPE });
    setAvailableReferenceStatuses(available);
    setSelectedImportStatuses([]);
    setShowStatusImportDialog(true);
  };

  const handleImportSelected = async () => {
    try {
      // Check for conflicts first
      const conflicts = await checkImportConflicts(
        'statuses',
        selectedImportStatuses,
        { item_type: STATUS_TYPE }
      );

      if (conflicts.length > 0) {
        // Show conflict resolution dialog
        setImportConflicts(conflicts);
        setConflictResolutions({});
        setShowConflictDialog(true);
        setShowStatusImportDialog(false);
      } else {
        // No conflicts, proceed with import
        const result = await importReferenceData(
          'statuses',
          selectedImportStatuses,
          { item_type: STATUS_TYPE }
        );

        if (result.imported.length > 0) {
          toast.success(t('interactions.statuses.messages.success.imported', { count: result.imported.length }));
          await fetchStatuses();
        }

        if (result.skipped.length > 0) {
          toast.error(t('interactions.statuses.messages.error.skipped', {
            count: result.skipped.length,
            reason: (result.skipped as any[])[0].reason
          }));
        }

        setShowStatusImportDialog(false);
        setSelectedImportStatuses([]);
      }
    } catch (error) {
      handleError(error, t('interactions.statuses.messages.error.importFailed'));
    }
  };

  const handleResolveConflicts = async () => {
    try {
      const result = await importReferenceData(
        'statuses',
        selectedImportStatuses,
        { item_type: STATUS_TYPE },
        conflictResolutions
      );

      if (result.imported.length > 0) {
        toast.success(t('interactions.statuses.messages.success.imported', { count: result.imported.length }));
        await fetchStatuses();
        setSelectedImportStatuses([]);
      }

      if (result.skipped.length > 0) {
        const skippedNames = (result.skipped as any[]).map((s: any) => s.name).join(', ');
        toast(`Skipped: ${skippedNames}`, {
          icon: 'ℹ️',
          duration: 4000,
        });
      }

      setShowConflictDialog(false);
      setImportConflicts([]);
      setConflictResolutions({});
    } catch (error) {
      handleError(error, t('interactions.statuses.messages.error.importFailed'));
    }
  };

  const statusColumns: ColumnDefinition<IStatus>[] = [
    {
      title: t('interactions.statuses.table.name'),
      dataIndex: 'name',
      width: '30%',
    },
    {
      title: t('interactions.statuses.table.status'),
      dataIndex: 'is_closed',
      width: '40%',
      render: (value, record) => (
        <div className="flex items-center space-x-2 text-gray-500">
          <span className="text-sm mr-2">
            {record.is_closed ? t('ticketing.statuses.statusLabels.closed') : t('ticketing.statuses.statusLabels.open')}
          </span>
          <Switch
            checked={record.is_closed}
            onCheckedChange={() => updateStatusItem({ ...record, is_closed: !record.is_closed })}
            className="data-[state=checked]:bg-primary-500"
          />
          <span className="text-xs text-gray-400 ml-2">
            {record.is_closed
              ? t('interactions.statuses.statusLabels.closedHelp')
              : t('interactions.statuses.statusLabels.openHelp')
            }
          </span>
        </div>
      ),
    },
    {
      title: t('interactions.statuses.table.order'),
      dataIndex: 'order_number',
      width: '10%',
      render: (value) => value || 0,
    },
    {
      title: t('interactions.statuses.table.actions'),
      dataIndex: 'action',
      width: '10%',
      render: (_, item) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              className="h-8 w-8 p-0"
              id={`interaction-status-actions-menu-${item.status_id}`}
              onClick={(e) => e.stopPropagation()}
            >
              <span className="sr-only">{t('interactions.openMenu')}</span>
              <MoreVertical className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              id={`edit-interaction-status-${item.status_id}`}
              onClick={(e) => {
                e.stopPropagation();
                setEditingStatus(item);
                setShowStatusDialog(true);
              }}
            >
              {t('interactions.statuses.actions.edit')}
            </DropdownMenuItem>
            <DropdownMenuItem
              id={`delete-interaction-status-${item.status_id}`}
              className="text-destructive focus:text-destructive"
              onClick={(e) => {
                e.stopPropagation();
                handleDeleteStatusRequest(item.status_id);
              }}
            >
              {t('interactions.statuses.actions.delete')}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    }
  ];

  return (
    <div className="bg-white p-6 rounded-lg shadow-sm">
      <Alert variant="info" className="mb-4">
        <AlertDescription>
          {t('interactions.statuses.alert')}
        </AlertDescription>
      </Alert>

      <h3 className="text-lg font-semibold mb-4 text-gray-800">{t('interactions.statuses.title')}</h3>

      <DataTable
        id="interaction-statuses-table"
        data={statuses.filter(s => s.status_type === STATUS_TYPE).sort((a, b) => (a.order_number || 0) - (b.order_number || 0))}
        columns={statusColumns}
        pagination={true}
        currentPage={currentPage}
        onPageChange={setCurrentPage}
        pageSize={pageSize}
        onItemsPerPageChange={handlePageSizeChange}
      />

      <div className="mt-4 flex gap-2">
        <Button
          id='add-interaction-status-button'
          onClick={() => {
            setEditingStatus(null);
            setShowStatusDialog(true);
          }}
          className="bg-primary-500 text-white hover:bg-primary-600"
        >
          <Plus className="h-4 w-4 mr-2" /> {t('interactions.statuses.actions.addStatus')}
        </Button>
        <Button
          id='import-interaction-statuses-button'
          onClick={handleImportStatuses}
          variant="outline"
        >
          {t('interactions.statuses.actions.importStandard')}
        </Button>
      </div>

      {/* Status Dialog */}
      <StatusDialog
        open={showStatusDialog}
        onOpenChange={setShowStatusDialog}
        editingStatus={editingStatus}
        selectedStatusType={STATUS_TYPE}
        userId={userId}
        existingStatuses={statuses}
        onSuccess={async () => {
          await fetchStatuses();
        }}
      />

      {/* Import Dialog */}
      <StatusImportDialog
        open={showStatusImportDialog}
        onOpenChange={setShowStatusImportDialog}
        availableStatuses={availableReferenceStatuses}
        selectedStatuses={selectedImportStatuses}
        onSelectionChange={(statusId) => {
          setSelectedImportStatuses(prev =>
            prev.includes(statusId)
              ? prev.filter(id => id !== statusId)
              : [...prev, statusId]
          );
        }}
        onImport={handleImportSelected}
      />

      {/* Conflict Resolution Dialog */}
      <ConflictResolutionDialog
        open={showConflictDialog}
        onOpenChange={setShowConflictDialog}
        conflicts={importConflicts}
        resolutions={conflictResolutions}
        onResolutionChange={(itemId, resolution) => {
          setConflictResolutions(prev => ({
            ...prev,
            [itemId]: resolution
          }));
        }}
        onResolve={handleResolveConflicts}
        onCancel={() => {
          setShowConflictDialog(false);
          setImportConflicts([]);
          setConflictResolutions({});
        }}
      />

      {/* Delete Confirmation Dialog */}
      <DeleteConfirmationDialog
        isOpen={showDeleteDialog}
        onClose={() => {
          setShowDeleteDialog(false);
          setStatusToDelete(null);
        }}
        itemName={statusToDelete?.name || ''}
        itemType="Status"
        onConfirm={confirmDeleteStatus}
      />
    </div>
  );
};

export default InteractionStatusSettings;
