import { motion } from "framer-motion";
import {
  TagIcon,
  UserIcon,
  BuildingOfficeIcon,
  MapPinIcon,
  CubeIcon,
} from "@heroicons/react/24/outline";
import { useApiRequest } from "../../utils/useApiRequest";

interface TagDetailsProps {
  tagId: number;
}

export const TagDetails = ({ tagId }: TagDetailsProps) => {
  const { data: tagDetailData } = useApiRequest({
    api: `/tag/web/api/v1/tag/${tagId}/tag_detail/`,
    method: "get",
    queryKey: ["tagDetail", tagId],
  });

  if (!tagDetailData) {
    return (
      <div className="text-center p-8 text-gray-500 dark:text-gray-400">
        اطلاعاتی یافت نشد
      </div>
    );
  }

  const formatDate = (dateString: string) => {
    if (!dateString) return "-";
    const date = new Date(dateString);
    return date.toLocaleDateString("fa-IR");
  };

  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { text: string; color: string }> = {
      A: {
        text: "پلاک شده",
        color:
          "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",
      },
      F: {
        text: "آزاد",
        color: "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",
      },
      R: {
        text: "رزرو",
        color:
          "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",
      },
    };
    return (
      statusMap[status] || {
        text: "نامشخص",
        color: "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200",
      }
    );
  };

  const getGenderText = (gender: number) => {
    return gender === 1 ? "نر" : gender === 2 ? "ماده" : "نامشخص";
  };

  const getWeightTypeText = (weightType: string) => {
    return weightType === "H" ? "سنگین" : weightType === "L" ? "سبک" : "-";
  };

  const cardVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: (i: number) => ({
      opacity: 1,
      y: 0,
      transition: {
        delay: i * 0.1,
        duration: 0.5,
        ease: "easeOut",
      },
    }),
  };

  const InfoCard = ({
    title,
    icon: Icon,
    children,
    index,
  }: {
    title: string;
    icon: any;
    children: React.ReactNode;
    index: number;
  }) => (
    <motion.div
      custom={index}
      initial="hidden"
      animate="visible"
      variants={cardVariants}
      whileHover={{ scale: 1.01, y: -2 }}
      className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 border border-gray-200 dark:border-gray-700 hover:shadow-lg transition-all"
    >
      <div className="flex items-center gap-2 mb-3 pb-2 border-b border-gray-200 dark:border-gray-700">
        <div className="p-1.5 bg-primary-100 dark:bg-primary-900 rounded-md">
          <Icon className="w-4 h-4 text-primary-600 dark:text-primary-400" />
        </div>
        <h3 className="text-base font-semibold text-gray-900 dark:text-white">
          {title}
        </h3>
      </div>
      <div className="space-y-2">{children}</div>
    </motion.div>
  );

  const InfoRow = ({
    label,
    value,
  }: {
    label: string;
    value: string | number | React.ReactNode;
  }) => (
    <div className="flex justify-between items-start gap-2">
      <span className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
        {label}:
      </span>
      <span className="text-xs font-medium text-gray-900 dark:text-white text-left break-words">
        {value || "-"}
      </span>
    </div>
  );

  return (
    <div className="w-full rtl space-y-4 p-3">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="bg-gradient-to-r from-primary-600 to-primary-700 rounded-lg shadow-md p-3"
      >
        <div className="flex items-center justify-between gap-3">
          <div className="flex items-center gap-2.5 flex-1 min-w-0">
            <div className="bg-white/20 p-1.5 rounded-md flex-shrink-0">
              <TagIcon className="h-4 w-4 text-white" />
            </div>
            <div className="flex-1 min-w-0">
              <h1 className="text-sm font-semibold text-white truncate">
                جزئیات پلاک: {tagDetailData?.tag?.tag_code || "-"}
              </h1>
            </div>
          </div>
          <div className="flex-shrink-0">
            <span
              className={`inline-block px-2 py-1 rounded-md text-xs font-medium ${
                getStatusBadge(tagDetailData?.tag?.status).color
              }`}
            >
              {getStatusBadge(tagDetailData?.tag?.status).text}
            </span>
          </div>
        </div>
      </motion.div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <InfoCard title="اطلاعات پلاک" icon={TagIcon} index={0}>
          <InfoRow
            label="کد پلاک"
            value={tagDetailData?.tag?.tag_code || "-"}
          />
          <InfoRow
            label="کد کشور"
            value={tagDetailData?.tag?.country_code || "-"}
          />
          <InfoRow
            label="کد استاتیک"
            value={tagDetailData?.tag?.static_code || "-"}
          />
          <InfoRow
            label="کد مالکیت"
            value={tagDetailData?.tag?.ownership_code || "-"}
          />
          <InfoRow
            label="کد گونه"
            value={tagDetailData?.tag?.species_code || "-"}
          />
          <InfoRow label="سریال" value={tagDetailData?.tag?.serial || "-"} />
        </InfoCard>

        <InfoCard title="اطلاعات دام" icon={CubeIcon} index={1}>
          <InfoRow label="نوع" value={tagDetailData?.type?.name || "-"} />
          <InfoRow
            label="نوع وزن"
            value={getWeightTypeText(tagDetailData?.weight_type)}
          />
          <InfoRow
            label="تاریخ تولد"
            value={formatDate(tagDetailData?.birthdate)}
          />
          <InfoRow label="جنسیت" value={getGenderText(tagDetailData?.gender)} />
        </InfoCard>

        <InfoCard title="اطلاعات گله" icon={BuildingOfficeIcon} index={2}>
          <InfoRow label="نام" value={tagDetailData?.herd?.name || "-"} />
          <InfoRow label="کد" value={tagDetailData?.herd?.code || "-"} />
          <InfoRow
            label="کد اپیدمیولوژیک"
            value={tagDetailData?.herd?.epidemiologic || "-"}
          />
          <InfoRow label="کد پستی" value={tagDetailData?.herd?.postal || "-"} />
          <InfoRow
            label="کد واحد یکتا"
            value={tagDetailData?.herd?.unit_unique_id || "-"}
          />
          <InfoRow
            label="تعداد دام سنگین"
            value={
              tagDetailData?.herd?.heavy_livestock_number?.toLocaleString() || 0
            }
          />
          <InfoRow
            label="تعداد دام سبک"
            value={
              tagDetailData?.herd?.light_livestock_number?.toLocaleString() || 0
            }
          />
          <InfoRow
            label="سهمیه دام سنگین"
            value={
              tagDetailData?.herd?.heavy_livestock_quota?.toLocaleString() || 0
            }
          />
          <InfoRow
            label="سهمیه دام سبک"
            value={
              tagDetailData?.herd?.light_livestock_quota?.toLocaleString() || 0
            }
          />
          <InfoRow
            label="وضعیت فعالیت"
            value={tagDetailData?.herd?.activity_state ? "فعال" : "غیرفعال"}
          />
          <InfoRow
            label="وضعیت مجوز فعالیت"
            value={
              tagDetailData?.herd?.operating_license_state ? "دارد" : "ندارد"
            }
          />
          <InfoRow
            label="ظرفیت"
            value={tagDetailData?.herd?.capacity?.toLocaleString() || 0}
          />
        </InfoCard>

        <InfoCard title="اطلاعات دامدار" icon={UserIcon} index={3}>
          <InfoRow
            label="نام"
            value={
              `${tagDetailData?.herd?.rancher?.first_name || ""} ${
                tagDetailData?.herd?.rancher?.last_name || ""
              }`.trim() || "-"
            }
          />
          <InfoRow
            label="نام دامداری"
            value={tagDetailData?.herd?.rancher?.ranching_farm || "-"}
          />
          <InfoRow
            label="کد ملی"
            value={tagDetailData?.herd?.rancher?.national_code || "-"}
          />
          <InfoRow
            label="موبایل"
            value={tagDetailData?.herd?.rancher?.mobile || "-"}
          />
          <InfoRow
            label="آدرس"
            value={tagDetailData?.herd?.rancher?.address || "-"}
          />
        </InfoCard>

        <InfoCard title="موقعیت جغرافیایی" icon={MapPinIcon} index={4}>
          <InfoRow
            label="استان"
            value={
              tagDetailData?.herd?.province?.name ||
              tagDetailData?.herd?.rancher?.province?.name ||
              "-"
            }
          />
          <InfoRow
            label="شهر"
            value={
              tagDetailData?.herd?.city?.name ||
              tagDetailData?.herd?.rancher?.city?.name ||
              "-"
            }
          />
          <InfoRow
            label="عرض جغرافیایی"
            value={tagDetailData?.herd?.latitude || "-"}
          />
          <InfoRow
            label="طول جغرافیایی"
            value={tagDetailData?.herd?.longitude || "-"}
          />
        </InfoCard>
      </div>
    </div>
  );
};
