@inject ClipboardCopyService ClipboardCopyService
@inject JsInteropService JsInteropService
@implements IDisposable

<label for="@Id" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">@Label</label>
<div class="relative">
    <input type="text" id="@Id" class="outline-0 shadow-sm bg-gray-50 border @(Copied ? "border-green-500 border-2" : "border-gray-300") text-gray-900 sm:text-sm rounded-lg block w-full p-2.5 pr-10 dark:bg-gray-700 dark:border-@(Copied ? "green-500" : "gray-600") dark:placeholder-gray-400 dark:text-white" value="@Value" @onclick="CopyToClipboard" readonly>
    @if (Copied)
    {
        <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-green-500 dark:text-green-400">
            Copied!
        </span>
    }
</div>

@code {
    /// <summary>
    /// Id for the input field. Defaults to a random GUID if not provided.
    /// </summary>
    [Parameter]
    public string Id { get; set; } = Guid.NewGuid().ToString();

    /// <summary>
    /// The label for the input.
    /// </summary>
    [Parameter]
    public string Label { get; set; } = "Value";

    /// <summary>
    /// The value to copy to the clipboard.
    /// </summary>
    [Parameter]
    public string Value { get; set; } = string.Empty;

    private bool Copied => ClipboardCopyService.GetCopiedId() == Id;

    /// <inheritdoc />
    protected override void OnInitialized()
    {
        ClipboardCopyService.OnCopy += HandleCopy;
    }

    private async Task CopyToClipboard()
    {
        await JsInteropService.CopyToClipboard(Value);
        ClipboardCopyService.SetCopied(Id);

        // After 2 seconds, reset the copied state if it's still the same element
        await Task.Delay(2000);
        if (ClipboardCopyService.GetCopiedId() == Id)
        {
            ClipboardCopyService.SetCopied(string.Empty);
        }
    }

    private void HandleCopy(string copiedElementId)
    {
        StateHasChanged();
    }

    /// <inheritdoc />
    public void Dispose()
    {
        ClipboardCopyService.OnCopy -= HandleCopy;
    }
}
