import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ChevronDownIcon,
  ChevronRightIcon,
  ScaleIcon,
  CubeIcon,
  ShoppingBagIcon,
  GiftIcon,
  TruckIcon,
  UserIcon,
} from "@heroicons/react/24/outline";
import { useApiRequest } from "../../utils/useApiRequest";

export const LiveStockHerdDetails = ({
  farmid,
  name,
}: {
  farmid: string;
  name: string;
}) => {
  const [expandedProducts, setExpandedProducts] = useState<
    Record<number, boolean>
  >({});
  const [expandedItems, setExpandedItems] = useState<Record<string, boolean>>(
    {}
  );

  const { data: herdData } = useApiRequest({
    api: `herd/web/api/v1/rancher/${farmid}/rancher_dashboard_by_product_usage/`,
    method: "get",
    queryKey: ["HerdDetails"],
  });

  // Sample data structure based on your example
  const products = herdData || [];

  const toggleProduct = (productId: number) => {
    setExpandedProducts((prev) => ({
      ...prev,
      [productId]: !prev[productId],
    }));
  };

  const toggleItem = (productId: number, itemIndex: number) => {
    const key = `${productId}-${itemIndex}`;
    setExpandedItems((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const getAnimalTypeColor = (type: string) => {
    return type === "H"
      ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
      : "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200";
  };

  const getAnimalTypeText = (type: string) => {
    return type === "H" ? "دام سنگین" : "دام سبک";
  };

  const formatWeight = (weight: number) => {
    return weight.toLocaleString("fa-IR") + " کیلوگرم";
  };

  return (
    <div className="w-full mx-auto rtl">
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="bg-gradient-to-r from-primary-600 to-primary-800 rounded-2xl shadow-2xl p-6 mb-4"
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="bg-white/20 p-3 rounded-xl">
              <UserIcon className="h-8 w-8 text-white" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">
                جزئیات دامدار: {name}
              </h1>
            </div>
          </div>
        </div>
      </motion.div>

      <div className="space-y-4">
        {products.map((product: any, index: number) => (
          <motion.div
            key={product.product_id}
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.3, delay: index * 0.1 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-lg overflow-hidden border border-gray-200 dark:border-gray-700"
          >
            <div
              className="p-6 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900/60 transition-colors"
              onClick={() => toggleProduct(product.product_id)}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div
                    className={`p-3 rounded-lg ${
                      expandedProducts[product.product_id]
                        ? "bg-primary-100 dark:bg-primary-900"
                        : "bg-gray-100 dark:bg-gray-700"
                    }`}
                  >
                    <CubeIcon className="h-6 w-6 text-primary-600 dark:text-primary-400" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                      {product.product}
                    </h3>
                    <div className="flex flex-wrap gap-4 mt-2">
                      <div className="flex items-center gap-2">
                        <ScaleIcon className="h-5 w-5 text-gray-500 dark:text-white" />
                        <span className="text-sm text-gray-600 dark:text-white">
                          وزن کل:{" "}
                          <span className="font-medium">
                            {formatWeight(product.total_weight)}
                          </span>
                        </span>
                      </div>
                      <div className="flex items-center gap-2">
                        <CubeIcon className="h-5 w-5 text-gray-500 dark:text-white" />
                        <span className="text-sm text-gray-600 dark:text-white">
                          وزن باقیمانده:{" "}
                          <span className="font-medium">
                            {formatWeight(product.remaining_weight)}
                          </span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-6">
                  {product.free_sale > 0 && (
                    <div className="flex items-center gap-2 bg-yellow-50 dark:bg-yellow-900/30 px-4 py-2 rounded-lg">
                      <ShoppingBagIcon className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
                      <span className="text-yellow-700 dark:text-yellow-300 font-medium">
                        خرید مازاد: {formatWeight(product.free_sale)}
                      </span>
                    </div>
                  )}

                  {product.total_purchase > 0 && (
                    <div className="flex items-center gap-2 bg-purple-50 dark:bg-purple-900/30 px-4 py-2 rounded-lg">
                      <GiftIcon className="h-5 w-5 text-purple-600 dark:text-purple-400" />
                      <span className="text-purple-700 dark:text-purple-300 font-medium">
                        خرید کل: {formatWeight(product.total_purchase)}
                      </span>
                    </div>
                  )}

                  <div className="text-gray-500">
                    {expandedProducts[product.product_id] ? (
                      <ChevronDownIcon className="h-6 w-6" />
                    ) : (
                      <ChevronRightIcon className="h-6 w-6" />
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Product Details - Animated */}
            <AnimatePresence>
              {expandedProducts[product.product_id] && (
                <motion.div
                  initial={{ height: 0, opacity: 0 }}
                  animate={{ height: "auto", opacity: 1 }}
                  exit={{ height: 0, opacity: 0 }}
                  transition={{ duration: 0.3 }}
                  className="border-t border-gray-200 dark:border-gray-700"
                >
                  <div className="p-6">
                    <div className="space-y-4">
                      {product.items.map((item: any, itemIndex: number) => (
                        <motion.div
                          key={itemIndex}
                          initial={{ opacity: 0, scale: 0.95 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ delay: itemIndex * 0.05 }}
                          className="bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700"
                        >
                          <div
                            className="p-4 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors rounded-t-lg"
                            onClick={() =>
                              toggleItem(product.product_id, itemIndex)
                            }
                          >
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-3">
                                <TruckIcon className="h-5 w-5 text-gray-500 dark:text-white" />
                                <span className="font-medium text-gray-700 dark:text-white">
                                  سهمیه {item?.quota_id} :
                                </span>
                                <span className="text-sm text-gray-500 dark:text-white">
                                  وزن کل: {formatWeight(item.total_weight)}
                                </span>
                                <span className="text-sm text-gray-500 dark:text-white">
                                  باقیمانده:{" "}
                                  {formatWeight(item.remaining_weight)}
                                </span>
                              </div>
                              <div className="text-gray-500">
                                {expandedItems[
                                  `${product.product_id}-${itemIndex}`
                                ] ? (
                                  <ChevronDownIcon className="h-5 w-5" />
                                ) : (
                                  <ChevronRightIcon className="h-5 w-5" />
                                )}
                              </div>
                            </div>
                          </div>

                          <AnimatePresence>
                            {expandedItems[
                              `${product.product_id}-${itemIndex}`
                            ] && (
                              <motion.div
                                initial={{ height: 0, opacity: 0 }}
                                animate={{ height: "auto", opacity: 1 }}
                                exit={{ height: 0, opacity: 0 }}
                                transition={{ duration: 0.2 }}
                              >
                                <div className="p-4 border-t border-gray-200 dark:border-gray-700">
                                  <h5 className="text-sm font-medium text-gray-600 dark:text-white mb-3">
                                    سهمیه بر اساس نوع دام
                                  </h5>
                                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                    {item?.by_type?.length > 0 &&
                                      item?.by_type
                                        .filter(
                                          (animal: any) => animal.weight > 0
                                        )
                                        .map(
                                          (
                                            animal: any,
                                            animalIndex: number
                                          ) => (
                                            <motion.div
                                              key={animal.name}
                                              initial={{ opacity: 0, y: 10 }}
                                              animate={{ opacity: 1, y: 0 }}
                                              transition={{
                                                delay: animalIndex * 0.05,
                                              }}
                                              className="bg-white dark:bg-gray-800 rounded-lg p-3 border border-gray-200 dark:border-gray-700 shadow-sm"
                                            >
                                              <div className="flex justify-between items-start">
                                                <div>
                                                  <div className="flex items-center gap-2">
                                                    <span className="font-medium text-gray-900 dark:text-white">
                                                      {animal.name_fa}
                                                    </span>
                                                    <span
                                                      className={`text-xs px-2 py-1 rounded-full ${getAnimalTypeColor(
                                                        animal.type
                                                      )}`}
                                                    >
                                                      {getAnimalTypeText(
                                                        animal.type
                                                      )}
                                                    </span>
                                                  </div>
                                                  <p className="text-lg font-bold text-gray-800 dark:text-gray-200 mt-2">
                                                    {formatWeight(
                                                      animal.weight
                                                    )}
                                                  </p>
                                                </div>
                                              </div>
                                            </motion.div>
                                          )
                                        )}
                                  </div>
                                </div>
                              </motion.div>
                            )}
                          </AnimatePresence>
                        </motion.div>
                      ))}
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        ))}
      </div>

      {/* Empty State */}
      {products.length === 0 && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="text-center py-12"
        >
          <div className="max-w-md mx-auto">
            <div className="bg-gray-100 dark:bg-gray-800 w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4">
              <CubeIcon className="h-10 w-10 text-gray-400" />
            </div>
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
              اطلاعاتی یافت نشد
            </h3>
            <p className="text-gray-500 dark:text-white">
              هیچ محصولی برای این دامدار ثبت نشده است
            </p>
          </div>
        </motion.div>
      )}
    </div>
  );
};
