'use client';

import React, { useState } from 'react';
import { api } from '@/lib/api';
import Swal from 'sweetalert2';
import BackendSearchableSelect from './BackendSearchableSelect';

interface AssignNewCylinderModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedCylinderIds: string[];
  onSuccess: () => void;
}

const AssignNewCylinderModal: React.FC<AssignNewCylinderModalProps> = ({
  isOpen,
  onClose,
  selectedCylinderIds,
  onSuccess,
}) => {
  const [selectedWarehouse, setSelectedWarehouse] = useState('');
  const [loading, setLoading] = useState(false);

  // Assign only the NEW cylinders among the selection to the chosen warehouse.
  const handleSubmit = async () => {
    if (!selectedWarehouse) {
      Swal.fire('Error', 'Please select a location', 'error');
      return;
    }

    setLoading(true);
    try {
      const response: any = await api.post('/cylinders/assign-new-to-warehouse', {
        warehouseId: selectedWarehouse,
        cylinderIds: selectedCylinderIds,
      });

      Swal.fire(
        'Success',
        response?.message || 'Cylinders assigned to location successfully',
        'success',
      );
      setSelectedWarehouse('');
      onSuccess();
      onClose();
    } catch (error: any) {
      Swal.fire('Error', error.message || 'Failed to assign cylinders', 'error');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex justify-center items-center"
      style={{ backgroundColor: 'rgba(146, 140, 140, 0.3)' }}
    >
      <div className="bg-white p-8 rounded-2xl shadow-xl max-w-md w-full">
        <h2 className="text-2xl font-bold text-gray-800 mb-2">
          Assign Cylinders to Location
        </h2>
        <p className="text-sm text-gray-500 mb-6">
          Only cylinders with status <span className="font-semibold">NEW</span> will be
          assigned. Others in your selection are left unchanged.
        </p>

        <div className="mb-6">
          <BackendSearchableSelect
            id="warehouse"
            name="warehouse"
            value={selectedWarehouse}
            onChange={(e) => setSelectedWarehouse(e.target.value)}
            label="Select a location"
            apiEndpoint="/warehouse/all"
            labelKey="name"
            valueKey="id"
            defaultOption={{ value: '', label: 'Select a location' }}
          />
        </div>

        <div className="flex justify-end space-x-4">
          <button
            onClick={onClose}
            className="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2.5 px-6 rounded-lg"
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={loading}
            className="bg-[#dd3a3f] hover:bg-[#ad272b] text-white font-bold py-2.5 px-6 rounded-lg disabled:opacity-50 transition-all duration-200 active:scale-95"
          >
            {loading ? 'Submitting...' : 'Submit'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AssignNewCylinderModal;
