/**
 * Request Detail Modals Component
 * Consolidates all modals used in Request Detail
 */

import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { AlertCircle } from 'lucide-react';
import { ApprovalModal } from '@/components/approval/ApprovalModal/ApprovalModal';
import { RejectionModal } from '@/components/approval/RejectionModal/RejectionModal';
import { SkipApproverModal } from '@/components/approval/SkipApproverModal';
import { AddApproverModal } from '@/components/participant/AddApproverModal';
import { AddSpectatorModal } from '@/components/participant/AddSpectatorModal';
import { ActionStatusModal } from '@/components/common/ActionStatusModal';
import { FilePreview } from '@/components/common/FilePreview';
import { getDocumentPreviewUrl } from '@/services/workflowApi';

interface RequestDetailModalsProps {
  // Modal visibility states
  showApproveModal: boolean;
  showRejectModal: boolean;
  showAddApproverModal: boolean;
  showAddSpectatorModal: boolean;
  showSkipApproverModal: boolean;
  showActionStatusModal: boolean;
  previewDocument: any;
  documentError: { show: boolean; errors: any[] };

  // Modal data
  request: any;
  skipApproverData: any;
  actionStatus: any;
  existingParticipants: any[];
  currentLevels: any[];
  maxApprovalLevels?: number;
  onPolicyViolation?: (violations: Array<{ type: string; message: string; currentValue?: number; maxValue?: number }>) => void;

  // Handlers
  setShowApproveModal: (show: boolean) => void;
  setShowRejectModal: (show: boolean) => void;
  setShowAddApproverModal: (show: boolean) => void;
  setShowAddSpectatorModal: (show: boolean) => void;
  setShowSkipApproverModal: (show: boolean) => void;
  setShowActionStatusModal: (show: boolean) => void;
  setPreviewDocument: (doc: any) => void;
  setDocumentError: (error: any) => void;
  setSkipApproverData: (data: any) => void;
  setActionStatus: (status: any) => void;
  handleApproveConfirm: (description: string) => Promise<void>;
  handleRejectConfirm: (description: string) => Promise<void>;
  handleAddApprover: (email: string, tatHours: number, level: number) => Promise<void>;
  handleAddSpectator: (email: string) => void;
  handleSkipApprover: (reason: string) => void;
  downloadDocument: (documentId: string) => Promise<void>;
  documentPolicy: any;
}

export function RequestDetailModals({
  showApproveModal,
  showRejectModal,
  showAddApproverModal,
  showAddSpectatorModal,
  showSkipApproverModal,
  showActionStatusModal,
  previewDocument,
  documentError,
  request,
  skipApproverData,
  actionStatus,
  existingParticipants,
  currentLevels,
  maxApprovalLevels,
  onPolicyViolation,
  setShowApproveModal,
  setShowRejectModal,
  setShowAddApproverModal,
  setShowAddSpectatorModal,
  setShowSkipApproverModal,
  setShowActionStatusModal,
  setPreviewDocument,
  setDocumentError,
  setSkipApproverData,
  setActionStatus,
  handleApproveConfirm,
  handleRejectConfirm,
  handleAddApprover,
  handleAddSpectator,
  handleSkipApprover,
  downloadDocument,
  documentPolicy,
}: RequestDetailModalsProps) {
  return (
    <>
      {/* Approval Modal */}
      <ApprovalModal
        open={showApproveModal}
        onClose={() => setShowApproveModal(false)}
        onConfirm={handleApproveConfirm}
        requestIdDisplay={request.id}
        requestTitle={request.title}
      />

      {/* Rejection Modal */}
      <RejectionModal
        open={showRejectModal}
        onClose={() => setShowRejectModal(false)}
        onConfirm={handleRejectConfirm}
        requestIdDisplay={request.id}
        requestTitle={request.title}
      />

      {/* Add Approver Modal */}
      <AddApproverModal
        open={showAddApproverModal}
        onClose={() => setShowAddApproverModal(false)}
        onConfirm={handleAddApprover}
        requestIdDisplay={request.id}
        requestTitle={request.title}
        existingParticipants={existingParticipants}
        currentLevels={currentLevels}
        maxApprovalLevels={maxApprovalLevels}
        onPolicyViolation={onPolicyViolation}
      />

      {/* Add Spectator Modal */}
      <AddSpectatorModal
        open={showAddSpectatorModal}
        onClose={() => setShowAddSpectatorModal(false)}
        onConfirm={handleAddSpectator}
        requestIdDisplay={request.id}
        requestTitle={request.title}
        existingParticipants={existingParticipants}
      />

      {/* Skip Approver Modal */}
      <SkipApproverModal
        open={showSkipApproverModal}
        onClose={() => {
          setShowSkipApproverModal(false);
          setSkipApproverData(null);
        }}
        onConfirm={handleSkipApprover}
        approverName={skipApproverData?.approverName}
        levelNumber={skipApproverData?.levelNumber}
        requestIdDisplay={request.id}
        requestTitle={request.title}
      />

      {/* File Preview Modal */}
      {previewDocument && (
        <FilePreview
          fileName={previewDocument.fileName}
          fileType={previewDocument.fileType}
          fileUrl={getDocumentPreviewUrl(previewDocument.documentId)}
          fileSize={previewDocument.fileSize}
          attachmentId={previewDocument.documentId}
          onDownload={downloadDocument}
          open={!!previewDocument}
          onClose={() => setPreviewDocument(null)}
        />
      )}

      {/* Action Status Modal */}
      {actionStatus && (
        <ActionStatusModal
          open={showActionStatusModal}
          onClose={() => {
            setShowActionStatusModal(false);
            setActionStatus(null);
          }}
          success={actionStatus.success}
          title={actionStatus.title}
          message={actionStatus.message}
        />
      )}

      {/* Document Validation Error Modal */}
      <Dialog open={documentError.show} onOpenChange={(open) => setDocumentError((prev: any) => ({ ...prev, show: open }))}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertCircle className="w-5 h-5 text-red-600" />
              Document Upload Policy Violation
            </DialogTitle>
            <DialogDescription asChild>
              <div className="space-y-3">
                <p className="text-gray-700">The following file(s) could not be uploaded due to policy violations:</p>
                <div className="space-y-2 max-h-60 overflow-y-auto">
                  {documentError.errors.map((error, index) => (
                    <div key={index} className="bg-red-50 border border-red-200 rounded-lg p-3">
                      <p className="font-medium text-red-900 text-sm">{error.fileName}</p>
                      <p className="text-xs text-red-700 mt-1">{error.reason}</p>
                    </div>
                  ))}
                </div>
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                  <p className="text-sm text-blue-800 font-semibold mb-1">Document Policy:</p>
                  <ul className="text-xs text-blue-700 space-y-1 list-disc list-inside">
                    <li>Maximum file size: {documentPolicy.maxFileSizeMB}MB</li>
                    <li>Allowed file types: {documentPolicy.allowedFileTypes.join(', ')}</li>
                  </ul>
                </div>
              </div>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button onClick={() => setDocumentError({ show: false, errors: [] })} className="w-full sm:w-auto">
              OK
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

