import React, { useEffect, useState } from "react";
import { Dropdown } from "primereact/dropdown";
import axios from "axios";

export default function CustomerBranchDropdown({
    field,
    customerId,
    placeholder = "Select Branch",
    label = "Branch",
    className = "w-full",
    showLabel = true,
}) {
    const [branches, setBranches] = useState([]);

    useEffect(() => {
        if (!customerId) {
            setBranches([]);
            if (field && field.onChange) {
                field.onChange(null);
            }
            return;
        }

        axios
            .get(route("customer.branches.view", customerId))
            .then((response) => {
                setBranches(response.data.branches || []);
            })
            .catch(() => {
                setBranches([]);
            });
    }, [customerId]);

    return (
        <span className="p-float-label">
            <Dropdown
                id={field.name}
                {...field}
                options={branches}
                optionLabel="branch_name"
                optionValue="id"
                placeholder={placeholder}
                className={className}
                disabled={!customerId}
                showClear
            />
            {showLabel && <label htmlFor={field.name}>{label}</label>}
        </span>
    );
}


