"use client";

import { useState } from "react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/app/shadcn_components/ui/dropdown-menu";
import { Button } from "@/app/shadcn_components/ui/button";
import { Checkbox } from "@/app/shadcn_components/ui/checkbox";

export interface ReportingFunctionalityButtonsProps {
  /** Currently applied value */
  hideNonCompliant: boolean;

  /** Currently applied value */
  useOriginalBaseline: boolean;

  /**
   * Explicit user action.
   * Parent decides what "apply" means (refetch, mutate, etc).
   */
  onApply: (options: {
    hideNonCompliant: boolean;
    useOriginalBaseline: boolean;
  }) => Promise<void> | void;

  disabled?: boolean;

  /* Whether filters are available (only for specific non-default scenarios) */
  canFilterNonCompliant?: boolean;
}

export function ReportingFunctionalityButtons({
  hideNonCompliant,
  useOriginalBaseline,
  onApply,
  disabled = false,
  canFilterNonCompliant = true,
}: ReportingFunctionalityButtonsProps) {
  const [draftHideNonCompliant, setDraftHideNonCompliant] =
    useState<boolean>(hideNonCompliant);
  const [draftUseOriginalBaseline, setDraftUseOriginalBaseline] =
    useState<boolean>(useOriginalBaseline);

  const [isApplying, setIsApplying] = useState(false);

  async function handleApply() {
    try {
      setIsApplying(true);
      await onApply({
        hideNonCompliant: draftHideNonCompliant,
        useOriginalBaseline: draftUseOriginalBaseline,
      });
    } finally {
      setIsApplying(false);
    }
  }

  async function handleReset() {
    try {
      // reset the filter and trigger the fetch
      setIsApplying(true);
      setDraftHideNonCompliant(false);
      setDraftUseOriginalBaseline(false);
      await onApply({ hideNonCompliant: false, useOriginalBaseline: false });
    } finally {
      setIsApplying(false);
    }
  }

  return (
    <DropdownMenu
      onOpenChange={(open) => {
        if (open) {
          setDraftHideNonCompliant(hideNonCompliant);
          setDraftUseOriginalBaseline(useOriginalBaseline);
        }
      }}
    >
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          disabled={disabled || isApplying}
          className={`
            relative flex items-center gap-2
            ${
              hideNonCompliant || useOriginalBaseline
                ? "border-brandmidblue/40 bg-brandlightblue/40"
                : ""
            }
          `}
        >
          {/* Filter icon */}
          <svg
            className={`h-4 w-4 ${
              hideNonCompliant || useOriginalBaseline ? "text-brandmidblue" : "text-gray-500"
            }`}
            viewBox="0 0 20 20"
            fill="currentColor"
          >
            <path d="M3 4a1 1 0 011-1h12a1 1 0 01.8 1.6l-4.8 6.4V16a1 1 0 01-1.447.894l-2-1A1 1 0 018 14v-2.999L3.2 5.6A1 1 0 013 4z" />
          </svg>
          Filter options
          {(hideNonCompliant || useOriginalBaseline) && (
            <span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-brandmidblue" />
          )}
        </Button>
      </DropdownMenuTrigger>

      <DropdownMenuContent
        align="end"
        className="w-80 p-4 shadow-tremor-dropdown"
      >
        <div className="space-y-5">
          {/* Filter option */}
          <div
            className={`flex items-start gap-4 ${
              !canFilterNonCompliant ? "opacity-50 pointer-events-none" : ""
            }`}
          >
            <Checkbox
              id="hide-non-compliant"
              checked={draftHideNonCompliant}
              disabled={!canFilterNonCompliant}
              onCheckedChange={(checked) =>
                setDraftHideNonCompliant(Boolean(checked))
              }
              className="mt-1"
            />

            <label
              htmlFor="hide-non-compliant"
              className="cursor-pointer space-y-1"
            >
              <div className="flex items-center gap-2 text-sm font-medium text-gray-900 leading-snug">
                <svg
                  className="h-4 w-4 text-gray-400"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fillRule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.707a1 1 0 00-1.414-1.414L9 10.172 7.707 8.879a1 1 0 00-1.414 1.414L9 13l4.707-4.707z"
                    clipRule="evenodd"
                  />
                </svg>
                Hide non-compliant properties
              </div>
              <div className="text-xs text-gray-500 leading-relaxed">
                Exclude properties that don’t meet the defined upgrade targets
              </div>
            </label>
          </div>

          {/* Use original SAP points */}
          <div
            className={`flex items-start gap-4 ${
              !canFilterNonCompliant ? "opacity-50 pointer-events-none" : ""
            }`}
          >
            <Checkbox
              id="use-original-baseline"
              checked={draftUseOriginalBaseline}
              disabled={!canFilterNonCompliant}
              onCheckedChange={(checked) =>
                setDraftUseOriginalBaseline(Boolean(checked))
              }
              className="mt-1"
            />

            <label
              htmlFor="use-original-baseline"
              className="cursor-pointer space-y-1"
            >
              <div className="flex items-center gap-2 text-sm font-medium text-gray-900 leading-snug">
                <svg
                  className="h-4 w-4 text-gray-400"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9z" />
                  <path
                    fillRule="evenodd"
                    d="M4 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v11a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 000 2h.01a1 1 0 100-2H7zm3 0a1 1 0 000 2h3a1 1 0 100-2h-3zm-3 4a1 1 0 100 2h.01a1 1 0 100-2H7zm3 0a1 1 0 100 2h3a1 1 0 100-2h-3z"
                    clipRule="evenodd"
                  />
                </svg>
                Use lodged SAP points
              </div>
              <div className="text-xs text-gray-500 leading-relaxed">
                Base metrics on properties below the EPC target using their lodged SAP rating, rather than the current modelled rating
              </div>
            </label>
          </div>

          {/* Actions */}
          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button
              variant="ghost"
              size="sm"
              disabled={isApplying || !canFilterNonCompliant}
              onClick={handleReset}
            >
              Reset
            </Button>

            <Button
              size="sm"
              className="bg-brandmidblue hover:bg-hoverblue"
              disabled={isApplying || !canFilterNonCompliant}
              onClick={handleApply}
            >
              {isApplying ? "Applying…" : "Apply filters"}
            </Button>
          </div>
        </div>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
