import React, { useState } from "react";
import { Button } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { ChevronDown } from "lucide-react";
import {
  PermittedDashboardItem,
  DashaboardParam,
} from "@/record-management/services/api/advancedDashboardService";
import { useAdvancedDashboardHook } from "@/shared/hooks/useAdvancedDashboardHook";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useLocalizedName } from "@/shared/common/localizedName";
import { getFormattedDashboardLabel } from "@/performance-management/utils/dashboardUtils";
import { PositionDto } from "@/record-management/dto/userRecords/usersDto";

const AdvancedDashboardPage = () => {
  const [selectedDashboard, setSelectedDashboard] =
    useState<PermittedDashboardItem | null>(null);
  const [selectedParameters, setSelectedParameters] = useState<
    Record<string, any>
  >({});
  const localizedName = useLocalizedName();

  const {
    permittedDashboards,
    dashboardUrl,
    isLoadingPermitted,
    isLoadingUrl,
  } = useAdvancedDashboardHook(selectedDashboard?.id);

  const { allScopedDepartments, allScopedEmployees } = useSettings();

  const positionOptions = Array.isArray(allScopedDepartments)
    ? allScopedDepartments.map((pos: PositionDto) => ({
        label: localizedName(pos.name) || "N/A",
        value: pos.id,
      }))
    : [];

  const employeeOptions = Array.isArray(allScopedEmployees)
    ? allScopedEmployees.map((emp: any) => ({
        label: localizedName(emp.name) || "N/A",
        value: emp.id,
      }))
    : [];

  const handleParameterSelect = (key: string, value: string) => {
    setSelectedParameters((prev) => ({
      ...prev,
      [key]: value,
    }));
  };

  return (
    <div className="space-y-6">
      {/* Dashboard + Position + Employee in a row */}
      <div className="flex flex-wrap gap-4 items-start">
        {/* Dashboard Dropdown */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="outline"
              className="flex items-center justify-between w-60"
              disabled={isLoadingPermitted}>
              {isLoadingPermitted
                ? "Loading dashboards..."
                : getFormattedDashboardLabel(selectedDashboard?.name, "am") ||
                  "Select Dashboard"}
              <ChevronDown className="ml-2 h-4 w-4 opacity-70" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-60">
            <DropdownMenuLabel>Available Dashboards</DropdownMenuLabel>
            {permittedDashboards?.items.map((dashboard) => (
              <DropdownMenuItem
                key={dashboard.id}
                onClick={() => {
                  setSelectedDashboard(dashboard);
                  setSelectedParameters({}); // reset parameters
                }}>
                {getFormattedDashboardLabel(dashboard.name, "am")}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* Position Dropdown */}
        {selectedDashboard?.params?.includes(DashaboardParam.POSITION) && (
          <select
            className="border rounded-md w-60 p-2"
            value={selectedParameters["position"] || ""}
            onChange={(e) => handleParameterSelect("position", e.target.value)}>
            <option value="">Select Position</option>
            {positionOptions.map((pos) => (
              <option key={pos.value} value={pos.value}>
                {pos.label}
              </option>
            ))}
          </select>
        )}

        {/* Employee Dropdown */}
        {selectedDashboard?.params?.includes(DashaboardParam.EMPLOYEE) && (
          <select
            className="border rounded-md w-60 p-2"
            value={selectedParameters["employee"] || ""}
            onChange={(e) => handleParameterSelect("employee", e.target.value)}>
            <option value="">Select Employee</option>
            {employeeOptions.map((emp) => (
              <option key={emp.value} value={emp.value}>
                {emp.label}
              </option>
            ))}
          </select>
        )}
      </div>

      {/* Dashboard iframe */}
      {isLoadingUrl ? (
        <p>Loading dashboard...</p>
      ) : dashboardUrl ? (
        <iframe
          src={dashboardUrl?.iframeUrl}
          width="100%"
          height="800"
          className="rounded-xl border"
          title="Advanced Dashboard"
        />
      ) : (
        <p className="text-gray-500">Select a dashboard to view</p>
      )}
    </div>
  );
};

export default AdvancedDashboardPage;
