'use client';

/**
 * Manager Approval Modal
 * Modal for manager/admin to approve RM sales or stock overrides
 */

import { useState } from 'react';
import { Modal, Button } from '@/components/ui';
import { AlertTriangle, CheckCircle, Package, AlertCircle } from 'lucide-react';
import toast from 'react-hot-toast';

export default function ManagerApprovalModal({
  isOpen,
  onClose,
  onApprove,
  items,
  approvalType = 'RM_SALE', // 'RM_SALE' or 'STOCK_OVERRIDE'
  stockOverrideReason = '',
  onReasonChange,
}) {
  const [isProcessing, setIsProcessing] = useState(false);
  const [reason, setReason] = useState(stockOverrideReason);

  const handleApprove = async () => {
    if (approvalType === 'STOCK_OVERRIDE' && !reason.trim()) {
      toast.error('Please provide a reason for stock override');
      return;
    }

    setIsProcessing(true);
    try {
      await onApprove(approvalType === 'STOCK_OVERRIDE' ? reason : undefined);
    } catch (error) {
      toast.error(error.message || 'Approval failed');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={
        approvalType === 'RM_SALE'
          ? 'Manager Approval Required - Raw Material Sale'
          : 'Stock Override - Manager Approval'
      }
      size="lg"
    >
      <div className="p-6 space-y-6">
        {/* Warning/Info Section */}
        <div
          className={`
            rounded-xl p-4 border-2
            ${
              approvalType === 'RM_SALE'
                ? 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800'
                : 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
            }
          `}
        >
          <div className="flex items-start gap-3">
            {approvalType === 'RM_SALE' ? (
              <AlertTriangle className="w-6 h-6 text-amber-600 dark:text-amber-400 mt-0.5" />
            ) : (
              <AlertCircle className="w-6 h-6 text-red-600 dark:text-red-400 mt-0.5" />
            )}
            <div className="flex-1">
              <p className="font-semibold text-gray-900 dark:text-white mb-1">
                {approvalType === 'RM_SALE'
                  ? 'Raw Material Products Require Approval'
                  : 'Stock Override Warning'}
              </p>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {approvalType === 'RM_SALE'
                  ? 'These products are raw materials and typically should not be sold on POS. Manager approval is required to proceed.'
                  : 'This will allow the sale to proceed even with insufficient or negative stock. This action will be logged.'}
              </p>
            </div>
          </div>
        </div>

        {/* Items List */}
        <div>
          <h3 className="font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2">
            <Package className="w-5 h-5" />
            Items Requiring Approval
          </h3>
          <div className="space-y-2">
            {items.map((item, index) => (
              <div
                key={index}
                className="bg-gray-50 dark:bg-gray-800 rounded-lg p-3 border border-gray-200 dark:border-gray-700"
              >
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <p className="font-medium text-gray-900 dark:text-white">
                      {item.product_name || item.name}
                    </p>
                    {item.product_id && (
                      <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        Product ID: {item.product_id}
                      </p>
                    )}
                  </div>
                  <div className="text-right">
                    <p className="font-semibold text-gray-900 dark:text-white">
                      Qty: {item.quantity || item.requested || 0}
                    </p>
                    {approvalType === 'STOCK_OVERRIDE' && item.available !== undefined && (
                      <p className="text-xs text-red-600 dark:text-red-400 mt-1">
                        Available: {item.available}
                      </p>
                    )}
                  </div>
                </div>
                {approvalType === 'STOCK_OVERRIDE' && item.shortfall > 0 && (
                  <div className="mt-2 text-xs text-amber-600 dark:text-amber-400">
                    Shortfall: {item.shortfall} units
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Stock Override Reason Input */}
        {approvalType === 'STOCK_OVERRIDE' && (
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Reason for Stock Override *
            </label>
            <textarea
              value={reason}
              onChange={(e) => {
                setReason(e.target.value);
                if (onReasonChange) {
                  onReasonChange(e.target.value);
                }
              }}
              placeholder="Enter reason for allowing sale with insufficient stock..."
              rows={3}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-red-500 resize-none"
            />
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
              This reason will be logged for audit purposes.
            </p>
          </div>
        )}

        {/* Action Buttons */}
        <div className="flex gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
          <Button
            variant="outline"
            onClick={onClose}
            className="flex-1"
            disabled={isProcessing}
          >
            Cancel
          </Button>
          <Button
            variant={approvalType === 'RM_SALE' ? 'primary' : 'danger'}
            onClick={handleApprove}
            className="flex-1 flex items-center justify-center gap-2"
            disabled={isProcessing || (approvalType === 'STOCK_OVERRIDE' && !reason.trim())}
            loading={isProcessing}
          >
            <CheckCircle className="w-5 h-5" />
            {approvalType === 'RM_SALE' ? 'Approve Sale' : 'Approve Override'}
          </Button>
        </div>
      </div>
    </Modal>
  );
}

