import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Line,
  LineChart,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import {
  clearCustomerList,
  loadAllCustomer,
} from "../../../redux/rtk/features/customer/customerSlice";
import { loadProduct } from "../../../redux/rtk/features/product/productSlice";

const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white p-4 border border-gray-200 rounded-lg shadow-lg">
        <p className="font-semibold text-gray-800 mb-2">{label}</p>
        {payload.map((entry, index) => (
          <p
            key={index}
            style={{ color: entry.color }}
            className="text-sm font-medium">
            {entry.name}:{" "}
            {typeof entry.value === "number"
              ? `৳${entry.value.toLocaleString()}`
              : entry.value}
          </p>
        ))}
      </div>
    );
  }
  return null;
};

const RADIAN = Math.PI / 180;
const PURCHASE_COLORS = [
  "#0088FE",
  "#00C49F",
  "#FFBB28",
  "#FF8042",
  "#E91E63",
  "#9C27B0",
  "#673AB7",
  "#3F51B5",
];

const renderCustomizedLabel = ({
  cx,
  cy,
  midAngle,
  innerRadius,
  outerRadius,
  percent,
}) => {
  if (cx == null || cy == null || innerRadius == null || outerRadius == null) {
    return null;
  }
  const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
  const ncx = Number(cx);
  const x = ncx + radius * Math.cos(-(midAngle ?? 0) * RADIAN);
  const ncy = Number(cy);
  const y = ncy + radius * Math.sin(-(midAngle ?? 0) * RADIAN);
  return (
    <text
      x={x}
      y={y}
      fill="white"
      textAnchor={x > ncx ? "start" : "end"}
      dominantBaseline="central">
      {`${((percent ?? 1) * 100).toFixed(0)}%`}
    </text>
  );
};

// Empty State Component
const EmptyState = ({ title, message }) => (
  <div className="flex flex-col items-center justify-center h-[300px] text-gray-400">
    <svg
      className="w-24 h-24 mb-4"
      fill="none"
      stroke="currentColor"
      viewBox="0 0 24 24">
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={1.5}
        d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
      />
    </svg>
    <p className="text-lg font-medium text-gray-600">{title}</p>
    <p className="text-sm text-gray-500 mt-1">{message}</p>
  </div>
);

const DashboardCharts = () => {
  const dispatch = useDispatch();
  const { info, loading } = useSelector((state) => state?.dashboard) || {};
  const { list } = useSelector((state) => state.products);
  const { list: customerList, total } = useSelector((state) => state.customers);

  // Define pageConfig - adjust based on your actual requirements
  const [pageConfig, setPageConfig] = useState({
    storeId: null,
    page: 1,
    limit: 4,
  });

  // Filter and prepare monthly data - only show months where sales OR purchase exist
  const filteredMonthlyData = (info?.monthlyData || []).filter(
    (item) => item.sales > 0 || item.purchase > 0
  );

  // Filter sale breakdown - only show items where value exists (greater than 0)
  const filteredSaleBreakdown = (info?.saleBreakdown || []).filter(
    (item) => item.value > 0
  );

  // Filter purchase breakdown - only show items where value exists (greater than 0)
  const filteredPurchaseBreakdown = (info?.purchaseBreakdown || []).filter(
    (item) => item.value > 0
  );

  // Filter store comparison - only show stores where revenue OR orders exist
  const filteredStoreComparison = (info?.storeComparison || []).filter(
    (item) => item.revenue > 0 || item.orders > 0
  );

  // Get up to 5 products from list - filter products with stock quantity > 0
  const products = (list || [])
    .filter(
      (product) =>
        product.stockInfo &&
        product.stockInfo.length > 0 &&
        product.stockInfo[0].productQuantity > 0
    )
    .slice(0, 4);

  // Get up to 5 customers from customerList
  const customers = (customerList || []).slice(0, 4);

  useEffect(() => {
    dispatch(loadProduct(pageConfig));
  }, [dispatch, pageConfig]);

  useEffect(() => {
    dispatch(loadAllCustomer(pageConfig));
    return () => {
      dispatch(clearCustomerList());
    };
  }, [dispatch, pageConfig]);

  // Medal/Trophy icons for ranking
  const getRankIcon = (index) => {
    switch (index) {
      case 0:
        return (
          <div className="flex items-center justify-center w-10 h-10 rounded-full bg-yellow-100">
            <svg
              className="w-6 h-6 text-yellow-500"
              fill="currentColor"
              viewBox="0 0 20 20">
              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
            </svg>
          </div>
        );
      case 1:
        return (
          <div className="flex items-center justify-center w-10 h-10 rounded-full bg-gray-100">
            <svg
              className="w-6 h-6 text-gray-400"
              fill="currentColor"
              viewBox="0 0 20 20">
              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
            </svg>
          </div>
        );
      case 2:
        return (
          <div className="flex items-center justify-center w-10 h-10 rounded-full bg-orange-100">
            <svg
              className="w-6 h-6 text-orange-400"
              fill="currentColor"
              viewBox="0 0 20 20">
              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
            </svg>
          </div>
        );
      default:
        return (
          <div className="flex items-center justify-center w-10 h-10 rounded-full bg-blue-100">
            <svg
              className="w-6 h-6 text-blue-400"
              fill="currentColor"
              viewBox="0 0 20 20">
              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
            </svg>
          </div>
        );
    }
  };

  return (
    <div className="space-y-6 ">
      {/* Sales Overview and Revenue Breakdown Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Sales Overview Chart */}
        <div className="bg-gray-50 p-6 rounded-xl ">
          <div className="mb-4">
            <h2 className="text-xl font-semibold text-gray-800">
              Sales vs Purchases (Monthly)
            </h2>
            <p className="text-sm text-gray-500">
              Monthly sales vs purchase performance
            </p>
          </div>
          {filteredMonthlyData.length > 0 ? (
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={filteredMonthlyData}>
                <defs>
                  <linearGradient
                    id="salesGradient"
                    x1="0"
                    y1="0"
                    x2="0"
                    y2="1">
                    <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.8} />
                    <stop offset="95%" stopColor="#3b82f6" stopOpacity={0.1} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis
                  dataKey="month"
                  stroke="#6b7280"
                  style={{ fontSize: "14px" }}
                />
                <YAxis
                  stroke="#6b7280"
                  style={{ fontSize: "14px" }}
                  domain={[0, "auto"]}
                  allowDataOverflow={false}
                />
                <Tooltip content={<CustomTooltip />} />
                <Legend wrapperStyle={{ paddingTop: "20px" }} />
                <Line
                  type="monotone"
                  dataKey="sales"
                  stroke="#3b82f6"
                  strokeWidth={3}
                  dot={{ fill: "#3b82f6", r: 5 }}
                  activeDot={{ r: 7 }}
                  name="Sales"
                  connectNulls
                />
                <Line
                  type="monotone"
                  dataKey="purchase"
                  stroke="#10b981"
                  strokeWidth={2}
                  strokeDasharray="5 5"
                  dot={{ fill: "#10b981", r: 4 }}
                  name="Purchase"
                  connectNulls
                />
              </LineChart>
            </ResponsiveContainer>
          ) : (
            <EmptyState
              title="No Data Available"
              message="Sales and purchase data will appear here when available"
            />
          )}
        </div>

        {/* Revenue Breakdown Pie Chart */}
        <div className="bg-gray-50 p-6 rounded-xl ">
          <div className="mb-4">
            <h2 className="text-xl font-semibold text-gray-800">
              Sales (Paid/Due/Return)
            </h2>
            <p className="text-sm text-gray-500">
              Sales Overview Paid, Due, and Returned
            </p>
          </div>
          {filteredSaleBreakdown.length > 0 ? (
            <>
              <ResponsiveContainer width="100%" height={350}>
                <PieChart>
                  <Pie
                    data={filteredSaleBreakdown}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={110}
                    paddingAngle={5}
                    dataKey="value"
                    label={({ name, percent }) =>
                      `${name}: ${(percent * 100).toFixed(0)}%`
                    }
                    labelLine={{ stroke: "#6b7280", strokeWidth: 1 }}>
                    {filteredSaleBreakdown.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip content={<CustomTooltip />} />
                </PieChart>
              </ResponsiveContainer>

              {/* Status Legend */}
              <div className="mt-6 flex flex-wrap items-center justify-center gap-8">
                {filteredSaleBreakdown.map((item, index) => (
                  <div key={index} className="flex items-center gap-2">
                    <div
                      className="w-3 h-3 rounded-full"
                      style={{ backgroundColor: item.color }}></div>
                    <span className="text-sm text-gray-700 font-medium">
                      {item.name}
                    </span>
                    <span className="text-sm text-gray-500">
                      (৳{item.value.toLocaleString()})
                    </span>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <EmptyState
              title="No Sales Data"
              message="Sales breakdown data will appear here when available"
            />
          )}
        </div>
      </div>

      {/* Store Comparison and Purchase Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Purchase - Custom Pie Chart with Percentage Labels */}
        <div className="bg-gray-50 p-6 rounded-xl ">
          <div className="mb-4">
            <h2 className="text-xl font-semibold  text-gray-800">
              Purchase Distribution
            </h2>
            <p className="text-sm text-gray-500">
              Purchase Overview Paid, Due, and Returned
            </p>
          </div>
          {filteredPurchaseBreakdown.length > 0 ? (
            <>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={filteredPurchaseBreakdown}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={renderCustomizedLabel}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value">
                    {filteredPurchaseBreakdown.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip content={<CustomTooltip />} />
                </PieChart>
              </ResponsiveContainer>

              {/* Purchase Status Legend */}
              <div className="mt-6 flex flex-wrap items-center justify-center gap-6">
                {filteredPurchaseBreakdown.map((item, index) => (
                  <div key={index} className="flex items-center gap-2">
                    <div
                      className="w-3 h-3 rounded-full"
                      style={{ backgroundColor: item.color }}></div>
                    <span className="text-sm text-gray-700 font-medium">
                      {item.name}
                    </span>
                    <span className="text-sm text-gray-500">
                      (৳{item.value.toLocaleString()})
                    </span>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <EmptyState
              title="No Purchase Data"
              message="Purchase breakdown data will appear here when available"
            />
          )}
        </div>

        {/* Store Comparison Bar Chart */}
        <div className="bg-gray-50 p-6 rounded-xl">
          <div className="mb-4">
            <h2 className="text-xl font-semibold text-gray-800">
              Store Comparison
            </h2>
            <p className="text-sm text-gray-500">Revenue and orders by store</p>
          </div>
          {filteredStoreComparison.length > 0 ? (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={filteredStoreComparison}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis
                  dataKey="store"
                  stroke="#6b7280"
                  style={{ fontSize: "12px" }}
                />
                <YAxis stroke="#6b7280" style={{ fontSize: "12px" }} />
                <Tooltip content={<CustomTooltip />} />
                <Legend />
                <Bar
                  dataKey="revenue"
                  fill="#8b5cf6"
                  radius={[8, 8, 0, 0]}
                  name="Revenue"
                />
                <Bar
                  dataKey="orders"
                  fill="#ec4899"
                  radius={[8, 8, 0, 0]}
                  name="Orders"
                />
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <EmptyState
              title="No Store Data"
              message="Store comparison data will appear here when available"
            />
          )}
        </div>
      </div>

      {/* Products and Customers Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Best Selling Products */}
        <div className="bg-gray-50 p-6 rounded-xl">
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-2">
              <svg
                className="w-6 h-6 text-gray-700"
                fill="currentColor"
                viewBox="0 0 20 20">
                <path d="M10 3.5a1.5 1.5 0 013 0V4a1 1 0 001 1h3a1 1 0 011 1v3a1 1 0 01-1 1h-.5a1.5 1.5 0 000 3h.5a1 1 0 011 1v3a1 1 0 01-1 1h-3a1 1 0 01-1-1v-.5a1.5 1.5 0 00-3 0v.5a1 1 0 01-1 1H6a1 1 0 01-1-1v-3a1 1 0 00-1-1h-.5a1.5 1.5 0 010-3H4a1 1 0 001-1V6a1 1 0 011-1h3a1 1 0 001-1v-.5z" />
              </svg>
              <h2 className="text-lg font-semibold text-gray-800">
                Selling Products
              </h2>
            </div>
          </div>

          {products.length > 0 ? (
            <div className="space-y-3">
              {products.map((product, index) => {
                const stockInfo = product.stockInfo[0];

                return (
                  <div
                    key={product.id || index}
                    className="flex items-center justify-between bg-white p-3 rounded-lg  transition-colors">
                    <div className="flex items-center gap-3  flex-1">
                      <div className="flex-1">
                        <h3 className="font-medium text-gray-800 text-sm">
                          {product.name}
                        </h3>
                        <p className="text-xs text-gray-500 mt-0.5">
                          {stockInfo.productQuantity} Units Sold
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-blue-50">
                      <span className="text-sm font-bold text-blue-600">
                        #{index + 1}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <EmptyState
              title="No Product Data"
              message="Best selling products will appear here when available"
            />
          )}
        </div>

        {/* Top Customers */}
        <div className="bg-gray-50 p-6 rounded-xl">
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-2">
              <svg
                className="w-6 h-6 text-gray-700"
                fill="currentColor"
                viewBox="0 0 20 20">
                <path d="M9 6a3 3 0 11-6 0 3 3 0 016 0zM17 6a3 3 0 11-6 0 3 3 0 016 0zM12.93 17c.046-.327.07-.66.07-1a6.97 6.97 0 00-1.5-4.33A5 5 0 0119 16v1h-6.07zM6 11a5 5 0 015 5v1H1v-1a5 5 0 015-5z" />
              </svg>
              <h2 className="text-lg font-semibold text-gray-800">Customers</h2>
            </div>
          </div>

          {customers.length > 0 ? (
            <div className="space-y-3">
              {customers.map((customer, index) => {
                return (
                  <div
                    key={customer.id || index}
                    className="flex items-center bg-white justify-between p-3 rounded-lg   transition-colors">
                    <div className="flex items-center gap-3 flex-1">
                      <div className="flex-1">
                        <h3 className="font-medium text-gray-800 text-sm">
                          {customer.username || customer.name || "N/A"}
                        </h3>
                        <p className="text-xs text-gray-500 mt-0.5">
                          ৳{customer.dueAmount?.toLocaleString() || "0"} Due
                          Amount
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-purple-50">
                      <span className="text-sm font-bold text-purple-600">
                        #{index + 1}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <EmptyState
              title="No Customer Data"
              message="Top customers will appear here when available"
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default DashboardCharts;
