import Col from "@admin/ui/Col";
import Row from "@admin/ui/Row";
import StyledTable from "@admin/ui/StyledTable";
import { toast, Toaster } from "react-hot-toast";
import { useState } from "react";
import EditPricingRule from "./EditPricingRule";

export default function PricingRule({ accommodations = [] }) {
    const columns = [
        { header: '', key: 'checkbox' },
        { header: 'Category', key: 'name' },
        { header: 'Base Price (BIF)', key: 'base_price_bif' },
        { header: 'Base Price (USD)', key: 'base_price_usd' },
        { header: 'Base Price (EUR)', key: 'base_price_eur' },
        { header: 'Additional Adult', key: 'additional_adult' },
        { header: 'Child Surcharge', key: 'child_surcharge' },
        { header: 'Status', key: 'has_pricing_rule' },
    ];

    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);

    const handleEdit = (row) => {
        fetch(`/admin/edit_pricing_rule/${row.id}`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then((pricingRuleData) => {
                setInitialData(pricingRuleData);
                setIsEditModalOpen(true);
            })
            .catch((error) => {
                console.error('Error fetching pricing rule details:', error);
                toast.error('Failed to load pricing rule details');
            });
    };

    const transformedAccommodations = accommodations.map(acc => ({
        ...acc,
        base_price_bif: acc.base_price_bif ? `${parseInt(acc.base_price_bif).toLocaleString()} BIF` : 'N/A',
        base_price_usd: acc.base_price_usd ? `$${parseFloat(acc.base_price_usd).toFixed(2)}` : 'N/A',
        base_price_eur: acc.base_price_eur ? `€${parseFloat(acc.base_price_eur).toFixed(2)}` : 'N/A',
        additional_adult: acc.additional_adult_bif > 0 || acc.additional_adult_usd > 0 || acc.additional_adult_eur > 0 
            ? `${parseInt(acc.additional_adult_bif || 0).toLocaleString()} BIF / $${parseFloat(acc.additional_adult_usd || 0).toFixed(0)} / €${parseFloat(acc.additional_adult_eur || 0).toFixed(0)}`
            : 'No charge',
        child_surcharge: acc.child_surcharge_bif > 0 || acc.child_surcharge_usd > 0 || acc.child_surcharge_eur > 0
            ? `${parseInt(acc.child_surcharge_bif || 0).toLocaleString()} BIF / $${parseFloat(acc.child_surcharge_usd || 0).toFixed(0)} / €${parseFloat(acc.child_surcharge_eur || 0).toFixed(0)}`
            : 'No charge',
        has_pricing_rule: acc.has_pricing_rule ? (
            <span className="badge badge-success">Configured</span>
        ) : (
            <span className="badge badge-warning">Default Only</span>
        ),
    }));

    return (
        <>
            <Toaster />
            <Row md="12">
                <Col lg="12">
                    <div className="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4">
                        <div className="mb-3 mb-md-0">
                            <h2 className="page-title mb-1">Pricing Rules</h2>
                            <p className="text-muted mb-0">Configure pricing rules for accommodation categories (base price, additional adults, children)</p>
                        </div>
                    </div>

                    <Row>
                        <Col lg="12">
                            <StyledTable
                                data={transformedAccommodations}
                                columns={columns}
                                itemsPerPage={15}
                                title="Accommodation Pricing Rules"
                                onEdit={handleEdit}
                                onDelete={null}
                                noDataText="No accommodations found"
                            />
                        </Col>
                    </Row>
                </Col>
            </Row>

            <EditPricingRule
                isOpen={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                initialData={initialData}
            />
        </>
    );
}



