import React, { useState, useEffect } from "react";
import { apiFetch } from "@/utils/api";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
} from "recharts";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardTable,
  DashboardChartTooltip,
  TableSkeleton,
  ChartSkeleton,
  TOOLTIP_STYLES,
  PILL_TRIGGER_CLASS,
} from "@/components/dashboard/shared";

export const UserBehaviorDashboard = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState("30");

  const processPageData = (data) => {
    if (!data?.rows) {
      return [];
    }

    return data.rows.map((row) => ({
      path: row.dimensionValues[0].value || "Unknown",
      pageViews: parseInt(row.metricValues[0].value || 0),
      avgSessionDuration: parseFloat(row.metricValues[1].value || 0),
      bounceRate: parseFloat(row.metricValues[2].value || 0) * 100,
      engagedSessions: parseInt(row.metricValues[3].value || 0),
    }));
  };

  const processDeviceData = (data) => {
    if (!data?.rows) {
      return [];
    }

    return data.rows
      .filter((row) => {
        const device = (row.dimensionValues[0].value || "").toLowerCase();
        return ["desktop", "mobile", "tablet"].includes(device);
      })
      .map((row) => {
        const device = row.dimensionValues[0].value || "Unknown";
        return {
          device: device.charAt(0).toUpperCase() + device.slice(1).toLowerCase(),
          pageViews: parseInt(row.metricValues[0].value || 0),
          sessions: parseInt(row.metricValues[1].value || 0),
        };
      })
      .sort((a, b) => b.pageViews - a.pageViews);
  };

  const processSourceData = (data) => {
    if (!data?.rows) {
      return [];
    }

    return data.rows.map((row) => ({
      source: row.dimensionValues[0].value || "Unknown",
      sessions: parseInt(row.metricValues[0].value || 0),
      conversions: parseInt(row.metricValues[1].value || 0),
    }));
  };

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const response = await apiFetch(
          `/api/dashboard-analytics/user-behavior?timeRange=${timeRange}`,
          {
            credentials: "include",
          }
        );

        if (!response.ok) {
          throw new Error("Failed to fetch user behavior");
        }

        const result = await response.json();

        if (!result?.success) {
          throw new Error("Invalid response structure");
        }

        const rawData = result.data?.data || result.data;
        const pageResponse = rawData?.pageResponse || rawData?.reports?.[0];
        const deviceResponse = rawData?.deviceResponse || rawData?.reports?.[1];
        const sourceResponse = rawData?.sourceResponse || rawData?.reports?.[2];

        const processed = {
          success: true,
          data: {
            pageData: {
              pageData: processPageData(pageResponse),
              deviceData: processDeviceData(deviceResponse),
            },
            sourceData: processSourceData(sourceResponse),
          },
        };

        setData(processed);
      } catch (error) {
        console.error("Failed to fetch behavior data:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [timeRange]);

  const formatDuration = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes}m ${remainingSeconds}s`;
  };

  // Column definitions for pages table
  const pagesColumns = [
    {
      key: "path",
      header: "Page Path",
      render: (value) =>
        typeof value === "string" && value.startsWith("/") ? (
          <a
            href={`https://www.acherryontop.com${value}`}
            target="_blank"
            rel="noopener noreferrer"
            className="font-medium text-foreground hover:underline"
          >
            {value}
          </a>
        ) : (
          <span className="font-medium text-foreground">{value}</span>
        ),
    },
    {
      key: "pageViews",
      header: "Views",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{value.toLocaleString()}</span>,
    },
    {
      key: "bounceRate",
      header: "Bounce Rate",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{value.toFixed(1)}%</span>,
    },
    {
      key: "avgSessionDuration",
      header: "Avg. Duration",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{formatDuration(value)}</span>,
    },
  ];

  // Column definitions for sources table
  const sourcesColumns = [
    {
      key: "source",
      header: "Source",
      width: "w-[40%]",
      render: (value) => <span className="font-medium text-foreground break-all">{value}</span>,
    },
    {
      key: "sessions",
      header: "Sessions",
      align: "right",
      width: "w-[19%] whitespace-nowrap",
      render: (value) => <span className="text-muted-foreground whitespace-nowrap">{value.toLocaleString()}</span>,
    },
    {
      key: "conversions",
      header: "Conv.",
      align: "right",
      width: "w-[17%] whitespace-nowrap",
      render: (value) => <span className="text-muted-foreground whitespace-nowrap">{value.toLocaleString()}</span>,
    },
    {
      key: "conversionRate",
      header: "Conv. Rate",
      align: "right",
      width: "w-[24%] whitespace-nowrap",
      render: (_, row) => (
        <span className="text-muted-foreground whitespace-nowrap">
          {((row.conversions / row.sessions) * 100).toFixed(1)}%
        </span>
      ),
    },
  ];

  if (loading) {
    return (
      <Card className={`${CARD_STYLES.base} flex h-full flex-col`}>
        <DashboardSectionHeader
          title="User Behavior Analysis"
          loading={true}
          size="large"
          timeSelector={<div className="w-36" />}
        />
        <CardContent className="p-4 pt-3">
          <Tabs defaultValue="pages" className="w-full">
            <TabsList className="mb-3 h-8 w-fit self-start">
              <TabsTrigger value="pages" disabled>Top Pages</TabsTrigger>
              <TabsTrigger value="sources" disabled>Traffic Sources</TabsTrigger>
              <TabsTrigger value="devices" disabled>Device Usage</TabsTrigger>
            </TabsList>

            <TabsContent value="pages" className="mt-3 space-y-2">
              <TableSkeleton rows={15} columns={4} />
            </TabsContent>

            <TabsContent value="sources" className="mt-3 space-y-2">
              <TableSkeleton rows={12} columns={4} />
            </TabsContent>

            <TabsContent value="devices" className="mt-3 space-y-2">
              <ChartSkeleton type="pie" height="sm" withCard={false} />
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    );
  }

  const COLORS = {
    desktop: "#6b5fc7", // Purple
    mobile: "#0f8f77", // Green
    tablet: "#a87a24", // Yellow
  };

  const deviceData = data?.data?.pageData?.deviceData || [];
  const totalViews = deviceData.reduce((sum, item) => sum + item.pageViews, 0);
  const totalSessions = deviceData.reduce(
    (sum, item) => sum + item.sessions,
    0
  );

  // Custom item renderer for the device tooltip - renders both Views and Sessions rows
  const deviceTooltipRenderer = (item, index) => {
    if (index > 0) return null; // Only render for the first item (pie chart sends single slice)

    const deviceData = item.payload;
    const color = COLORS[deviceData.device.toLowerCase()];
    const viewsPercentage = ((deviceData.pageViews / totalViews) * 100).toFixed(1);
    const sessionsPercentage = ((deviceData.sessions / totalSessions) * 100).toFixed(1);

    return (
      <>
        <div className={TOOLTIP_STYLES.row}>
          <div className={TOOLTIP_STYLES.rowLabel}>
            <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: color }} />
            <span className={TOOLTIP_STYLES.name}>Views</span>
          </div>
          <span className={TOOLTIP_STYLES.value}>{deviceData.pageViews.toLocaleString()} ({viewsPercentage}%)</span>
        </div>
        <div className={TOOLTIP_STYLES.row}>
          <div className={TOOLTIP_STYLES.rowLabel}>
            <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: color }} />
            <span className={TOOLTIP_STYLES.name}>Sessions</span>
          </div>
          <span className={TOOLTIP_STYLES.value}>{deviceData.sessions.toLocaleString()} ({sessionsPercentage}%)</span>
        </div>
      </>
    );
  };

  return (
    <Card className={`${CARD_STYLES.base} flex h-full flex-col`}>
      <DashboardSectionHeader
        title="User Behavior Analysis"
        size="large"
        timeSelector={
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className={PILL_TRIGGER_CLASS}>
              <SelectValue>
                {timeRange === "7" && "Last 7 days"}
                {timeRange === "14" && "Last 14 days"}
                {timeRange === "30" && "Last 30 days"}
                {timeRange === "90" && "Last 90 days"}
              </SelectValue>
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7">Last 7 days</SelectItem>
              <SelectItem value="14">Last 14 days</SelectItem>
              <SelectItem value="30">Last 30 days</SelectItem>
              <SelectItem value="90">Last 90 days</SelectItem>
            </SelectContent>
          </Select>
        }
      />
      <CardContent className="flex min-h-0 flex-1 flex-col p-4 pt-3">
        {/* Fixed-height tab body so the card doesn't grow/shrink per tab; the
            tables scroll internally instead. On xl the card fills the Analytics
            panel beside it (absolute-fill in Dashboard.tsx). */}
        <Tabs defaultValue="pages" className="flex min-h-0 w-full flex-1 flex-col">
          <TabsList className="mb-3 h-8 w-fit shrink-0 self-start">
            <TabsTrigger value="pages">Top Pages</TabsTrigger>
            <TabsTrigger value="sources">Traffic Sources</TabsTrigger>
            <TabsTrigger value="devices">Device Usage</TabsTrigger>
          </TabsList>

          <TabsContent value="pages" className="mt-0 min-h-0 flex-1 overflow-y-auto dashboard-scroll max-h-[420px] xl:max-h-none">
            <DashboardTable
              columns={pagesColumns}
              data={data?.data?.pageData?.pageData || []}
              getRowKey={(page, index) => `${page.path}-${index}`}
              compact
            />
          </TabsContent>

          <TabsContent value="sources" className="mt-0 min-h-0 flex-1 overflow-y-auto dashboard-scroll max-h-[420px] xl:max-h-none">
            <DashboardTable
              columns={sourcesColumns}
              data={data?.data?.sourceData || []}
              getRowKey={(source, index) => `${source.source}-${index}`}
              compact
            />
          </TabsContent>

          {/* NOTE: TabsContent must not carry a bare display class (e.g. `flex`)
              — it would override Radix's [hidden] attribute and render the
              inactive panel into the layout. Center via the inner wrapper. */}
          <TabsContent value="devices" className="mt-0 min-h-0 flex-1">
            {/* Studio donut: slice gaps + center total + labeled rows (no on-slice labels) */}
            <div className="flex h-full min-h-[280px] w-full flex-col items-center justify-center gap-4 py-2 sm:flex-row sm:gap-10">
              <div className="relative h-48 w-48 shrink-0">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={deviceData}
                      dataKey="pageViews"
                      nameKey="device"
                      cx="50%"
                      cy="50%"
                      innerRadius={58}
                      outerRadius={88}
                      paddingAngle={2}
                      stroke="#ffffff"
                      strokeWidth={2}
                      labelLine={false}
                    >
                      {deviceData.map((entry, index) => (
                        <Cell
                          key={`cell-${index}`}
                          fill={COLORS[entry.device.toLowerCase()]}
                        />
                      ))}
                    </Pie>
                    <Tooltip
                      content={
                        <DashboardChartTooltip
                          labelFormatter={(_, payload) => payload?.[0]?.payload?.device || ""}
                          itemRenderer={deviceTooltipRenderer}
                        />
                      }
                    />
                  </PieChart>
                </ResponsiveContainer>
                <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
                  <span className="text-[20px] font-bold tabular-nums text-[#2b2925]">
                    {totalViews >= 1000
                      ? `${(totalViews / 1000).toFixed(1)}K`
                      : totalViews.toLocaleString()}
                  </span>
                  <span className="text-[10.5px] font-semibold text-[#a09b92]">views</span>
                </div>
              </div>
              <div className="w-full max-w-[280px] space-y-2.5">
                {deviceData.map((entry) => {
                  const pct =
                    totalViews > 0
                      ? ((entry.pageViews / totalViews) * 100).toFixed(1)
                      : "0.0";
                  return (
                    <div key={entry.device} className="flex items-center gap-2.5">
                      <span
                        className="h-2 w-2 shrink-0 rounded-full"
                        style={{ background: COLORS[entry.device.toLowerCase()] }}
                      />
                      <span className="flex-1 text-xs font-medium text-[#2b2925]">
                        {entry.device}
                      </span>
                      <span className="text-xs tabular-nums text-[#7c7870]">
                        {entry.pageViews.toLocaleString()}
                      </span>
                      <span className="w-12 text-right text-xs font-bold tabular-nums text-[#2b2925]">
                        {pct}%
                      </span>
                    </div>
                  );
                })}
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  );
};

export default UserBehaviorDashboard;
