"use client";

import { useState, useEffect } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import {
  TrendingUp,
  TrendingDown,
  Users,
  ShoppingCart,
  DollarSign,
  Package,
  RefreshCw,
} from "lucide-react";
import {
  getGrowthAnalyticsWithStore,
  type GrowthAnalytics,
} from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
import {
  ComposedChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from "recharts";

interface GrowthAnalyticsChartProps {
  hideNumbers?: boolean;
}

const SEGMENT_COLORS = {
  new: "#3b82f6",
  returning: "#10b981",
  loyal: "#f59e0b",
  vip: "#8b5cf6",
};

export default function GrowthAnalyticsChart({
  hideNumbers = false,
}: GrowthAnalyticsChartProps) {
  const [data, setData] = useState<GrowthAnalytics | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState("30");
  const [refreshing, setRefreshing] = useState(false);
  const { toast } = useToast();

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

  useEffect(() => {
    fetchData();
  }, [period]);

  const handleRefresh = () => {
    setRefreshing(true);
    fetchData();
  };

  const formatCurrency = (value: number) => {
    if (hideNumbers) return "£***";
    return new Intl.NumberFormat("en-GB", {
      style: "currency",
      currency: "GBP",
      maximumFractionDigits: 0,
    }).format(value);
  };

  const formatNumber = (value: number) => {
    if (hideNumbers) return "***";
    return value.toLocaleString();
  };

  const TrendIndicator = ({
    value,
    suffix = "%",
  }: {
    value: number;
    suffix?: string;
  }) => {
    if (hideNumbers) return <span className="text-muted-foreground">***</span>;

    const isPositive = value > 0;
    const isNeutral = value === 0;

    return (
      <div
        className={`flex items-center text-sm font-medium ${
          isNeutral
            ? "text-muted-foreground"
            : isPositive
              ? "text-green-600"
              : "text-red-600"
        }`}
      >
        {isPositive ? (
          <TrendingUp className="h-4 w-4 mr-1" />
        ) : isNeutral ? null : (
          <TrendingDown className="h-4 w-4 mr-1" />
        )}
        {isPositive ? "+" : ""}
        {value.toFixed(1)}
        {suffix}
      </div>
    );
  };

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

  if (loading && !data) {
    return (
      <div className="flex justify-center my-8">
        <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
      </div>
    );
  }

  if (!data) {
    return (
      <Card>
        <CardContent className="pt-6">
          <div className="text-center text-muted-foreground">
            No growth data available
          </div>
        </CardContent>
      </Card>
    );
  }

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

  // Prepare pie chart data
  const segmentData = [
    {
      name: "New",
      value: customerInsights.newCustomers,
      color: SEGMENT_COLORS.new,
    },
    {
      name: "Returning",
      value: customerInsights.returningCustomers,
      color: SEGMENT_COLORS.returning,
    },
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-lg font-semibold">Store Growth</h3>
          <p className="text-sm text-muted-foreground">
            {data.period.start} to {data.period.end} ({data.period.granularity})
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-[140px]">
              <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 year</SelectItem>
              <SelectItem value="all">All time</SelectItem>
            </SelectContent>
          </Select>
          <Button
            variant="outline"
            size="icon"
            onClick={handleRefresh}
            disabled={refreshing}
          >
            <RefreshCw
              className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`}
            />
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Orders */}
        <Card>
          <CardHeader className="pb-2">
            <div className="flex justify-between items-start">
              <CardTitle className="text-sm font-medium">Orders</CardTitle>
              <ShoppingCart className="h-4 w-4 text-muted-foreground" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatNumber(summary.currentPeriod.orders)}
            </div>
            <div className="flex items-center justify-between mt-1">
              <span className="text-xs text-muted-foreground">
                vs {formatNumber(summary.previousPeriod.orders)} prev
              </span>
              <TrendIndicator value={summary.growthRates.orders} />
            </div>
          </CardContent>
        </Card>

        {/* Revenue */}
        <Card>
          <CardHeader className="pb-2">
            <div className="flex justify-between items-start">
              <CardTitle className="text-sm font-medium">Revenue</CardTitle>
              <DollarSign className="h-4 w-4 text-muted-foreground" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {formatCurrency(summary.currentPeriod.revenue)}
            </div>
            <div className="flex items-center justify-between mt-1">
              <span className="text-xs text-muted-foreground">
                vs {formatCurrency(summary.previousPeriod.revenue)} prev
              </span>
              <TrendIndicator value={summary.growthRates.revenue} />
            </div>
          </CardContent>
        </Card>

        {/* Avg Order Value */}
        <Card>
          <CardHeader className="pb-2">
            <div className="flex justify-between items-start">
              <CardTitle className="text-sm font-medium">Avg Order</CardTitle>
              <Package className="h-4 w-4 text-muted-foreground" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatCurrency(summary.currentPeriod.avgOrderValue)}
            </div>
            <div className="flex items-center justify-between mt-1">
              <span className="text-xs text-muted-foreground">
                vs {formatCurrency(summary.previousPeriod.avgOrderValue)} prev
              </span>
              <TrendIndicator value={summary.growthRates.avgOrderValue} />
            </div>
          </CardContent>
        </Card>

        {/* Customers */}
        <Card>
          <CardHeader className="pb-2">
            <div className="flex justify-between items-start">
              <CardTitle className="text-sm font-medium">Customers</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatNumber(summary.currentPeriod.customers)}
            </div>
            <div className="flex items-center justify-between mt-1">
              <span className="text-xs text-muted-foreground">
                vs {formatNumber(summary.previousPeriod.customers)} prev
              </span>
              <TrendIndicator value={summary.growthRates.customers} />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Orders & Revenue Chart */}
      <Card>
        <CardHeader>
          <CardTitle>Orders & Revenue Trend</CardTitle>
          <CardDescription>
            Performance over the selected time period
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading || refreshing ? (
            <div className="flex items-center justify-center h-80">
              <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
            </div>
          ) : timeSeries.length > 0 ? (
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <ComposedChart
                  data={timeSeries}
                  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis
                    dataKey="date"
                    tick={{ fontSize: 12 }}
                    angle={-45}
                    textAnchor="end"
                    height={60}
                  />
                  <YAxis
                    yAxisId="left"
                    tick={{ fontSize: 12 }}
                    tickFormatter={(v) => (hideNumbers ? "***" : v)}
                  />
                  <YAxis
                    yAxisId="right"
                    orientation="right"
                    tick={{ fontSize: 12 }}
                    tickFormatter={(v) =>
                      hideNumbers ? "***" : `£${(v / 1000).toFixed(0)}k`
                    }
                  />
                  <Tooltip content={<CustomTooltip />} />
                  <Bar
                    yAxisId="left"
                    dataKey="orders"
                    fill="#3b82f6"
                    radius={[4, 4, 0, 0]}
                    name="Orders"
                  />
                  <Line
                    yAxisId="right"
                    type="monotone"
                    dataKey="revenue"
                    stroke="#10b981"
                    strokeWidth={3}
                    dot={{ fill: "#10b981", r: 4 }}
                    name="Revenue"
                  />
                </ComposedChart>
              </ResponsiveContainer>
            </div>
          ) : (
            <div className="flex items-center justify-center h-80 text-muted-foreground">
              No data available for the selected period
            </div>
          )}
        </CardContent>
      </Card>

      {/* Customer Breakdown & Top Products */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Customer Segments */}
        <Card>
          <CardHeader>
            <CardTitle>Customer Breakdown</CardTitle>
            <CardDescription>New vs returning customers</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-3 gap-4 mb-4">
              <div className="bg-muted/50 p-3 rounded-lg text-center">
                <div className="text-2xl font-bold text-blue-600">
                  {formatNumber(customerInsights.newCustomers)}
                </div>
                <div className="text-xs text-muted-foreground">New</div>
              </div>
              <div className="bg-muted/50 p-3 rounded-lg text-center">
                <div className="text-2xl font-bold text-green-600">
                  {formatNumber(customerInsights.returningCustomers)}
                </div>
                <div className="text-xs text-muted-foreground">Returning</div>
              </div>
              <div className="bg-muted/50 p-3 rounded-lg text-center">
                <div className="text-2xl font-bold">
                  {formatNumber(customerInsights.totalCustomers)}
                </div>
                <div className="text-xs text-muted-foreground">Total</div>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="bg-muted/50 p-3 rounded-lg text-center">
                <div className="text-lg font-bold">
                  {hideNumbers
                    ? "***"
                    : customerInsights.avgOrdersPerCustomer.toFixed(1)}
                </div>
                <div className="text-xs text-muted-foreground">
                  Avg Orders/Customer
                </div>
              </div>
              <div className="bg-muted/50 p-3 rounded-lg text-center">
                <div className="text-lg font-bold">
                  {formatCurrency(customerInsights.avgSpentPerCustomer)}
                </div>
                <div className="text-xs text-muted-foreground">
                  Avg Spent/Customer
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Top Growing Products */}
        <Card>
          <CardHeader>
            <CardTitle>Top Growing Products</CardTitle>
            <CardDescription>
              Highest revenue growth vs previous period
            </CardDescription>
          </CardHeader>
          <CardContent>
            {topGrowingProducts.length > 0 ? (
              <div className="space-y-2">
                {topGrowingProducts.slice(0, 5).map((product, index) => (
                  <div
                    key={product.productId}
                    className="flex items-center justify-between p-2 bg-muted/30 rounded-lg"
                  >
                    <div className="flex items-center gap-2">
                      <div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary/10 text-primary text-xs font-semibold">
                        {index + 1}
                      </div>
                      <div>
                        <div className="text-sm font-medium truncate max-w-[150px]">
                          {product.productName}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {formatCurrency(product.currentPeriodRevenue)}
                        </div>
                      </div>
                    </div>
                    <div
                      className={`text-sm font-semibold ${
                        product.revenueGrowth >= 0
                          ? "text-green-600"
                          : "text-red-600"
                      }`}
                    >
                      {hideNumbers
                        ? "***"
                        : `${product.revenueGrowth >= 0 ? "+" : ""}${product.revenueGrowth.toFixed(0)}%`}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center text-muted-foreground py-8">
                No product growth data available
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
