import { useState, useEffect } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "../../components/ui/card";
import { Skeleton } from "../../components/ui/skeleton";
import { BarChart3, Loader2 } from "lucide-react";
import { Button } from "../../components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../../components/ui/dialog";
import { PieChart, Pie, ResponsiveContainer, Cell, Sector } from "recharts";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../components/ui/table";

// Add this constant for pie chart colors
const COLORS = [
  "#0088FE",
  "#00C49F",
  "#FFBB28",
  "#FF8042",
  "#8884D8",
  "#82CA9D",
  "#FFC658",
  "#FF7C43",
];

// The renderActiveShape function for pie charts
const renderActiveShape = (props: any) => {
  const {
    cx,
    cy,
    innerRadius,
    outerRadius,
    startAngle,
    endAngle,
    fill,
    category,
    total_spend,
  } = props;

  // Split category name into words and create lines of max 12 chars
  const words = category.split(" ");
  const lines: string[] = [];
  let currentLine = "";

  words.forEach((word: string) => {
    if ((currentLine + " " + word).length <= 12) {
      currentLine = currentLine ? `${currentLine} ${word}` : word;
    } else {
      if (currentLine) lines.push(currentLine);
      currentLine = word;
    }
  });
  if (currentLine) lines.push(currentLine);

  return (
    <g>
      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius}
        outerRadius={outerRadius}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
      />
      <Sector
        cx={cx}
        cy={cy}
        startAngle={startAngle}
        endAngle={endAngle}
        innerRadius={outerRadius - 1}
        outerRadius={outerRadius + 4}
        fill={fill}
      />
      {lines.map((line, i) => (
        <text
          key={i}
          x={cx}
          y={cy}
          dy={-20 + i * 16}
          textAnchor="middle"
          fill="#888888"
          className="text-xs"
        >
          {line}
        </text>
      ))}
      <text
        x={cx}
        y={cy}
        dy={lines.length * 16 - 10}
        textAnchor="middle"
        fill="#000000"
        className="text-base font-medium"
      >
        {`$${Number(total_spend).toLocaleString("en-US", {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`}
      </text>
    </g>
  );
};

interface CategoryMetricsCardProps {
  loading: boolean;
  yearlyCategoryData: {
    category: string;
    unique_products?: number;
    total_spend: number;
    percentage?: number;
    avg_cost?: number;
    cost_variance?: number;
  }[];
  yearlyDataLoading: boolean;
}

export default function CategoryMetricsCard({
  loading,
  yearlyCategoryData,
  yearlyDataLoading,
}: CategoryMetricsCardProps) {
  const [costAnalysisOpen, setCostAnalysisOpen] = useState(false);
  const [activeSpendingIndex, setActiveSpendingIndex] = useState<
    number | undefined
  >();
  const [initialLoading, setInitialLoading] = useState(true);

  // Only show loading state on initial load, not during table refreshes
  useEffect(() => {
    if (yearlyCategoryData.length > 0 && !yearlyDataLoading) {
      setInitialLoading(false);
    }
  }, [yearlyCategoryData, yearlyDataLoading]);

  const formatNumber = (value: number) => {
    return value.toLocaleString("en-US", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });
  };

  const formatCurrency = (value: number) => {
    return `$${formatNumber(value)}`;
  };

  const formatPercent = (value: number) => {
    return (
      (value * 100).toLocaleString("en-US", {
        minimumFractionDigits: 1,
        maximumFractionDigits: 1,
      }) + "%"
    );
  };

  // Prepare spending chart data
  const prepareSpendingChartData = () => {
    if (!yearlyCategoryData.length) return [];

    // Make a copy to avoid modifying state directly
    const categoryArray = [...yearlyCategoryData];
    const totalSpend = categoryArray.reduce(
      (sum, cat) => sum + cat.total_spend,
      0
    );

    // Split into significant categories (>=1%) and others
    const significantCategories = categoryArray.filter(
      (cat) => cat.total_spend / totalSpend >= 0.01
    );

    const otherCategories = categoryArray.filter(
      (cat) => cat.total_spend / totalSpend < 0.01
    );

    let result = [...significantCategories];

    // Add "Other" category if needed
    if (otherCategories.length > 0) {
      const otherTotalSpend = otherCategories.reduce(
        (sum, cat) => sum + cat.total_spend,
        0
      );

      result.push({
        category: "Other",
        total_spend: otherTotalSpend,
        percentage: otherTotalSpend / totalSpend,
        unique_products: otherCategories.reduce(
          (sum, cat) => sum + (cat.unique_products || 0),
          0
        ),
        avg_cost:
          otherTotalSpend /
          otherCategories.reduce(
            (sum, cat) => sum + (cat.unique_products || 0),
            1
          ),
        cost_variance: 0,
      });
    }

    // Sort by spend amount descending
    return result.sort((a, b) => b.total_spend - a.total_spend);
  };

  // Cost analysis table component
  const CostAnalysisTable = () => {
    if (!yearlyCategoryData.length) {
      return yearlyDataLoading ? (
        <div className="flex justify-center p-4">
          <Loader2 className="h-8 w-8 animate-spin" />
        </div>
      ) : (
        <div className="text-center p-4 text-muted-foreground">
          No category data available for the past 12 months
        </div>
      );
    }

    return (
      <div>
        {yearlyDataLoading ? (
          <div className="flex justify-center p-4">
            <Loader2 className="h-8 w-8 animate-spin" />
          </div>
        ) : (
          <>
            <div className="text-sm font-medium mb-2 px-4 flex justify-between">
              <span>
                Showing received inventory by category for the past 12 months
              </span>
              <span>{yearlyCategoryData.length} categories found</span>
            </div>
            <div className="text-xs text-muted-foreground px-4 mb-2">
              Note: items can be in multiple categories, so the sum of the
              categories will not equal the total spend.
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Category</TableHead>
                  <TableHead>Products</TableHead>
                  <TableHead>Avg. Cost</TableHead>
                  <TableHead>Price Variance</TableHead>
                  <TableHead>Total Spend</TableHead>
                  <TableHead>% of Total</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {yearlyCategoryData.map((category) => {
                  // Calculate percentage of total spend
                  const totalSpendPercentage =
                    "percentage" in category &&
                    typeof category.percentage === "number"
                      ? category.percentage
                      : yearlyCategoryData.reduce(
                          (sum, cat) => sum + cat.total_spend,
                          0
                        ) > 0
                      ? category.total_spend /
                        yearlyCategoryData.reduce(
                          (sum, cat) => sum + cat.total_spend,
                          0
                        )
                      : 0;

                  return (
                    <TableRow key={category.category}>
                      <TableCell className="font-medium">
                        {category.category || "Uncategorized"}
                      </TableCell>
                      <TableCell>
                        {category.unique_products?.toLocaleString() || "N/A"}
                      </TableCell>
                      <TableCell>
                        {category.avg_cost !== undefined
                          ? formatCurrency(category.avg_cost)
                          : "N/A"}
                      </TableCell>
                      <TableCell>
                        {category.cost_variance !== undefined
                          ? parseFloat(
                              category.cost_variance.toFixed(2)
                            ).toLocaleString()
                          : "N/A"}
                      </TableCell>
                      <TableCell>
                        {formatCurrency(category.total_spend)}
                      </TableCell>
                      <TableCell>
                        {formatPercent(totalSpendPercentage)}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </>
        )}
      </div>
    );
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">
          Received by Category
        </CardTitle>
        <Dialog open={costAnalysisOpen} onOpenChange={setCostAnalysisOpen}>
          <DialogTrigger asChild>
            <Button variant="outline" disabled={initialLoading || loading}>
              <BarChart3 className="h-4 w-4" />
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-[90%] w-fit">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <BarChart3 className="h-5 w-5" />
                <span>Received Inventory by Category</span>
              </DialogTitle>
            </DialogHeader>
            <div className="overflow-auto max-h-[70vh]">
              <CostAnalysisTable />
            </div>
          </DialogContent>
        </Dialog>
      </CardHeader>
      <CardContent>
        {initialLoading || loading ? (
          <div className="flex flex-col items-center justify-center h-[170px]">
            <Skeleton className="h-[170px] w-[170px] rounded-full" />
          </div>
        ) : (
          <>
            <div className="h-[170px] relative">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart margin={{ top: 30, right: 0, left: 0, bottom: 30 }}>
                  <Pie
                    data={prepareSpendingChartData()}
                    dataKey="total_spend"
                    nameKey="category"
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={1}
                    activeIndex={activeSpendingIndex}
                    activeShape={renderActiveShape}
                    onMouseEnter={(_, index) => setActiveSpendingIndex(index)}
                    onMouseLeave={() => setActiveSpendingIndex(undefined)}
                  >
                    {prepareSpendingChartData().map((entry, index) => (
                      <Cell
                        key={entry.category}
                        fill={COLORS[index % COLORS.length]}
                      />
                    ))}
                  </Pie>
                </PieChart>
              </ResponsiveContainer>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
} 