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,
} 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) => <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-[35%] min-w-[120px]",
      render: (value) => <span className="font-medium text-foreground break-words max-w-[160px]">{value}</span>,
    },
    {
      key: "sessions",
      header: "Sessions",
      align: "right",
      width: "w-[20%] min-w-[80px]",
      render: (value) => <span className="text-muted-foreground whitespace-nowrap">{value.toLocaleString()}</span>,
    },
    {
      key: "conversions",
      header: "Conv.",
      align: "right",
      width: "w-[20%] min-w-[80px]",
      render: (value) => <span className="text-muted-foreground whitespace-nowrap">{value.toLocaleString()}</span>,
    },
    {
      key: "conversionRate",
      header: "Conv. Rate",
      align: "right",
      width: "w-[25%] min-w-[80px]",
      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} h-full`}>
        <DashboardSectionHeader
          title="User Behavior Analysis"
          loading={true}
          size="large"
          timeSelector={<div className="w-36" />}
        />
        <CardContent className="p-6 pt-0">
          <Tabs defaultValue="pages" className="w-full">
            <TabsList className="mb-4">
              <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-4 space-y-2">
              <TableSkeleton rows={15} columns={4} />
            </TabsContent>

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

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

  const COLORS = {
    desktop: "#8b5cf6", // Purple
    mobile: "#10b981", // Green
    tablet: "#f59e0b", // 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} h-full`}>
      <DashboardSectionHeader
        title="User Behavior Analysis"
        size="large"
        timeSelector={
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className="w-36 h-9">
              <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="p-6 pt-0">
        <Tabs defaultValue="pages" className="w-full">
          <TabsList className="mb-4">
            <TabsTrigger value="pages">Top Pages</TabsTrigger>
            <TabsTrigger value="sources">Traffic Sources</TabsTrigger>
            <TabsTrigger value="devices">Device Usage</TabsTrigger>
          </TabsList>

          <TabsContent value="pages" className="mt-4 space-y-2">
            <DashboardTable
              columns={pagesColumns}
              data={data?.data?.pageData?.pageData || []}
              getRowKey={(page, index) => `${page.path}-${index}`}
              maxHeight="xl"
              compact
            />
          </TabsContent>

          <TabsContent value="sources" className="mt-4 space-y-2">
            <DashboardTable
              columns={sourcesColumns}
              data={data?.data?.sourceData || []}
              getRowKey={(source, index) => `${source.source}-${index}`}
              maxHeight="xl"
              compact
            />
          </TabsContent>

          <TabsContent value="devices" className="mt-4 space-y-2">
            <div className={`h-60 ${CARD_STYLES.base} rounded-lg p-4`}>
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={deviceData}
                    dataKey="pageViews"
                    nameKey="device"
                    cx="50%"
                    cy="50%"
                    outerRadius={80}
                    labelLine={false}
                    label={({ name, percent }) =>
                      `${name} ${(percent * 100).toFixed(1)}%`
                    }
                  >
                    {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>
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  );
};

export default UserBehaviorDashboard;
