import React, { useState } from "react";
import { Box, Typography, Tab, Tabs, IconButton, Divider } from "@mui/material";
import { Grid } from "../grid/Grid";
import { SPACING } from "../../data/spacing";
import { LabelField } from "../label-field/LabelField";
import CloseIcon from "@mui/icons-material/Close";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import axios from "axios";

export const InspectionDetailsModal = ({ item }) => {
  const [statusTab, setStatusTab] = useState(0);
  const [fullscreenMedia, setFullscreenMedia] = useState(null);

  const handleStatusTabChange = (newValue) => {
    setStatusTab(newValue);
  };

  const handleOpenFullscreen = (mediaUrl) => {
    setFullscreenMedia(mediaUrl);
  };

  const handleCloseFullscreen = () => {
    setFullscreenMedia(null);
  };

  const handleDownloadPdf = () => {
    const baseUrl = axios.defaults.baseURL || "";
    const url = `${baseUrl}poultry_science_report_pdf/?key=${item?.key}`;
    window.open(url, "_blank");
  };

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

  const formatDateTime = (dateString) => {
    if (!dateString) return "---";
    try {
      const date = new Date(dateString);
      return `${date.toLocaleDateString("fa-IR")} (${date.toLocaleTimeString(
        "fa-IR",
        { hour: "2-digit", minute: "2-digit" }
      )})`;
    } catch {
      return dateString;
    }
  };

  const poultry = item?.hatching?.poultry || {};
  const hatching = item?.hatching || {};
  const reportInfo = item?.reportInformation || {};

  const informationData = {
    "نام واحد مرغداری": poultry?.unitName || "---",
    "کد یکتا / شناسه واحد": poultry?.breedingUniqueId || "---",
    "پروانه بهداشتی": poultry?.healthCertificateNumber || "---",
    "مجوز جوجه ریزی": hatching?.licenceNumber || "---",
    "کد اپیدمیولوژیک": poultry?.epidemiologicalCode || "---",
    "اعتبار پروانه بهره برداری": poultry?.operatingLicenceCapacity
      ? `${poultry.operatingLicenceCapacity}`
      : "---",
    "وضعیت مستاجر": hatching?.hasTenant
      ? hatching?.InteractTypeName || "دارد"
      : "ندارد",
    "نام مالک / بهره بردار": poultry?.user?.fullname || "---",
    "نوع مالکیت": hatching?.InteractTypeName || "---",
    "کد ملی بهره بردار":
      poultry?.user?.nationalId || poultry?.user?.nationalCode || "---",
    استان: poultry?.address?.province?.name || poultry?.provinceName || "---",
    شهر: poultry?.address?.city?.name || poultry?.cityName || "---",
    "مختصات جغرافیایی":
      poultry?.Lat && poultry?.Long
        ? `${poultry.Lat}, ${poultry.Long}`
        : item?.lat && item?.log
        ? `${item.lat}, ${item.log}`
        : "---",
    "شماره تماس بهره بردار": poultry?.user?.mobile || "---",
    "ظرفیت اسمی واحدها": poultry?.totalCapacity
      ? `${poultry.totalCapacity.toLocaleString()}`
      : "---",

    "تاریخ جوجه ریزی": formatDateTime(hatching?.date),
    "تاریخ بازدید": formatDateTime(item?.date),
    "تعداد جوجه ریزی اولیه": hatching?.quantity
      ? `${hatching.quantity.toLocaleString()}`
      : "---",
    "تعداد جوجه ریزی توسط دامپزشکی": hatching?.quantity
      ? `${hatching.quantity.toLocaleString()}`
      : "---",
    "تعداد جوجه طبق خود اظهاری مرغدار": hatching?.quantity
      ? `${hatching.quantity.toLocaleString()}`
      : "---",
    "منبع تهیه جوجه": reportInfo?.casualties?.sourceOfHatching || "---",
    "سن جوجه در زمان بازدید": hatching?.chickenAge
      ? `${hatching.chickenAge} روز`
      : hatching?.nowAge
      ? `${hatching.nowAge} روز`
      : "---",
    "نوع نژاد": hatching?.chickenBreed || "---",
  };

  const generalCondition = reportInfo?.generalConditionHall || {};
  const casualties = reportInfo?.casualties || {};
  const technicalOfficer = reportInfo?.technicalOfficer || {};

  const healthMonitoringData = {
    "وضعیت بهداشتی سالن": generalCondition?.healthStatus || "---",
    "وضعیت تهویه": generalCondition?.ventilationStatus || "---",
    "وضعیت بستر": generalCondition?.bedCondition || "---",
    "دما و رطوبت سالن با توجه به سن جوجه": generalCondition?.temperature
      ? `${generalCondition.temperature} درجه`
      : "---",
    "کیفیت آب مصرفی": generalCondition?.drinkingWaterQuality || "---",
    "منبع آب مصرفی": generalCondition?.drinkingWaterSource || "---",
    "تعداد تلفات عادی دوره": casualties?.normalLosses
      ? `${casualties.normalLosses}`
      : "---",
    "تلفات غیر عادی": casualties?.abnormalLosses
      ? `${casualties.abnormalLosses}`
      : "---",
    "علت تلفات غیر عادی": casualties?.causeAbnormalLosses || "---",
    "نوع بیماری تشخیصی": casualties?.typeDisease || "---",
    "نمونه برداری انجام شده": casualties?.samplingDone ? "بله" : "خیر",
    "نوع نمونه": casualties?.typeSampling || "---",
    "نام مسئول فنی بهداشتی": technicalOfficer?.technicalHealthOfficer || "---",
    "نام مسئول فنی نظام مهندسی":
      technicalOfficer?.technicalEngineeringOfficer || "---",
  };

  const inputStatus = reportInfo?.inputStatus || {};
  const infrastructureEnergy = reportInfo?.infrastructureEnergy || {};
  const facilities = reportInfo?.facilities || {};
  const hr = reportInfo?.hr || {};

  const infrastructureData = {
    "وضعیت نهاده": inputStatus?.inputStatus || "---",
    "نوع دان": inputStatus?.typeOfGrain || "---",
    "کیفیت دانه": inputStatus?.gradeGrain || "---",
    "موجودی تا روز بازدید": inputStatus?.inventoryUntilVisit || "---",
    "موجودی در انبار": inputStatus?.inventoryInWarehouse || "---",
    "کد رهگیری": inputStatus?.trackingCode || "---",
    "نام شرکت": inputStatus?.companyName || "---",
    "نوع ژنراتور": infrastructureEnergy?.generatorType || "---",
    "مدل ژنراتور": infrastructureEnergy?.generatorModel || "---",
    "تعداد ژنراتور": infrastructureEnergy?.generatorCount || "---",
    "نوع سوخت": infrastructureEnergy?.fuelType || "---",
    "ظرفیت ژنراتور": infrastructureEnergy?.generatorCapacity
      ? `${infrastructureEnergy.generatorCapacity.toLocaleString()}`
      : "---",
    "میزان موجودی سوخت اضطراری (لیتر)":
      infrastructureEnergy?.emergencyFuelInventory
        ? `${infrastructureEnergy.emergencyFuelInventory.toLocaleString()}`
        : "---",
    "سابقه قطعی برق دوره جاری": infrastructureEnergy?.hasPowerCutHistory
      ? "بله"
      : "خیر",
    "مدت زمان قطعی": infrastructureEnergy?.powerCutDuration
      ? `${infrastructureEnergy.powerCutDuration} ساعت`
      : "---",
    "ساعت قطعی": infrastructureEnergy?.powerCutHour || "---",
    "عملکرد ژنراتور": infrastructureEnergy?.generatorPerformance || "---",
    "توضیحات تکمیلی": infrastructureEnergy?.additionalNotes || "---",
    "تعداد افراد شاغل": hr?.numberEmployed ? `${hr.numberEmployed}` : "---",
    "تعداد افراد بومی": hr?.numberIndigenous ? `${hr.numberIndigenous}` : "---",
    "تعداد افراد غیر بومی": hr?.numberNonIndigenous
      ? `${hr.numberNonIndigenous}`
      : "---",
    "وضعیت قرارداد کارگران": hr?.contractStatus || "---",
    "آموزش دیده در حوزه بهداشت و امنیت زیستی": hr?.trained ? "بله" : "خیر",
    "تسهیلات دریافتی فعال": facilities?.hasFacilities ? "بله" : "خیر",
    "نوع تسهیلات": facilities?.typeOfFacility || "---",
    "مبلغ تسهیلات": facilities?.amount
      ? `${facilities.amount.toLocaleString()}`
      : "---",
    "وضعیت بازپرداخت": facilities?.repaymentStatus || "---",
    "درخواست جدید بهره بردار": facilities?.requestFacilities || "---",
    "تاریخ تسهیلات": formatDate(facilities?.date),
  };

  const renderInformationTab = () => (
    <Grid
      container
      item
      sx={{
        width: "100%",
        display: "flex",
        flexWrap: "wrap",
      }}
      xs={12}
    >
      {Object.entries(informationData).map(([label, value]) => (
        <Grid key={label} xs={2.4} lg={3} nxl={2.4} p={1}>
          <LabelField label={label}>
            <Typography variant="body2" sx={{ py: 1 }}>
              {value || "---"}
            </Typography>
          </LabelField>
        </Grid>
      ))}
    </Grid>
  );

  const renderHealthMonitoringTab = () => (
    <Grid
      container
      item
      sx={{
        width: "100%",
        display: "flex",
        flexWrap: "wrap",
      }}
      xs={12}
    >
      {Object.entries(healthMonitoringData).map(([label, value]) => (
        <Grid key={label} xs={2.4} lg={3} nxl={2.4} p={1}>
          <LabelField label={label}>
            <Typography variant="body2" sx={{ py: 1 }}>
              {value || "---"}
            </Typography>
          </LabelField>
        </Grid>
      ))}
    </Grid>
  );

  const renderInfrastructureTab = () => (
    <Grid
      container
      item
      sx={{
        width: "100%",
        display: "flex",
        flexWrap: "wrap",
      }}
      xs={12}
    >
      {Object.entries(infrastructureData).map(([label, value]) => (
        <Grid key={label} xs={4} p={1}>
          <LabelField label={label}>
            <Typography variant="body2" sx={{ py: 1 }}>
              {value || "---"}
            </Typography>
          </LabelField>
        </Grid>
      ))}
    </Grid>
  );

  const ImageThumbnail = ({ src, onClick }) => {
    const isVideo = src?.toLowerCase().match(/\.(mp4|webm|ogg|mov)$/i);

    return (
      <Box
        onClick={() => onClick && onClick(src)}
        sx={{
          position: "relative",
          width: "70px",
          height: "70px",
          borderRadius: 1.5,
          overflow: "hidden",
          border: "1px solid #e0e0e0",
          cursor: "pointer",
          "&:hover": {
            opacity: 0.8,
          },
        }}
      >
        {isVideo ? (
          <Box
            component="video"
            src={src}
            sx={{
              width: "100%",
              height: "100%",
              objectFit: "cover",
            }}
          />
        ) : (
          <Box
            component="img"
            src={src}
            alt="thumbnail"
            sx={{
              width: "100%",
              height: "100%",
              objectFit: "cover",
            }}
          />
        )}
      </Box>
    );
  };

  const ImageGallerySection = ({ title, description, images = [] }) => (
    <Grid container direction="column" gap={1} sx={{ mb: 2 }}>
      <Typography variant="h6" sx={{ fontWeight: "bold", fontSize: 18 }}>
        {title}
      </Typography>
      {description && (
        <Typography variant="body2" sx={{ mb: 1, color: "text.secondary" }}>
          {description}
        </Typography>
      )}
      {images && images.length > 0 ? (
        <Grid container gap={SPACING.SMALL}>
          {images.map((imageUrl, index) => (
            <ImageThumbnail
              key={index}
              src={imageUrl}
              onClick={handleOpenFullscreen}
            />
          ))}
        </Grid>
      ) : (
        <Typography
          variant="body2"
          sx={{ color: "text.secondary", fontStyle: "italic" }}
        >
          تصویری موجود نیست
        </Typography>
      )}
    </Grid>
  );

  const renderDocumentsTab = () => {
    const generalConditionImages = generalCondition?.images || [];
    const inputStatusImages = inputStatus?.images || [];
    const casualtiesImages = casualties?.images || [];
    const violationImages = hatching?.violationImage || [];

    return (
      <Grid direction="column" xs={12}>
        <ImageGallerySection
          title="وضعیت کلی سالن"
          images={generalConditionImages}
        />

        <ImageGallerySection
          title="انبار نهاده ها"
          images={inputStatusImages}
        />

        <ImageGallerySection title="تلفات" images={casualtiesImages} />

        <ImageGallerySection title="تصاویر تخلف" images={violationImages} />

        <Box sx={{ mb: 3 }}>
          <Tabs
            value={statusTab}
            onChange={(event, newValue) => handleStatusTabChange(newValue)}
            sx={{
              "& .MuiTabs-indicator": {
                display: "none",
              },
              "& .MuiTab-root": {
                minHeight: "auto",
                px: 3,
                py: 1,
                borderRadius: 2,
                fontWeight: "bold",
                textTransform: "none",
                "&.Mui-selected": {
                  bgcolor: "#4caf50",
                  color: "white",
                },
                "&:not(.Mui-selected)": {
                  bgcolor: "#f5f5f5",
                  color: "text.primary",
                },
              },
            }}
          >
            <Tab label="وضعیت کلی واحد" />
            <Tab label={reportInfo?.inspectionStatus || "---"} />
          </Tabs>
        </Box>
        <LabelField label="توصیه ها / اخطارها / اقدامات اصلاحی :">
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: 13, py: 1 }}
          >
            {reportInfo?.inspectionNotes || "---"}
          </Typography>
        </LabelField>
        <Divider sx={{ my: 2, visibility: "hidden" }} />

        <Typography
          variant="h6"
          sx={{ fontWeight: "bold", fontSize: 16, mb: 2 }}
        >
          احراز مسئول سالن
        </Typography>
        <Grid container xs={12}>
          <Grid xs={12} lg={3} p={1}>
            <LabelField label="مسئول سالن حضور دارد؟">
              <Typography variant="body2" sx={{ py: 1 }}>
                {hatching?.vetFarm?.vetFarmFullName ? "بله" : "خیر"}
              </Typography>
            </LabelField>
          </Grid>
          <Grid xs={12} lg={3} p={1}>
            <LabelField label="نام مسئول سالن در زمان بازدید">
              <Typography variant="body2" sx={{ py: 1 }}>
                {hatching?.vetFarm?.vetFarmFullName || "---"}
              </Typography>
            </LabelField>
          </Grid>
          <Grid xs={12} lg={3} p={1}>
            <LabelField label="تلفن مسئول سالن">
              <Typography variant="body2" sx={{ py: 1 }}>
                {hatching?.vetFarm?.vetFarmMobile || "---"}
              </Typography>
            </LabelField>
          </Grid>
        </Grid>
      </Grid>
    );
  };

  return (
    <Box
      sx={{
        maxHeight: "80vh",
        overflowY: "auto",
        width: "100%",
        p: 2,
      }}
    >
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 2,
        }}
      >
        <Typography variant="h5" sx={{ fontWeight: "bold" }}>
          اطلاعات
        </Typography>
        <IconButton
          onClick={handleDownloadPdf}
          color="error"
          title="دانلود PDF"
        >
          <PictureAsPdfIcon />
        </IconButton>
      </Box>
      <Divider sx={{ mb: 3 }} />
      {renderInformationTab()}

      <Typography variant="h5" sx={{ fontWeight: "bold", mb: 2, mt: 4 }}>
        پایش سلامت
      </Typography>
      <Divider sx={{ mb: 3 }} />
      {renderHealthMonitoringTab()}

      <Typography variant="h5" sx={{ fontWeight: "bold", mb: 2, mt: 4 }}>
        زیرساخت
      </Typography>
      <Divider sx={{ mb: 3 }} />
      {renderInfrastructureTab()}

      <Typography variant="h5" sx={{ fontWeight: "bold", mb: 2, mt: 4 }}>
        مستندات
      </Typography>
      <Divider sx={{ mb: 3 }} />
      {renderDocumentsTab()}

      {fullscreenMedia && (
        <Box
          onClick={handleCloseFullscreen}
          sx={{
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0, 0, 0, 0.9)",
            zIndex: 9999,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            cursor: "pointer",
          }}
        >
          <IconButton
            onClick={(e) => {
              e.stopPropagation();
              handleCloseFullscreen();
            }}
            sx={{
              position: "absolute",
              top: 16,
              right: 16,
              backgroundColor: "rgba(255, 255, 255, 0.2)",
              color: "white",
              "&:hover": {
                backgroundColor: "rgba(255, 255, 255, 0.3)",
              },
              zIndex: 10000,
            }}
          >
            <CloseIcon />
          </IconButton>
          <Box
            onClick={(e) => e.stopPropagation()}
            sx={{
              maxWidth: "90vw",
              maxHeight: "90vh",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            {fullscreenMedia?.toLowerCase().match(/\.(mp4|webm|ogg|mov)$/i) ? (
              <Box
                component="video"
                src={fullscreenMedia}
                controls
                autoPlay
                sx={{
                  maxWidth: "100%",
                  maxHeight: "90vh",
                  objectFit: "contain",
                }}
              />
            ) : (
              <Box
                component="img"
                src={fullscreenMedia}
                alt="fullscreen"
                sx={{
                  maxWidth: "100%",
                  maxHeight: "90vh",
                  objectFit: "contain",
                }}
              />
            )}
          </Box>
        </Box>
      )}
    </Box>
  );
};
