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 VendorMetricsCardProps {
  loading: boolean;
  yearlyVendorData: {
    vendor: string;
    orders: number;
    total_spend: number;
    percentage?: number;
  }[];
  yearlyDataLoading: boolean;
}

export default function VendorMetricsCard({
  loading,
  yearlyVendorData,
  yearlyDataLoading,
}: VendorMetricsCardProps) {
  const [vendorAnalysisOpen, setVendorAnalysisOpen] = useState(false);
  const [activeVendorIndex, setActiveVendorIndex] = useState<
    number | undefined
  >();
  const [initialLoading, setInitialLoading] = useState(true);

  // Only show loading state on initial load, not during table refreshes
  useEffect(() => {
    if (yearlyVendorData.length > 0 && !yearlyDataLoading) {
      setInitialLoading(false);
    }
  }, [yearlyVendorData, 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 vendor chart data
  const prepareVendorChartData = () => {
    if (!yearlyVendorData.length) return [];

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

    // Split into significant vendors (>=1%) and others
    const significantVendors = vendorArray.filter(
      (vendor) => vendor.total_spend / totalSpend >= 0.01
    );

    const otherVendors = vendorArray.filter(
      (vendor) => vendor.total_spend / totalSpend < 0.01
    );

    let result = [...significantVendors];

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

      result.push({
        vendor: "Other Vendors",
        total_spend: otherTotalSpend,
        percentage: otherTotalSpend / totalSpend,
        orders: otherVendors.reduce((sum, vendor) => sum + vendor.orders, 0),
      });
    }

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

  // Get all vendors for table
  const getAllVendorsForTable = () => {
    if (!yearlyVendorData.length) return [];
    return [...yearlyVendorData].sort((a, b) => b.total_spend - a.total_spend);
  };

  // Vendor analysis table component
  const VendorAnalysisTable = () => {
    const vendorData = getAllVendorsForTable();

    if (!vendorData.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 supplier 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 flex justify-between items-center px-4">
              <span>
                Showing received inventory by supplier for the past 12 months
              </span>
              <span>{vendorData.length} suppliers found</span>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Supplier</TableHead>
                  <TableHead>Orders</TableHead>
                  <TableHead>Total Spend</TableHead>
                  <TableHead>% of Total</TableHead>
                  <TableHead>Avg. Order Value</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {vendorData.map((vendor) => {
                  return (
                    <TableRow key={vendor.vendor}>
                      <TableCell className="font-medium">
                        {vendor.vendor}
                      </TableCell>
                      <TableCell>{vendor.orders.toLocaleString()}</TableCell>
                      <TableCell>
                        {formatCurrency(vendor.total_spend)}
                      </TableCell>
                      <TableCell>
                        {formatPercent(vendor.percentage || 0)}
                      </TableCell>
                      <TableCell>
                        {formatCurrency(
                          vendor.orders ? vendor.total_spend / vendor.orders : 0
                        )}
                      </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 Supplier
        </CardTitle>
        <Dialog
          open={vendorAnalysisOpen}
          onOpenChange={setVendorAnalysisOpen}
        >
          <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 Supplier</span>
              </DialogTitle>
            </DialogHeader>
            <div className="overflow-auto max-h-[70vh]">
              <VendorAnalysisTable />
            </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>
                  <Pie
                    data={prepareVendorChartData()}
                    dataKey="total_spend"
                    nameKey="vendor"
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={1}
                    activeIndex={activeVendorIndex}
                    activeShape={(props: any) =>
                      renderActiveShape({ ...props, category: props.vendor })
                    }
                    onMouseEnter={(_, index) => setActiveVendorIndex(index)}
                    onMouseLeave={() => setActiveVendorIndex(undefined)}
                  >
                    {prepareVendorChartData().map((entry, index) => (
                      <Cell
                        key={entry.vendor}
                        fill={COLORS[index % COLORS.length]}
                      />
                    ))}
                  </Pie>
                </PieChart>
              </ResponsiveContainer>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
} 