import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/dashboard/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/dashboard/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/dashboard/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/dashboard/ui/table";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  Legend,
} from "recharts";
import { Loader2 } from "lucide-react";
import { Skeleton } from "@/components/dashboard/ui/skeleton";

// Add skeleton components
const SkeletonTable = ({ rows = 12 }) => (
  <div className="h-full max-h-[540px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600 pr-2">
    <Table>
      <TableHeader>
        <TableRow className="dark:border-gray-800">
          <TableHead><Skeleton className="h-4 w-48 bg-muted rounded-sm" /></TableHead>
          <TableHead className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted rounded-sm" /></TableHead>
          <TableHead className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted rounded-sm" /></TableHead>
          <TableHead className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted rounded-sm" /></TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {[...Array(rows)].map((_, i) => (
          <TableRow key={i} className="dark:border-gray-800">
            <TableCell className="py-3"><Skeleton className="h-4 w-64 bg-muted rounded-sm" /></TableCell>
            <TableCell className="text-right py-3"><Skeleton className="h-4 w-12 ml-auto bg-muted rounded-sm" /></TableCell>
            <TableCell className="text-right py-3"><Skeleton className="h-4 w-12 ml-auto bg-muted rounded-sm" /></TableCell>
            <TableCell className="text-right py-3"><Skeleton className="h-4 w-16 ml-auto bg-muted rounded-sm" /></TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  </div>
);

const SkeletonPieChart = () => (
  <div className="h-60 relative">
    <div className="absolute inset-0 flex items-center justify-center">
      <div className="w-40 h-40 rounded-full bg-muted animate-pulse" />
    </div>
    <div className="absolute bottom-0 left-1/2 transform -translate-x-1/2 flex gap-4">
      {[...Array(3)].map((_, i) => (
        <div key={i} className="flex items-center gap-2">
          <Skeleton className="h-3 w-3 rounded-full bg-muted" />
          <Skeleton className="h-4 w-16 bg-muted rounded-sm" />
        </div>
      ))}
    </div>
  </div>
);

const SkeletonTabs = () => (
  <div className="space-y-2">
    <div className="flex gap-2 mb-4">
      {[...Array(3)].map((_, i) => (
        <Skeleton key={i} className="h-8 w-24 bg-muted rounded-sm" />
      ))}
    </div>
  </div>
);

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

  const processPageData = (data) => {
    if (!data?.rows) {
      console.log("No rows in page data");
      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) {
      console.log("No rows in device data");
      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) {
      console.log("No rows in source data");
      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 fetch(
          `/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();
        console.log("Raw user behavior response:", result);

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

        // Handle both data structures
        const rawData = result.data?.data || result.data;

        // Try to access the data differently based on the structure
        const pageResponse = rawData?.pageResponse || rawData?.reports?.[0];
        const deviceResponse = rawData?.deviceResponse || rawData?.reports?.[1];
        const sourceResponse = rawData?.sourceResponse || rawData?.reports?.[2];

        console.log("Extracted responses:", {
          pageResponse,
          deviceResponse,
          sourceResponse,
        });

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

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

  if (loading) {
    return (
      <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm h-full">
        <CardHeader className="p-6 pb-4">
          <div className="flex justify-between items-start">
            <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              User Behavior Analysis
            </CardTitle>
            <Skeleton className="h-9 w-36 bg-muted rounded-sm" />
          </div>
        </CardHeader>
        <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">
              <SkeletonTable rows={15} />
            </TabsContent>

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

            <TabsContent value="devices" className="mt-4 space-y-2">
              <SkeletonPieChart />
            </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
  );

  const CustomTooltip = ({ active, payload }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      const percentage = ((data.pageViews / totalViews) * 100).toFixed(1);
      const sessionPercentage = ((data.sessions / totalSessions) * 100).toFixed(1);
      return (
        <Card className="p-3 shadow-lg bg-white dark:bg-gray-900/60 backdrop-blur-sm border border-border">
          <CardContent className="p-0 space-y-2">
            <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
              {data.device}
            </p>
            <p className="text-sm text-muted-foreground">
              {data.pageViews.toLocaleString()} views ({percentage}%)
            </p>
            <p className="text-sm text-muted-foreground">
              {data.sessions.toLocaleString()} sessions ({sessionPercentage}%)
            </p>
          </CardContent>
        </Card>
      );
    }
    return null;
  };

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

  return (
    <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm h-full">
      <CardHeader className="p-6 pb-4">
        <div className="flex justify-between items-start">
          <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
            User Behavior Analysis
          </CardTitle>
          <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>
        </div>
      </CardHeader>
      <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 h-full max-h-[540px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600 pr-2"
          >
            <Table>
              <TableHeader>
                <TableRow className="dark:border-gray-800">
                  <TableHead className="text-foreground">Page Path</TableHead>
                  <TableHead className="text-right text-foreground">Views</TableHead>
                  <TableHead className="text-right text-foreground">Bounce Rate</TableHead>
                  <TableHead className="text-right text-foreground">Avg. Duration</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data?.data?.pageData?.pageData.map((page, index) => (
                  <TableRow key={index} className="dark:border-gray-800">
                    <TableCell className="font-medium text-foreground">
                      {page.path}
                    </TableCell>
                    <TableCell className="text-right text-muted-foreground">
                      {page.pageViews.toLocaleString()}
                    </TableCell>
                    <TableCell className="text-right text-muted-foreground">
                      {page.bounceRate.toFixed(1)}%
                    </TableCell>
                    <TableCell className="text-right text-muted-foreground">
                      {formatDuration(page.avgSessionDuration)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TabsContent>

          <TabsContent
            value="sources"
            className="mt-4 space-y-2 h-full max-h-[540px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600 pr-2"
          >
            <Table>
              <TableHeader>
                <TableRow className="dark:border-gray-800">
                  <TableHead className="text-foreground w-[35%] min-w-[120px]">Source</TableHead>
                  <TableHead className="text-right text-foreground w-[20%] min-w-[80px]">Sessions</TableHead>
                  <TableHead className="text-right text-foreground w-[20%] min-w-[80px]">Conv.</TableHead>
                  <TableHead className="text-right text-foreground w-[25%] min-w-[80px]">Conv. Rate</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data?.data?.sourceData?.map((source, index) => (
                  <TableRow key={index} className="dark:border-gray-800">
                    <TableCell className="font-medium text-foreground break-words max-w-[160px]">
                      {source.source}
                    </TableCell>
                    <TableCell className="text-right text-muted-foreground whitespace-nowrap">
                      {source.sessions.toLocaleString()}
                    </TableCell>
                    <TableCell className="text-right text-muted-foreground whitespace-nowrap">
                      {source.conversions.toLocaleString()}
                    </TableCell>
                    <TableCell className="text-right text-muted-foreground whitespace-nowrap">
                      {((source.conversions / source.sessions) * 100).toFixed(1)}%
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TabsContent>

          <TabsContent
            value="devices"
            className="mt-4 space-y-2 h-full max-h-[540px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600 pr-2"
          >
            <div className="h-60 bg-white dark:bg-gray-900/60 backdrop-blur-sm 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={<CustomTooltip />} />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  );
};

export default UserBehaviorDashboard; 