"use client";

import { useState, useEffect } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import {
  TrendingUp,
  TrendingDown,
  Users,
  ShoppingCart,
  DollarSign,
  Package,
  ArrowUpRight,
  ArrowDownRight,
  Minus,
} from "lucide-react";
import {
  getGrowthAnalyticsWithStore,
  type GrowthAnalytics,
} from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  AreaChart,
  Area,
  BarChart,
  Bar,
} from "recharts";
import { ChartSkeleton } from "./SkeletonLoaders";

interface GrowthAnalyticsChartProps {
  hideNumbers?: boolean;
}

export default function GrowthAnalyticsChart({
  hideNumbers = false,
}: GrowthAnalyticsChartProps) {
  const [data, setData] = useState<GrowthAnalytics | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [period, setPeriod] = useState("30");
  const { toast } = useToast();

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const response = await getGrowthAnalyticsWithStore(period);
        setData(response);
      } catch (err) {
        console.error("Error fetching growth data:", err);
        setError("Failed to load growth data");
        toast({
          title: "Error",
          description: "Failed to load growth analytics data.",
          variant: "destructive",
        });
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [period, toast]);

  const maskValue = (value: string): string => {
    if (!hideNumbers) return value;
    if (value.includes("£")) return "£***";
    if (value.match(/^\d/) || value.match(/^-?\d/)) return "***";
    return value;
  };

  const formatGrowthRate = (rate: number): string => {
    const prefix = rate > 0 ? "+" : "";
    return `${prefix}${rate.toFixed(1)}%`;
  };

  const getGrowthIcon = (rate: number) => {
    if (rate > 0) return <ArrowUpRight className="h-4 w-4 text-green-500" />;
    if (rate < 0) return <ArrowDownRight className="h-4 w-4 text-red-500" />;
    return <Minus className="h-4 w-4 text-muted-foreground" />;
  };

  const getGrowthColor = (rate: number): string => {
    if (rate > 0) return "text-green-600";
    if (rate < 0) return "text-red-600";
    return "text-muted-foreground";
  };

  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      const item = payload[0].payload;
      return (
        <div className="bg-background p-3 border border-border rounded-lg shadow-lg">
          <p className="text-sm font-medium text-foreground mb-2">{item.date}</p>
          <div className="space-y-1">
            <p className="text-sm text-blue-600">
              Revenue:{" "}
              <span className="font-semibold">
                {hideNumbers ? "£***" : formatGBP(item.revenue)}
              </span>
            </p>
            <p className="text-sm text-green-600">
              Orders:{" "}
              <span className="font-semibold">
                {hideNumbers ? "***" : item.orders}
              </span>
            </p>
            <p className="text-sm text-purple-600">
              Customers:{" "}
              <span className="font-semibold">
                {hideNumbers ? "***" : item.uniqueCustomers}
              </span>
            </p>
            <p className="text-sm text-orange-600">
              Avg Order:{" "}
              <span className="font-semibold">
                {hideNumbers ? "£***" : formatGBP(item.avgOrderValue)}
              </span>
            </p>
          </div>
        </div>
      );
    }
    return null;
  };

  if (isLoading) {
    return (
      <ChartSkeleton
        title="Growth Analytics"
        description="Track your store's growth over time"
        icon={TrendingUp}
        showStats={true}
      />
    );
  }

  if (error || !data) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Growth Analytics
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <TrendingUp className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">
              {error || "No growth data available"}
            </p>
          </div>
        </CardContent>
      </Card>
    );
  }

  const { summary, customerInsights, timeSeries, topGrowingProducts } = data;

  return (
    <div className="space-y-6">
      {/* Period Selector */}
      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="h-5 w-5" />
                Growth Analytics
              </CardTitle>
              <CardDescription>
                Compare performance against the previous period
              </CardDescription>
            </div>
            <Select value={period} onValueChange={setPeriod}>
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="7">Last 7 days</SelectItem>
                <SelectItem value="30">Last 30 days</SelectItem>
                <SelectItem value="90">Last 90 days</SelectItem>
                <SelectItem value="365">Last 365 days</SelectItem>
                <SelectItem value="all">All time</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardHeader>
      </Card>

      {/* Growth Rate Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Revenue Growth */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <DollarSign className="h-5 w-5 text-blue-500" />
                <span className="text-sm font-medium text-muted-foreground">
                  Revenue
                </span>
              </div>
              <div className="flex items-center gap-1">
                {getGrowthIcon(summary.growthRates.revenue)}
                <span
                  className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.revenue)}`}
                >
                  {hideNumbers ? "***" : formatGrowthRate(summary.growthRates.revenue)}
                </span>
              </div>
            </div>
            <div className="mt-3">
              <div className="text-2xl font-bold">
                {maskValue(formatGBP(summary.currentPeriod.revenue))}
              </div>
              <div className="text-xs text-muted-foreground mt-1">
                vs {maskValue(formatGBP(summary.previousPeriod.revenue))} previous
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Orders Growth */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <ShoppingCart className="h-5 w-5 text-green-500" />
                <span className="text-sm font-medium text-muted-foreground">
                  Orders
                </span>
              </div>
              <div className="flex items-center gap-1">
                {getGrowthIcon(summary.growthRates.orders)}
                <span
                  className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.orders)}`}
                >
                  {hideNumbers ? "***" : formatGrowthRate(summary.growthRates.orders)}
                </span>
              </div>
            </div>
            <div className="mt-3">
              <div className="text-2xl font-bold">
                {maskValue(summary.currentPeriod.orders.toString())}
              </div>
              <div className="text-xs text-muted-foreground mt-1">
                vs {maskValue(summary.previousPeriod.orders.toString())} previous
              </div>
            </div>
          </CardContent>
        </Card>

        {/* AOV Growth */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Package className="h-5 w-5 text-purple-500" />
                <span className="text-sm font-medium text-muted-foreground">
                  Avg Order
                </span>
              </div>
              <div className="flex items-center gap-1">
                {getGrowthIcon(summary.growthRates.avgOrderValue)}
                <span
                  className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.avgOrderValue)}`}
                >
                  {hideNumbers ? "***" : formatGrowthRate(summary.growthRates.avgOrderValue)}
                </span>
              </div>
            </div>
            <div className="mt-3">
              <div className="text-2xl font-bold">
                {maskValue(formatGBP(summary.currentPeriod.avgOrderValue))}
              </div>
              <div className="text-xs text-muted-foreground mt-1">
                vs {maskValue(formatGBP(summary.previousPeriod.avgOrderValue))} previous
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Customers Growth */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Users className="h-5 w-5 text-orange-500" />
                <span className="text-sm font-medium text-muted-foreground">
                  Customers
                </span>
              </div>
              <div className="flex items-center gap-1">
                {getGrowthIcon(summary.growthRates.customers)}
                <span
                  className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.customers)}`}
                >
                  {hideNumbers ? "***" : formatGrowthRate(summary.growthRates.customers)}
                </span>
              </div>
            </div>
            <div className="mt-3">
              <div className="text-2xl font-bold">
                {maskValue(summary.currentPeriod.customers.toString())}
              </div>
              <div className="text-xs text-muted-foreground mt-1">
                vs {maskValue(summary.previousPeriod.customers.toString())} previous
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Revenue Trend Chart */}
      <Card>
        <CardHeader>
          <CardTitle>Revenue & Orders Over Time</CardTitle>
          <CardDescription>
            {data.period.granularity === "daily"
              ? "Daily"
              : data.period.granularity === "weekly"
                ? "Weekly"
                : "Monthly"}{" "}
            breakdown from {data.period.start} to {data.period.end}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {timeSeries.length === 0 ? (
            <div className="text-center py-8">
              <TrendingUp className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">
                No data available for this period
              </p>
            </div>
          ) : (
            <div className="h-72">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart
                  data={timeSeries}
                  margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
                >
                  <defs>
                    <linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#2563eb" stopOpacity={0.3} />
                      <stop offset="95%" stopColor="#2563eb" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis
                    dataKey="date"
                    tick={{ fontSize: 11 }}
                    angle={-45}
                    textAnchor="end"
                    height={60}
                  />
                  <YAxis
                    yAxisId="left"
                    tick={{ fontSize: 11 }}
                    tickFormatter={(value) =>
                      hideNumbers ? "***" : `£${(value / 1000).toFixed(0)}k`
                    }
                  />
                  <YAxis
                    yAxisId="right"
                    orientation="right"
                    tick={{ fontSize: 11 }}
                    tickFormatter={(value) => (hideNumbers ? "***" : value)}
                  />
                  <Tooltip content={<CustomTooltip />} />
                  <Area
                    yAxisId="left"
                    type="monotone"
                    dataKey="revenue"
                    stroke="#2563eb"
                    strokeWidth={2}
                    fill="url(#colorRevenue)"
                  />
                  <Line
                    yAxisId="right"
                    type="monotone"
                    dataKey="orders"
                    stroke="#22c55e"
                    strokeWidth={2}
                    dot={false}
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Customer Insights */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            Customer Insights
          </CardTitle>
          <CardDescription>
            New vs returning customers and engagement metrics
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
            <div className="text-center p-3 bg-muted/50 rounded-lg">
              <div className="text-2xl font-bold text-green-600">
                {maskValue(customerInsights.newCustomers.toString())}
              </div>
              <div className="text-xs text-muted-foreground">New Customers</div>
            </div>
            <div className="text-center p-3 bg-muted/50 rounded-lg">
              <div className="text-2xl font-bold text-blue-600">
                {maskValue(customerInsights.returningCustomers.toString())}
              </div>
              <div className="text-xs text-muted-foreground">Returning</div>
            </div>
            <div className="text-center p-3 bg-muted/50 rounded-lg">
              <div className="text-2xl font-bold text-purple-600">
                {maskValue(customerInsights.totalCustomers.toString())}
              </div>
              <div className="text-xs text-muted-foreground">Total</div>
            </div>
            <div className="text-center p-3 bg-muted/50 rounded-lg">
              <div className="text-2xl font-bold text-orange-600">
                {hideNumbers ? "***%" : `${customerInsights.newCustomerRate}%`}
              </div>
              <div className="text-xs text-muted-foreground">New Rate</div>
            </div>
            <div className="text-center p-3 bg-muted/50 rounded-lg">
              <div className="text-2xl font-bold text-pink-600">
                {maskValue(customerInsights.avgOrdersPerCustomer.toString())}
              </div>
              <div className="text-xs text-muted-foreground">Avg Orders</div>
            </div>
            <div className="text-center p-3 bg-muted/50 rounded-lg">
              <div className="text-2xl font-bold text-teal-600">
                {maskValue(formatGBP(customerInsights.avgSpentPerCustomer))}
              </div>
              <div className="text-xs text-muted-foreground">Avg Spent</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Top Growing Products */}
      {topGrowingProducts.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              Top Growing Products
            </CardTitle>
            <CardDescription>
              Products with the highest revenue growth compared to previous period
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {topGrowingProducts.slice(0, 5).map((product, index) => (
                <div
                  key={product.productId}
                  className="flex items-center justify-between p-3 bg-muted/30 rounded-lg"
                >
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary/10 text-primary text-sm font-bold">
                      {index + 1}
                    </div>
                    <div>
                      <div className="font-medium">{product.productName}</div>
                      <div className="text-xs text-muted-foreground">
                        {maskValue(formatGBP(product.currentPeriodRevenue))} revenue
                        {" · "}
                        {maskValue(product.currentPeriodQuantity.toString())} sold
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge
                      variant={product.revenueGrowth >= 0 ? "default" : "destructive"}
                      className="flex items-center gap-1"
                    >
                      {product.revenueGrowth >= 0 ? (
                        <TrendingUp className="h-3 w-3" />
                      ) : (
                        <TrendingDown className="h-3 w-3" />
                      )}
                      {hideNumbers ? "***" : formatGrowthRate(product.revenueGrowth)}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
