import React from "react";
import { Grid } from "../../components/Grid/Grid";
import Typography from "../../components/Typography/Typography";
import { ShowWeight } from "../../components/ShowWeight/ShowWeight";
import ShowStringList from "../../components/ShowStringList/ShowStringList";
import Divider from "../../components/Divider/Divider";
import { formatJustDate } from "../../utils/formatTime";
import { getPersianMonths } from "../../utils/getPersianMonths";

interface QuotaViewProps {
  item: any;
}

export const QuotaView: React.FC<QuotaViewProps> = ({ item }) => {
  const InfoCard = ({
    title,
    children,
    className = "",
  }: {
    title: string;
    children: React.ReactNode;
    className?: string;
  }) => (
    <div
      className={`bg-gradient-to-br from-white to-gray-50 dark:from-dark-800 dark:to-dark-900 rounded-xl p-4 border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-md transition-shadow duration-200 ${className}`}
    >
      <Typography
        variant="body2"
        fontWeight="semibold"
        className="text-primary-700 dark:text-primary-300 mb-3 pb-2 border-b border-primary-200 dark:border-primary-800"
      >
        {title}
      </Typography>
      {children}
    </div>
  );

  const InfoRow = ({
    label,
    value,
  }: {
    label: string;
    value: React.ReactNode;
  }) => (
    <div className="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700 last:border-0">
      <Typography variant="body2" className="text-gray-600 dark:text-gray-400">
        {label}:
      </Typography>
      <Typography
        variant="body2"
        fontWeight="medium"
        className="text-gray-900 dark:text-gray-100 text-left"
      >
        {value}
      </Typography>
    </div>
  );

  return (
    <div className="w-full p-4 space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <InfoCard title="اطلاعات پایه">
          <div className="space-y-2">
            <InfoRow label="شناسه سهمیه" value={item?.quota_id} />
            <InfoRow label="محصول" value={item?.product?.product || "-"} />
            <InfoRow label="ایجاد کننده" value={item?.creator_info || "-"} />
            <InfoRow
              label="تاریخ ثبت"
              value={formatJustDate(item?.create_date) || "-"}
            />
            {item?.closed_at && (
              <InfoRow
                label="تاریخ بایگانی"
                value={formatJustDate(item?.closed_at)}
              />
            )}
          </div>
        </InfoCard>

        <InfoCard title="وزن و واحد">
          <div className="space-y-2">
            <div className="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
              <Typography
                variant="body2"
                className="text-gray-600 dark:text-gray-400"
              >
                وزن محصول:
              </Typography>
              <ShowWeight
                weight={item?.quota_weight}
                type={item?.sale_unit?.unit}
              />
            </div>
            <div className="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
              <Typography
                variant="body2"
                className="text-gray-600 dark:text-gray-400"
              >
                وزن توزیع شده:
              </Typography>
              <ShowWeight
                weight={item?.quota_distributed}
                type={item?.sale_unit?.unit}
              />
            </div>

            <div className="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
              <Typography
                variant="body2"
                className="text-gray-600 dark:text-gray-400"
              >
                وزن باقیمانده:
              </Typography>
              <ShowWeight
                weight={item?.remaining_weight}
                type={item?.sale_unit?.unit}
              />
            </div>
          </div>
        </InfoCard>

        <InfoCard title="گروه و نوع فروش">
          <div className="space-y-2">
            <InfoRow
              label="گروه"
              value={
                item?.group
                  ?.map((group: any) =>
                    group === "rural"
                      ? "روستایی"
                      : group === "industrial"
                        ? "صنعتی"
                        : "عشایری",
                  )
                  .join(", ") || "-"
              }
            />
            <InfoRow
              label="نوع فروش"
              value={item?.sale_type === "gov" ? "دولتی" : "آزاد"}
            />
            <InfoRow
              label="نوع فروش در دستگاه"
              value={
                item?.pos_sale_type === "all"
                  ? "بر اساس تعداد راس دام و وزن"
                  : item?.pos_sale_type === "weight"
                    ? "بر اساس وزن"
                    : item?.pos_sale_type === "count"
                      ? "بر اساس تعداد راس دام"
                      : "-"
              }
            />
          </div>
        </InfoCard>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <InfoCard title="سهمیه و مجوز" className="w-full">
          <Grid container column className="gap-3">
            <div>
              <Typography
                variant="body2"
                sign="info"
                className="mb-2 font-semibold"
              >
                سهمیه ماه
              </Typography>
              <ShowStringList
                strings={getPersianMonths(item?.month_choices)}
                showSearch={false}
              />
            </div>
            <Divider />
            <div>
              <Typography
                variant="body2"
                sign="info"
                className="mb-2 font-semibold"
              >
                مجوز فروش
              </Typography>
              <ShowStringList
                strings={getPersianMonths(item?.sale_license)}
                showSearch={false}
              />
            </div>
          </Grid>
        </InfoCard>

        <InfoCard title="سهمیه بندی دام" className="w-full">
          {item?.livestock_allocations?.length > 0 ? (
            <div className="space-y-6">
              {(
                Object.entries(
                  item?.livestock_allocations?.reduce(
                    (acc: Record<string, any[]>, allocation: any) => {
                      const group = allocation?.livestock_group || "other";
                      if (!acc[group]) {
                        acc[group] = [];
                      }
                      acc[group].push(allocation);
                      return acc;
                    },
                    {} as Record<string, any[]>,
                  ),
                ) as [string, any[]][]
              ).map(([group, allocations]) => (
                <div key={group} className="space-y-2">
                  <Typography
                    variant="body1"
                    fontWeight="semibold"
                    className="text-primary-700 dark:text-primary-300 pb-2 border-b border-primary-200 dark:border-primary-800"
                  >
                    {group === "rural"
                      ? "روستایی"
                      : group === "industrial"
                        ? "صنعتی"
                        : "سایر"}
                  </Typography>
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                      <thead className="bg-primary-50 dark:bg-dark-900">
                        <tr>
                          <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300 uppercase">
                            نوع دام
                          </th>
                          <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300 uppercase">
                            وزن
                          </th>
                          <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300 uppercase">
                            دسته
                          </th>
                        </tr>
                      </thead>
                      <tbody className="bg-white dark:bg-dark-800 divide-y divide-gray-200 dark:divide-gray-700">
                        {allocations.map((allocation: any, idx: number) => (
                          <tr
                            key={idx}
                            className="hover:bg-gray-50 dark:hover:bg-dark-700"
                          >
                            <td className="px-4 py-2 text-sm text-gray-900 dark:text-gray-100">
                              {allocation?.livestock_type?.name || "-"}
                            </td>
                            <td className="px-4 py-2 text-sm text-gray-900 dark:text-gray-100">
                              {allocation?.quantity_kg?.toLocaleString()}
                            </td>
                            <td className="px-4 py-2 text-sm text-gray-900 dark:text-gray-100">
                              {allocation?.livestock_type?.weight_type === "L"
                                ? "سبک"
                                : "سنگین"}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <Typography
              variant="body2"
              className="text-gray-500 dark:text-gray-400"
            >
              اطلاعاتی موجود نیست
            </Typography>
          )}
        </InfoCard>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <InfoCard title="محدودیت ها" className="w-full">
          <Grid container column className="gap-3">
            <div>
              <Typography
                variant="body1"
                sign="info"
                color="text-red-500 dark:text-red-200"
                className="mb-2"
              >
                محدودیت بر اساس تعداد راس دام:{" "}
                {item?.limit_by_herd_size ? "دارد" : "ندارد"}
              </Typography>
            </div>
            <Divider />
            <div>
              <Typography variant="body1" sign="info" className="mb-2">
                فروش مازاد به توزیع سهمیه: {item?.free_sale ? "دارد" : "ندارد"}
              </Typography>
            </div>
            <Divider />
            <div>
              <Typography variant="body1" sign="info" className="mb-2">
                پیش فروش به توزیع سهمیه: {item?.pre_sale ? "دارد" : "ندارد"}
              </Typography>
            </div>
            <Divider />
            <div>
              <Typography variant="body1" sign="info" className="mb-2">
                محدودیت یکبار خرید از سهیمه:{" "}
                {item?.one_time_purchase_limit ? "دارد" : "ندارد"}
              </Typography>
            </div>
            <Divider />
            <div>
              <Typography
                variant="body2"
                sign="info"
                className="mb-2 font-semibold"
              >
                محدودیت بر اساس شهرستان و تعاونی
              </Typography>
              {item?.limit_by_organizations?.length > 0 ? (
                <ShowStringList
                  showSearch={false}
                  strings={item?.limit_by_organizations?.map(
                    (opt: { name: string }) => opt?.name,
                  )}
                />
              ) : (
                <Typography
                  variant="body2"
                  className="text-gray-500 dark:text-gray-400"
                >
                  محدودیتی وجود ندارد
                </Typography>
              )}
            </div>
            <Divider />
            <div>
              <Typography
                variant="body2"
                sign="info"
                className="mb-2 font-semibold"
              >
                محدودیت بر اساس بازه سنی دام
              </Typography>
              {item?.livestock_limitations?.length > 0 ? (
                <ShowStringList
                  showSearch={false}
                  strings={item?.livestock_limitations?.map(
                    (opt: {
                      age_month: string;
                      livestock_type: { name: string; weight_type: string };
                    }) =>
                      `${opt?.livestock_type?.name} (${
                        opt?.livestock_type?.weight_type === "L"
                          ? "سبک"
                          : "سنگین"
                      }) با سن ${opt?.age_month}`,
                  )}
                />
              ) : (
                <Typography
                  variant="body2"
                  className="text-gray-500 dark:text-gray-400"
                >
                  محدودیتی وجود ندارد
                </Typography>
              )}
            </div>
            <Divider />
            <div>
              <Typography
                variant="body2"
                sign="info"
                className="mb-2 font-semibold"
              >
                محدودیت توزیع دوره
              </Typography>
              {item?.distribution_mode?.length > 0 ? (
                <ShowStringList
                  showSearch={false}
                  strings={getPersianMonths(item?.distribution_mode)}
                />
              ) : (
                <Typography
                  variant="body2"
                  className="text-gray-500 dark:text-gray-400"
                >
                  محدودیتی وجود ندارد
                </Typography>
              )}
            </div>
          </Grid>
        </InfoCard>

        <InfoCard title="طرح های تشویقی" className="w-full">
          {item?.incentive_plan?.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[400px] overflow-y-auto">
              {item?.incentive_plan?.map((itm: any, idx: number) => (
                <div
                  key={idx}
                  className="bg-gradient-to-br from-primary-50/50 to-primary-100/30 dark:from-dark-900 dark:to-dark-800 rounded-lg p-3 border border-primary-200/50 dark:border-dark-700 shadow-sm hover:shadow-md transition-all duration-200"
                >
                  <div className="flex items-center gap-2 mb-2">
                    <div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary-500 text-white font-semibold text-xs shadow-sm">
                      {idx + 1}
                    </div>
                    <Typography
                      variant="body1"
                      fontWeight="semibold"
                      className="text-primary-900 dark:text-primary-100"
                    >
                      {itm?.name}
                    </Typography>
                  </div>
                  {itm?.live_stocks?.length > 0 && (
                    <div className="space-y-1 pr-2">
                      {itm?.live_stocks?.map(
                        (liveStock: any, inidx: number) => (
                          <div
                            key={inidx}
                            className="flex items-center justify-between bg-white/60 dark:bg-dark-700/50 rounded-md px-2 py-1 border border-primary-100 dark:border-dark-600"
                          >
                            <Typography
                              variant="caption"
                              className="text-gray-700 dark:text-gray-200 font-medium"
                            >
                              {liveStock?.name}
                            </Typography>
                            <div className="flex items-center gap-1 px-1.5 py-0.5 rounded-full bg-primary-500/10 dark:bg-primary-500/20 border border-primary-300/30 dark:border-primary-500/30">
                              <Typography
                                variant="caption"
                                fontWeight="semibold"
                                className="text-primary-700 dark:text-primary-300"
                              >
                                {liveStock?.quantity?.toLocaleString()}
                              </Typography>
                            </div>
                          </div>
                        ),
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <Typography
              variant="body2"
              className="text-gray-500 dark:text-gray-400"
            >
              طرح تشویقی ثبت نشده است
            </Typography>
          )}
        </InfoCard>
      </div>

      <InfoCard title="قیمت گذاری" className="w-full">
        {item?.price_calculation_items?.length > 0 ? (
          <div className="space-y-3">
            {Object.values(
              (item?.price_calculation_items || []).reduce(
                (
                  acc: Record<string, any>,
                  itm: {
                    pricing_type: number;
                    pricing_type_name: string;
                    name: string;
                    value: number;
                  },
                ) => {
                  const key = itm.pricing_type_name;
                  if (acc[key]) {
                    acc[key].value += itm.value;
                  } else {
                    acc[key] = { ...itm };
                  }
                  return acc;
                },
                {} as Record<string, any>,
              ),
            ).map((priceItem: any, priceIndex: number) => (
              <div
                key={priceIndex}
                className="flex justify-between items-center py-2 px-3 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800"
              >
                <Typography
                  variant="body2"
                  fontWeight="medium"
                  className="text-gray-700 dark:text-gray-300"
                >
                  {priceItem?.pricing_type_name}
                </Typography>
                <Typography
                  variant="body2"
                  fontWeight="semibold"
                  color="text-red-600 dark:text-red-300"
                >
                  {priceItem?.value?.toLocaleString()}
                </Typography>
              </div>
            ))}
            <Divider />
            <div className="mt-2 space-y-4">
              {(
                Object.entries(
                  (item?.price_calculation_items || []).reduce(
                    (acc: Record<string, any[]>, itm: any) => {
                      const key = itm.pricing_type_name || "سایر";
                      if (!acc[key]) {
                        acc[key] = [];
                      }
                      acc[key].push(itm);
                      return acc;
                    },
                    {} as Record<string, any[]>,
                  ),
                ) as [string, any[]][]
              ).map(([pricingTypeName, items]) => (
                <div key={pricingTypeName} className="space-y-2">
                  <Typography
                    variant="body2"
                    fontWeight="semibold"
                    className="text-primary-700 dark:text-primary-300 pb-2 border-b border-primary-200 dark:border-primary-800"
                  >
                    {pricingTypeName}
                  </Typography>
                  <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead className="bg-primary-50 dark:bg-dark-900">
                      <tr>
                        <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300 uppercase">
                          مولفه
                        </th>
                        <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300 uppercase">
                          قیمت
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-white dark:bg-dark-800 divide-y divide-gray-200 dark:divide-gray-700">
                      {items.map((priceItem: any, idx: number) => (
                        <tr
                          key={idx}
                          className="hover:bg-gray-50 dark:hover:bg-dark-700"
                        >
                          <td className="px-4 py-2 text-sm text-gray-900 dark:text-gray-100">
                            {priceItem?.name}
                          </td>
                          <td className="px-4 py-2 text-sm text-gray-900 dark:text-gray-100">
                            {priceItem?.value?.toLocaleString()}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <Typography
            variant="body2"
            className="text-gray-500 dark:text-gray-400"
          >
            اطلاعات قیمت گذاری موجود نیست
          </Typography>
        )}
      </InfoCard>
    </div>
  );
};
