import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useMetabaseDashboard } from "../hooks/useMetabaseDashboard";
import { usePlanYear } from "../hooks/usePlanYear";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Button } from "@/shared/common/ui/button";
import { Badge } from "@/shared/common/ui/badge";
import { Alert, AlertDescription } from "@/shared/common/ui/alert";
import { DashboardDropdown } from "@/shared/components/ui/DashboardDropdown";
import {
  RefreshCw,
  BarChart3,
  AlertCircle,
  ExternalLink,
  Loader2,
  Calendar,
} from "lucide-react";
import { useLocalizedName } from "@/shared/common/localizedName";
import { getFormattedDashboardLabel } from "../utils/dashboardUtils";

interface MetabaseDashboardProps {
  className?: string;
  planYearId?: string;
}

export const MetabaseDashboard: React.FC<MetabaseDashboardProps> = ({
  className = "",
  planYearId,
}) => {
  const { yearId } = useParams<{ yearId: string }>();
  const currentPlanYearId = planYearId || yearId;
  const localizedName = useLocalizedName();

  const {
    dashboards,
    selectedDashboard,
    iframeUrl,
    loading,
    error,
    fetchDashboards,
    selectDashboard,
    getFilteredDashboardUrl,
  } = useMetabaseDashboard();

  // Fetch plan year details if we have a plan year ID
  const { data: planYearData } = usePlanYear(currentPlanYearId || "");
  const planYear = planYearData?.data;

  const handleRefresh = () => {
    if (selectedDashboard && currentPlanYearId) {
      getFilteredDashboardUrl(selectedDashboard.id, currentPlanYearId);
    } else {
      fetchDashboards();
    }
  };

  // Auto-load filtered dashboard when plan year or selected dashboard changes
  useEffect(() => {
    if (selectedDashboard && currentPlanYearId) {
      getFilteredDashboardUrl(selectedDashboard.id, currentPlanYearId);
    }
  }, [selectedDashboard, currentPlanYearId, getFilteredDashboardUrl]);

  const openInNewTab = () => {
    if (iframeUrl) {
      window.open(iframeUrl, "_blank");
    }
  };

  if (error) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-red-600">
            <AlertCircle className="h-5 w-5" />
            Dashboard Error
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
          <Button onClick={handleRefresh} className="mt-4" variant="outline">
            <RefreshCw className="h-4 w-4 mr-2" />
            Retry
          </Button>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Dashboard Header */}
      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div className="flex items-center gap-3">
              <BarChart3 className="h-6 w-6 text-indigo-600" />
              <div>
                <p className="text-sm text-muted-foreground mt-1">
                  {planYear
                    ? `${planYear.year} - ${localizedName(
                        planYear.name
                      )} Performance Insights`
                    : "Real-time performance insights powered by Tria"}
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <DashboardDropdown
                dashboards={dashboards}
                selectedDashboard={selectedDashboard}
                onSelect={selectDashboard}
                isLoading={loading}
              />

              <Button
                variant="outline"
                size="icon"
                onClick={handleRefresh}
                disabled={loading}
              >
                <RefreshCw
                  className={`h-4 w-4 ${loading ? "animate-spin" : ""}`}
                />
              </Button>

              {iframeUrl && (
                <Button
                  variant="outline"
                  size="icon"
                  onClick={openInNewTab}
                  title="Open in new tab"
                >
                  <ExternalLink className="h-4 w-4" />
                </Button>
              )}
            </div>
          </div>

          <div className="flex items-center gap-2 mt-2 flex-wrap">
            {planYear && (
              <Badge variant="secondary" className="bg-green-50 text-primary-700">
                <Calendar className="h-3 w-3 mr-1" />
                {planYear.year} - {localizedName(planYear.name)}
              </Badge>
            )}
            {selectedDashboard && (
              <>
                <Badge
                  variant="secondary"
                  className="bg-indigo-50 text-indigo-700"
                >
                  {getFormattedDashboardLabel(selectedDashboard.name)}
                </Badge>
                
              </>
            )}
          </div>
        </CardHeader>
      </Card>

      {/* Dashboard Content */}
      <Card className="min-h-[600px]">
        <CardContent className="p-0">
          {loading && !iframeUrl ? (
            <div className="flex items-center justify-center h-96">
              <div className="text-center">
                <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4 text-indigo-600" />
                <p className="text-muted-foreground">Loading dashboard...</p>
              </div>
            </div>
          ) : iframeUrl ? (
            <div className="relative w-full h-[600px] rounded-lg overflow-hidden">
              <iframe
                src={iframeUrl}
                className="w-full h-full border-0"
                title={`${getFormattedDashboardLabel(selectedDashboard?.name) || "Performance"} Dashboard`}
                allow="fullscreen"
                loading="lazy"
              />
            </div>
          ) : (
            <div className="flex items-center justify-center h-96">
              <div className="text-center">
                <BarChart3 className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
                <p className="text-muted-foreground">
                  {dashboards.length === 0
                    ? "No dashboards available"
                    : "Select a dashboard to view analytics"}
                </p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
};
