/**
 * AdditionalApproverReviewModal Component
 * Modal for Additional Approvers to review request and approve/reject
 * Similar to InitiatorProposalApprovalModal but simpler - shows request details
 */

import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { 
  CheckCircle, 
  XCircle, 
  FileText,
  MessageSquare,
} from 'lucide-react';
import { toast } from 'sonner';
import { FormattedDescription } from '@/components/common/FormattedDescription';

interface AdditionalApproverReviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  onApprove: (comments: string) => Promise<void>;
  onReject: (comments: string) => Promise<void>;
  requestTitle?: string;
  requestDescription?: string;
  requestId?: string;
  levelName?: string;
  approverName?: string;
}

export function AdditionalApproverReviewModal({
  isOpen,
  onClose,
  onApprove,
  onReject,
  requestTitle = 'Request',
  requestDescription = '',
  requestId,
  levelName = 'Approval Level',
  approverName = 'Approver',
}: AdditionalApproverReviewModalProps) {
  const [comments, setComments] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [actionType, setActionType] = useState<'approve' | 'reject' | null>(null);

  const handleApprove = async () => {
    if (!comments.trim()) {
      toast.error('Please provide approval comments');
      return;
    }

    try {
      setSubmitting(true);
      setActionType('approve');
      await onApprove(comments);
      handleReset();
      onClose();
    } catch (error) {
      console.error('Failed to approve request:', error);
      toast.error('Failed to approve request. Please try again.');
    } finally {
      setSubmitting(false);
      setActionType(null);
    }
  };

  const handleReject = async () => {
    if (!comments.trim()) {
      toast.error('Please provide rejection reason');
      return;
    }

    try {
      setSubmitting(true);
      setActionType('reject');
      await onReject(comments);
      handleReset();
      onClose();
    } catch (error) {
      console.error('Failed to reject request:', error);
      toast.error('Failed to reject request. Please try again.');
    } finally {
      setSubmitting(false);
      setActionType(null);
    }
  };

  const handleReset = () => {
    setComments('');
    setActionType(null);
  };

  const handleClose = () => {
    if (!submitting) {
      handleReset();
      onClose();
    }
  };

  if (!isOpen) {
    return null;
  }

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl">
        <DialogHeader className="flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b">
          <DialogTitle className="flex items-center gap-2 text-lg lg:text-xl">
            <CheckCircle className="w-4 h-4 lg:w-5 lg:h-5 text-blue-600" />
            Review Request
          </DialogTitle>
          <DialogDescription className="text-xs lg:text-sm">
            {levelName}: Review request details and make a decision
          </DialogDescription>
          <div className="space-y-1 mt-2 text-xs text-gray-600">
            <div className="flex flex-wrap gap-x-4 gap-y-1">
              <div>
                <strong>Request ID:</strong> {requestId || 'N/A'}
              </div>
              <div>
                <strong>Approver:</strong> {approverName}
              </div>
            </div>
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6">
          <div className="space-y-4">
            {/* Request Title */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-sm lg:text-base flex items-center gap-2">
                  <FileText className="w-4 h-4 text-blue-600" />
                  Request Title
                </h3>
              </div>
              <div className="border rounded-lg p-2.5 lg:p-3 bg-gray-50">
                <p className="text-sm lg:text-base font-medium text-gray-900">{requestTitle}</p>
              </div>
            </div>

            {/* Request Description */}
            {requestDescription && (
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <h3 className="font-semibold text-sm lg:text-base flex items-center gap-2">
                    <MessageSquare className="w-4 h-4 text-blue-600" />
                    Request Description
                  </h3>
                </div>
                <div className="border rounded-lg p-2.5 lg:p-3 bg-gray-50 max-h-[200px] overflow-y-auto">
                  <FormattedDescription
                    content={requestDescription}
                    className="text-xs lg:text-sm text-gray-700"
                  />
                </div>
              </div>
            )}

            {/* Decision Section */}
            <div className="space-y-2 border-t pt-3 lg:pt-3">
              <h3 className="font-semibold text-sm lg:text-base">Your Decision & Comments</h3>
              <Textarea
                placeholder="Provide your evaluation comments, approval conditions, or rejection reasons..."
                value={comments}
                onChange={(e) => setComments(e.target.value)}
                className="min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"
              />
              <p className="text-xs text-gray-500">{comments.length} characters</p>
            </div>

            {/* Warning for missing comments */}
            {!comments.trim() && (
              <div className="bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2">
                <XCircle className="w-3.5 h-3.5 text-amber-600 flex-shrink-0 mt-0.5" />
                <p className="text-xs text-amber-800">
                  Please provide comments before making a decision. Comments are required and will be visible to all participants.
                </p>
              </div>
            )}
          </div>
        </div>

        <DialogFooter className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50">
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={submitting}
            className="border-2"
          >
            Cancel
          </Button>
          <div className="flex gap-2">
            <Button
              onClick={handleReject}
              disabled={!comments.trim() || submitting}
              variant="destructive"
              className="bg-red-600 hover:bg-red-700"
            >
              {submitting && actionType === 'reject' ? (
                'Rejecting...'
              ) : (
                <>
                  <XCircle className="w-4 h-4 mr-2" />
                  Reject
                </>
              )}
            </Button>
            <Button
              onClick={handleApprove}
              disabled={!comments.trim() || submitting}
              className="bg-green-600 hover:bg-green-700 text-white"
            >
              {submitting && actionType === 'approve' ? (
                'Approving...'
              ) : (
                <>
                  <CheckCircle className="w-4 h-4 mr-2" />
                  Approve
                </>
              )}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

