import React, { useState } from "react";
import { Grid } from "../components/Grid/Grid";
import Textfield from "../components/Textfeild/Textfeild";
import DatePicker from "../components/date-picker/DatePicker";
import { useApiMutation } from "../utils/useApiRequest";
import { motion, AnimatePresence, Variants } from "framer-motion";
import Typography from "../components/Typography/Typography";
import { useToast } from "../hooks/useToast";
import {
  CalendarIcon,
  IdentificationIcon,
  UserIcon,
  MapPinIcon,
  DocumentTextIcon,
} from "@heroicons/react/24/outline";
import Button from "../components/Button/Button";
import moment from "jalali-moment";

interface KalaItem {
  gOODHSCODE: number;
  gOODCODE: number;
  wEIGHT: number;
  pACKINGTYPECODE: number;
  gOODVALUE: number;
  iRANCODE: string;
  kALADESC: string;
}

interface LadingData {
  bARNAMEHID: number;
  bARNUMBER: number;
  bARSERIAL: string;
  iSSUDATE: string;
  sENDERNAME: string;
  sENDERLASTNAME: string;
  sENDERNATIONALCODE: string;
  sENDERPOSTALCODE: string;
  rCIEVERNAME: string;
  rECIEVERLASTNAME: string;
  rECIEVERNATIONALCODE: string;
  rECIEVERPOSTALCODE: string;
  fIRSTDRIVERCARDID: string;
  sECONDDRIVERCARDID: string;
  fRIGHTERCARDID: string;
  lANDERTYPEID: number;
  lANDERCODE: number;
  sTATUS: string;
  cOST: number;
  kOOTAJNO: number;
  kOOTAJDATE: string;
  cUSTOMCODE: string;
  tRANSITTYPEID: number;
  cREATEDATE: string;
  tRACECODE: string;
  kalaList: KalaItem[];
  introduceTraceCode: string | null;
  cmpDesc: string;
  originCityDesc: string;
  destCityDesc: string;
  pLAQUE_ID: string;
  pLAQUE_SN: string;
  firstDriverName: string;
  firstDriverFamily: string;
  secondDriverName: string;
  secondDriverFamily: string;
}

interface LadingResponse {
  status: boolean;
  statusCode: number;
  data: LadingData[];
  apiLogId: string;
}

const LadingInfo: React.FC = () => {
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [ladingData, setLadingData] = useState<LadingData[]>([]);
  const showToast = useToast();

  const ladingMutation = useApiMutation<LadingResponse>({
    api: "ladinginfo",
    method: "get",
  });

  const convertToPersianDate = (gregorianDate: string): string => {
    if (!gregorianDate) return "";
    const jDate = moment(gregorianDate, "YYYY-MM-DD").locale("fa");
    return jDate.format("jYYYY/jMM/jDD");
  };

  const handleSearch = async () => {
    if (!startDate || !endDate) {
      showToast("لطفا تاریخ شروع و پایان را وارد کنید", "error");
      return;
    }

    if (!postalCode) {
      showToast("لطفا کد پستی را وارد کنید", "error");
      return;
    }

    if (postalCode.length !== 10) {
      showToast("کد پستی باید 10 رقم باشد", "error");
      return;
    }

    try {
      const persianStartDate = convertToPersianDate(startDate);
      const persianEndDate = convertToPersianDate(endDate);

      const result = await ladingMutation.mutateAsync({
        start: persianStartDate,
        end: persianEndDate,
        postal: postalCode,
      });

      if (result?.status && result?.data && result.data.length > 0) {
        setLadingData(result.data);
      } else {
        setLadingData([]);
        showToast("نتیجه‌ای یافت نشد", "info");
      }
    } catch (error: any) {
      console.error("Lading info error:", error);
      showToast(
        error?.response?.data?.message || "خطا در دریافت اطلاعات بارنامه",
        "error"
      );
      setLadingData([]);
    }
  };

  const handlePostalCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    const numericValue = value.replace(/\D/g, "").slice(0, 10);
    setPostalCode(numericValue);
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleSearch();
    }
  };

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

  return (
    <Grid container column className="gap-4 p-4 max-w-6xl mx-auto">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, delay: 0.1 }}
        className="w-full"
      >
        <Grid
          container
          column
          className="gap-4 p-6 bg-white dark:bg-dark-800 rounded-xl shadow-lg border border-gray-200 dark:border-dark-600"
        >
          <Typography
            variant="h5"
            className="text-gray-900 dark:text-gray-100 font-bold mb-2"
          >
            دریافت اطلاعات بارنامه
          </Typography>

          <Grid container className="gap-4 items-end">
            <Grid container className="flex-1" column>
              <DatePicker
                label="تاریخ شروع"
                value={startDate}
                onChange={setStartDate}
                fullWidth
              />
            </Grid>
            <Grid container className="flex-1" column>
              <DatePicker
                label="تاریخ پایان"
                value={endDate}
                onChange={setEndDate}
                fullWidth
              />
            </Grid>
            <Grid container className="flex-1" column>
              <Textfield
                placeholder="کد پستی"
                value={postalCode}
                onChange={handlePostalCodeChange}
                onKeyPress={handleKeyPress}
                fullWidth
              />
            </Grid>
            <Button
              onClick={handleSearch}
              disabled={ladingMutation.isPending}
              className="px-6 py-2.5"
            >
              {ladingMutation.isPending ? "در حال جستجو..." : "جستجو"}
            </Button>
          </Grid>
        </Grid>
      </motion.div>

      <AnimatePresence mode="popLayout">
        {ladingData.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="w-full"
          >
            <Typography
              variant="body1"
              className="mb-4 text-gray-700 dark:text-gray-300 font-semibold"
            >
              نتایج جستجو ({ladingData.length})
            </Typography>

            <Grid container column className="gap-6">
              {ladingData.map((lading, index) => (
                <motion.div
                  key={lading.bARNAMEHID}
                  custom={index}
                  variants={cardVariants}
                  initial="hidden"
                  animate="visible"
                  exit="exit"
                  className="w-full"
                >
                  <div className="bg-white dark:bg-dark-800 rounded-xl shadow-lg border border-gray-200 dark:border-dark-600 p-6 hover:shadow-xl transition-shadow">
                    <Grid container column className="gap-4">
                      <div className="flex items-start justify-between pb-4 border-b border-gray-200 dark:border-dark-600">
                        <div className="flex items-center gap-3">
                          <div className="p-3 bg-primary-100 dark:bg-primary-900/30 rounded-lg">
                            <DocumentTextIcon className="w-6 h-6 text-primary-600 dark:text-primary-400" />
                          </div>
                          <div>
                            <Typography
                              variant="h6"
                              className="text-gray-900 dark:text-gray-100 font-bold"
                            >
                              بارنامه ردیف {index + 1}
                            </Typography>
                          </div>
                        </div>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <CalendarIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              تاریخ صدور
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.iSSUDATE}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <DocumentTextIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              شماره بارنامه
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.bARNUMBER}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <MapPinIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              شهر مبدا
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.originCityDesc}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <MapPinIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              شهر مقصد
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.destCityDesc}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <UserIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              نام فرستنده
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.sENDERNAME} {lading.sENDERLASTNAME}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <UserIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              نام گیرنده
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.rCIEVERNAME} {lading.rECIEVERLASTNAME}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <IdentificationIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              کدرهگیری
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium break-all"
                            >
                              {lading.tRACECODE}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <IdentificationIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              شماره پلاک
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.pLAQUE_ID}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <IdentificationIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              سریال پلاک
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.pLAQUE_SN}
                            </Typography>
                          </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-dark-700 rounded-lg">
                          <UserIcon className="w-5 h-5 text-gray-600 dark:text-gray-400 shrink-0" />
                          <div>
                            <Typography
                              variant="body2"
                              className="text-gray-500 dark:text-gray-400 text-xs"
                            >
                              نام راننده
                            </Typography>
                            <Typography
                              variant="body1"
                              className="text-gray-900 dark:text-gray-100 font-medium"
                            >
                              {lading.firstDriverName}{" "}
                              {lading.firstDriverFamily}
                            </Typography>
                          </div>
                        </div>
                      </div>

                      {lading.kalaList && lading.kalaList.length > 0 && (
                        <div className="pt-2">
                          <div className="flex items-center gap-2 mb-3">
                            <DocumentTextIcon className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                            <Typography
                              variant="body2"
                              className="text-gray-700 dark:text-gray-300 font-semibold"
                            >
                              لیست کالا
                            </Typography>
                          </div>
                          <div className="overflow-x-auto">
                            <table className="w-full border-collapse">
                              <thead>
                                <tr className="bg-gray-100 dark:bg-dark-700">
                                  <th className="border border-gray-300 dark:border-dark-600 px-4 py-2 text-center text-sm font-semibold text-gray-700 dark:text-gray-300">
                                    ردیف
                                  </th>
                                  <th className="border border-gray-300 dark:border-dark-600 px-4 py-2 text-center text-sm font-semibold text-gray-700 dark:text-gray-300">
                                    نام کالا
                                  </th>
                                  <th className="border border-gray-300 dark:border-dark-600 px-4 py-2 text-center text-sm font-semibold text-gray-700 dark:text-gray-300">
                                    وزن
                                  </th>
                                </tr>
                              </thead>
                              <tbody>
                                {lading.kalaList.map((kala, idx) => (
                                  <tr
                                    key={idx}
                                    className="hover:bg-gray-50 dark:hover:bg-dark-700"
                                  >
                                    <td className="border border-gray-300 dark:border-dark-600 px-4 py-2 text-sm text-gray-900 dark:text-gray-100 text-center">
                                      {idx + 1}
                                    </td>
                                    <td className="border border-gray-300 dark:border-dark-600 px-4 py-2 text-sm text-gray-900 dark:text-gray-100 text-center">
                                      {kala.kALADESC}
                                    </td>
                                    <td className="border border-gray-300 dark:border-dark-600 px-4 py-2 text-sm text-gray-900 dark:text-gray-100 text-center">
                                      {kala.wEIGHT.toLocaleString()}
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      )}
                    </Grid>
                  </div>
                </motion.div>
              ))}
            </Grid>
          </motion.div>
        )}
      </AnimatePresence>
    </Grid>
  );
};

export default LadingInfo;
