'use client';

import ProtectedRoute from '@/lib/ProtectedRoute';
import { useAuth } from '@/lib/auth';
import CylinderTable from './CylinderTable';
import Link from 'next/link';
import { Warehouse, Cylinder as CylinderIcon, ArrowUpRightFromSquare, ArrowUpLeftFromSquare } from 'lucide-react';
import { useState } from 'react';
import MoveToWarehouseModal from '@/components/MoveToWarehouseModal';
import AssignToClientModal from '@/components/AssignToClientModal';
import AssignToWarehouseModal from '@/components/AssignToWarehouseModal';
import AssignNewCylinderModal from '@/components/AssignNewCylinderModal';
import AddMaintenanceForm from '@/components/AddMaintenanceForm';
import AssignClientModal from '@/components/AssignClientModal';
import { Cylinder } from '@/types/common';
import Swal from 'sweetalert2';
import { api } from '@/lib/api';

interface CylinderInventoryProps {
    title: string;
}

const CylinderInventory = ({ title }: CylinderInventoryProps) => {
    const { user, isAdmin } = useAuth();
    const [selectedCylinderIds, setSelectedCylinderIds] = useState<string[]>([]);
    const [selectedCylinders, setSelectedCylinders] = useState<Cylinder[]>([]);
    const [refreshTrigger, setRefreshTrigger] = useState(0);
    const [isMoveModalOpen, setIsMoveModalOpen] = useState(false);
    const [isAssignModalOpen, setIsAssignModalOpen] = useState(false);
    const [isAssignWarehouseModalOpen, setIsAssignWarehouseModalOpen] = useState(false);
    const [isMaintenanceModalOpen, setIsMaintenanceModalOpen] = useState(false);
    const [isAssignClientModalOpen, setIsAssignClientModalOpen] = useState(false);
    const [isAssignNewModalOpen, setIsAssignNewModalOpen] = useState(false);
    const [isDirectAssignmentLoading, setIsDirectAssignmentLoading] = useState(false);

    // Admin can assign NEW cylinders to a warehouse. Show the button whenever
    // at least one selected cylinder is still NEW.
    const showAssignNewButton = isAdmin && selectedCylinders.some(cylinder => cylinder.status === 'NEW');

    const showAssignClientButton = selectedCylinders.some(cylinder =>
        cylinder.status === 'OUTSIDE' && (cylinder.is_client_owned == 0)
    );

    const allSelectedAreOutside = selectedCylinders.length > 0 && selectedCylinders.every(cylinder => cylinder.status === 'OUTSIDE');
    const allSelectedAreInside = selectedCylinders.length > 0 && selectedCylinders.every(cylinder => cylinder.status === 'INSIDE');
    const hasAssignedSelected = selectedCylinders.some(cylinder => cylinder.status === 'ASSIGNED');
    const isPlant = user?.role === 'PLANT';
    // NEW cylinders are view-only for a plant user; selecting any of them
    // disables the action buttons (Mark Inside still targets only ASSIGNED ones).
    const plantHasNewSelected = isPlant && selectedCylinders.some(cylinder => cylinder.status === 'NEW');
    const [isMarkInsideLoading, setIsMarkInsideLoading] = useState(false);

    const handleMarkInside = async () => {
        setIsMarkInsideLoading(true);
        try {
            const response: any = await api.patch('/cylinders/mark-inside', {
                cylinderIds: selectedCylinderIds,
            });
            Swal.fire('Success', response?.message || 'Cylinders marked inside successfully', 'success');
            handleSuccess();
        } catch (error: any) {
            Swal.fire('Error', error.message || 'Failed to mark cylinders inside', 'error');
        } finally {
            setIsMarkInsideLoading(false);
        }
    };

    const handleDirectAssignToWarehouse = async () => {
        if (!user?.warehouseId) return; // Should not happen if button is enabled correctly

        const confirm = await Swal.fire({
            title: 'Are you sure?',
            text: 'Do you want to make the selected cylinder(s) inside?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#dd3a3f',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, mark inside',
            cancelButtonText: 'No',
        });
        if (!confirm.isConfirmed) return;

        setIsDirectAssignmentLoading(true);
        try {
            await api.post('/cylinders/assign-to-warehouse', {
                warehouseId: user.warehouseId,
                cylinderIds: selectedCylinderIds,
                action: 'INSIDE',
            });
            Swal.fire('Success', 'Cylinders moved to your location successfully', 'success');
            handleSuccess();
        } catch (error: any) {
            Swal.fire('Error', error.message || 'Failed to move cylinders to location', 'error');
        } finally {
            setIsDirectAssignmentLoading(false);
        }
    };

    const handleSuccess = () => {
        setIsMoveModalOpen(false);
        setIsAssignModalOpen(false);
        setIsAssignWarehouseModalOpen(false);
        setIsAssignClientModalOpen(false);
        setIsAssignNewModalOpen(false);
        setSelectedCylinderIds([]);
        setSelectedCylinders([]);
        setRefreshTrigger(prev => prev + 1);
    }

    return (
        <ProtectedRoute>
            <div className="min-h-screen bg-gray-100 p-4 sm:p-6 lg:p-8">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 p-4 bg-white rounded-xl shadow-lg border-l-4 border-[#dd3a3f]">
                    <h1 className="text-3xl font-extrabold text-gray-800">
                        {title}
                    </h1>
                    <div className="flex flex-wrap gap-3 mt-4 sm:mt-0">
                        {showAssignNewButton && (
                            <button
                                className="flex items-center space-x-2 bg-red-600 hover:bg-red-700 text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
                                onClick={() => setIsAssignNewModalOpen(true)}
                                disabled={selectedCylinderIds.length === 0}
                            >
                                <Warehouse className="w-4 h-4" />
                                <span>Assign</span>
                            </button>
                        )}
                        {isPlant && hasAssignedSelected && (
                            <button
                                className="flex items-center space-x-2 bg-blue-600 hover:bg-blue-700 text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
                                onClick={handleMarkInside}
                                disabled={isMarkInsideLoading}
                            >
                                <ArrowUpLeftFromSquare className="w-4 h-4" />
                                <span>Mark Inside</span>
                            </button>
                        )}
                        {showAssignClientButton && (
                            <button
                                className="flex items-center space-x-2 bg-red-600 hover:bg-red-700 text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
                                onClick={() => setIsAssignClientModalOpen(true)}
                                disabled={selectedCylinderIds.length === 0 || plantHasNewSelected}
                            >
                                <ArrowUpRightFromSquare className="w-4 h-4" />
                                <span>Assign Client</span>
                            </button>
                        )}
                        {(
                            <button
                                className="flex items-center space-x-2 bg-red-600 hover:bg-red-700 text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
                                onClick={() => setIsMaintenanceModalOpen(true)}
                                disabled={selectedCylinderIds.length === 0 || allSelectedAreOutside || plantHasNewSelected}
                            >
                                <Warehouse className="w-4 h-4" />
                                <span>Maintanence</span>
                            </button>
                        )}
                        {(
                            <button
                                className="flex items-center space-x-2 bg-red-600 hover:bg-red-700 text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
                                onClick={user?.warehouseId ? handleDirectAssignToWarehouse : () => setIsAssignWarehouseModalOpen(true)}
                                disabled={selectedCylinderIds.length === 0 || allSelectedAreInside || isDirectAssignmentLoading || plantHasNewSelected}
                            >
                                <ArrowUpLeftFromSquare className="w-4 h-4" />
                                <span>In</span>
                            </button>
                        )}
                        {(
                            <button
                                className="flex items-center space-x-2 bg-red-600 hover:bg-red-700 text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
                                onClick={() => setIsAssignModalOpen(true)}
                                disabled={selectedCylinderIds.length === 0 || !allSelectedAreInside || plantHasNewSelected}
                            >
                                <ArrowUpRightFromSquare className="w-4 h-4" />
                                <span>Out</span>
                            </button>
                        )}
                        <Link href="/cylinder/add" passHref>
                            <button className="flex items-center space-x-2 bg-[#dd3a3f] hover:bg-[#ad272b] text-white font-bold py-2.5 px-6 rounded-lg shadow-md transition-all duration-200 transform hover:scale-[1.02]">
                                <CylinderIcon className="w-4 h-4" />
                                <span>Add New Cylinder</span>
                            </button>
                        </Link>
                    </div>
                </div>
                <CylinderTable
                    selectedIds={selectedCylinderIds}
                    onSelectionChange={setSelectedCylinderIds}
                    onSelectedCylindersChange={setSelectedCylinders}
                    refreshTrigger={refreshTrigger}
                />
                <MoveToWarehouseModal
                    isOpen={isMoveModalOpen}
                    onClose={() => setIsMoveModalOpen(false)}
                    selectedCylinderIds={selectedCylinderIds}
                    onSuccess={handleSuccess}
                />
                <AssignToClientModal
                    isOpen={isAssignModalOpen}
                    onClose={() => setIsAssignModalOpen(false)}
                    selectedCylinderIds={selectedCylinderIds}
                    selectedCylinders={selectedCylinders}
                    onSuccess={handleSuccess}
                />
                <AssignToWarehouseModal
                    isOpen={isAssignWarehouseModalOpen}
                    onClose={() => setIsAssignWarehouseModalOpen(false)}
                    selectedCylinderIds={selectedCylinderIds}
                    onSuccess={handleSuccess}
                />
                <AddMaintenanceForm
                    isOpen={isMaintenanceModalOpen}
                    onClose={() => {
                        setIsMaintenanceModalOpen(false);
                        setSelectedCylinderIds([]);
                    }}
                    cylinderIds={selectedCylinderIds}
                    onSuccess={handleSuccess}
                />
                <AssignClientModal
                    isOpen={isAssignClientModalOpen}
                    onClose={() => setIsAssignClientModalOpen(false)}
                    selectedCylinderIds={selectedCylinderIds}
                    onSuccess={handleSuccess}
                />
                <AssignNewCylinderModal
                    isOpen={isAssignNewModalOpen}
                    onClose={() => setIsAssignNewModalOpen(false)}
                    selectedCylinderIds={selectedCylinderIds}
                    onSuccess={handleSuccess}
                />
            </div>
        </ProtectedRoute>
    );
};

export default CylinderInventory;
