import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from "@/shared/common/ui/card";
import { Stamp, X, Plus } from "lucide-react";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { Button } from "@/shared/common/ui/button";
import { useEffect, useState, useRef } from "react";
import { useSeal } from "@/user-management/hooks/useSeal";
import {
  CreateSealPayload,
  sealService,
} from "@/user-management/services/api/sealService";
import { toast } from "sonner";
import { FilePreview } from "./ContentManagement";
import { presignedAxios } from "@/shared/services/presignedAxios";
import { t } from "i18next";
import { useQueryClient } from "@tanstack/react-query";

interface Props {
  unitId: string;
}

const SealCard = ({ unitId }: Props) => {
  const {
    createSeal,
    isCreatingSeal,
    isLoadingSeals,
    deleteSeal,
    getSealsByUnitId,
  } = useSeal();

  const [file, setFile] = useState<File>();
  const [previews, setPreviews] = useState<FilePreview[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
    const queryClient = useQueryClient();

  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);

  const [sealName, setSealName] = useState("");
  const [sealNameError, setSealNameError] = useState("");

  const MAX_SIZE = 1 * 1024 * 1024;

  const { data: seals } = getSealsByUnitId(unitId);

  // -------------------------------
  // Fetch existing seals
  // -------------------------------
  useEffect(() => {
    let isMounted = true;

    const fetchPresigned = async () => {
      if (!seals?.items) return;

      const filtered = seals.items.filter(
        (s) => s.uploadedSuccessfully && s.isCurrent
      );

      const resolved = await Promise.all(
        filtered.map(async (seal): Promise<FilePreview | null> => {
          try {
            const sealDetail = await sealService.getSeal(seal.id);
            const presigned = sealDetail.data.presigned;

            if (!presigned) return null;

            return {
              type: "seal",
              file: new File([], seal.fileInfo.fileName),
              url: presigned,
              uploadedAt: new Date(seal.createdAt),
              id: seal.id,
            };
          } catch {
            return null;
          }
        })
      );

      const filteredPreviews: FilePreview[] = resolved.filter(
        (p): p is FilePreview => p !== null
      );

      if (isMounted) {
        setPreviews(filteredPreviews);
      }
    };

    fetchPresigned();

    return () => {
      isMounted = false;

      previews.forEach((p) => {
        if (!p.id && p.url.startsWith("blob:")) {
          URL.revokeObjectURL(p.url);
        }
      });
    };
  }, [seals?.items]);

  // -------------------------------
  // File validation + preview
  // -------------------------------
  const handleFileUpload = (selectedFile: File) => {
    if (selectedFile.type !== "image/png") {
      toast.error(t("contentManagement.onlyPngAllowed"));
      return;
    }

    if (selectedFile.size > MAX_SIZE) {
      toast.error("Image size should be less than 1 MB");
      return;
    }

    const tempUrl = URL.createObjectURL(selectedFile);
    const img = new Image();

    img.onload = () => {
      if (img.width !== img.height) {
        toast.error(t("contentManagement.onlySquareAllowed"));
        URL.revokeObjectURL(tempUrl);
        return;
      }

      setFile(selectedFile);
      setSealName("");
      setSealNameError("");

      setPreviews([
        {
          type: "seal",
          url: tempUrl,
          file: selectedFile,
          uploadedAt: new Date(),
          id: null,
        },
      ]);
    };

    img.onerror = () => {
      toast.error(t("contentManagement.invalidImage"));
      URL.revokeObjectURL(tempUrl);
    };

    img.src = tempUrl;
  };

  // -------------------------------
  // Upload flow (CREATE + PUT)
  // -------------------------------
  const uploadSeal = async () => {
    if (!file) {
      toast.error(t("contentManagement.noFileSelected"));
      return;
    }

    if (!sealName.trim()) {
      setSealNameError(t("contentManagement.sealNameMsg"));
      return;
    }

    try {
      // Step 1: Create seal (get presigned URL)
      const payload: CreateSealPayload = {
        fileInfo: {
          fileName: file.name,
          contentType: file.type,
          size: file.size,
          originalname: file.name,
        },
        name: {
          am: sealName,
          en: sealName,
        },
        unitId,
      };

      const data = await createSeal(payload);

      // Step 2: Upload file
      setIsUploading(true);
      setUploadProgress(0);

      await presignedAxios.put(data.presigned, file, {
        headers: {
          "Content-Type": file.type,
        },
      });

      // await updateSealStatus({
      //   id: data.id,
      //   updateSealStatusPayload: {
      //     id: data.id,
      //     parentId: data.id,
      //     uploadedSuccessfully: true,
      //   },
      // });

      setIsUploading(false);
      setUploadProgress(100);

      // Reset UI
      setFile(undefined);
      setSealName("");
      setSealNameError("");

      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
      
      queryClient.invalidateQueries({ queryKey: ["seal"] });

      toast.success(t("contentManagement.sealSuccessMsg"));
    } catch (error) {
      console.error(error);
      toast.error(t("contentManagement.sealErrorMsg"));

      setIsUploading(false);
      setUploadProgress(0);
      setFile(undefined);
    }
  };

  // -------------------------------
  // Delete seal
  // -------------------------------
  const handleRemove = async (id: string | null) => {
    if (!id) return;

    try {
      await deleteSeal(id);
      setPreviews((prev) => prev.filter((p) => p.id !== id));
      toast.success(t("contentManagement.sealRemove"));
    } catch (error) {
      console.error(error);
      toast.error(t("contentManagement.sealRemove"));
    }
  };

  const formatDate = (date: Date) =>
    new Intl.DateTimeFormat("en-US", {
      hour: "numeric",
      minute: "numeric",
      hour12: true,
      month: "short",
      day: "numeric",
    }).format(date);

  const isProcessing = isCreatingSeal || isUploading;

  return (
    <Card className="dark:border-gray-700 dark:bg-gray-800">
      <CardHeader>
        <CardTitle className="flex items-center dark:text-white">
          <Stamp className="h-5 w-5 mr-2" />
          {t("contentManagement.seal")}
        </CardTitle>
        <CardDescription className="dark:text-gray-400">
          {t("contentManagement.uploadSealMsg")} (PNG, max 1MB)
        </CardDescription>
      </CardHeader>

      <CardContent className="space-y-4">
        <div className="flex justify-between items-center">
          <Label htmlFor="seal" className="dark:text-gray-200">{t("contentManagement.sealImage")}</Label>
          <Button
            variant="outline"
            className="bg-primary hover:bg-primary/90 text-primary-foreground"
            onClick={() => fileInputRef.current?.click()}
            disabled={isProcessing}
          >
            <Plus className="h-4 w-4 mr-2" />
            {t("contentManagement.addSeal")}
          </Button>
        </div>

        <Input
          ref={fileInputRef}
          type="file"
          accept=".png,image/png"
          className="hidden"
          onChange={(e) =>
            e.target.files?.[0] && handleFileUpload(e.target.files[0])
          }
          disabled={isProcessing}
        />

        {/* PREVIEWS */}
        {previews.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {previews.map((preview) => (
              <div
                key={preview?.id || preview?.url}
                className="border rounded-lg p-3 bg-gray-50 dark:bg-gray-700 dark:border-gray-600"
              >
                <div className="flex justify-between items-center mb-2">
                  <span className="text-sm text-muted-foreground dark:text-gray-400">
                    {formatDate(preview?.uploadedAt)}
                  </span>

                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemove(preview?.id || null)}
                    className="text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/30"
                    disabled={isLoadingSeals}
                  >
                    <X className="h-4 w-4 text-red-500" />
                  </Button>
                </div>

                <img
                  src={preview.url}
                  alt="Seal"
                  className="max-h-32 mx-auto object-contain"
                />
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center p-4 border border-dashed rounded-lg dark:border-gray-600 dark:bg-gray-700/30">
            <p className="text-muted-foreground dark:text-gray-400">
              {t("contentManagement.noSealMsg")}
            </p>
            <p className="text-sm text-muted-foreground dark:text-gray-500 mt-1">
              {t("contentManagement.addSealInstruction")}
            </p>
          </div>
        )}

        {/* NAME INPUT */}
        {file && (
          <div className="space-y-2">
            <Label htmlFor="sealName" className="dark:text-gray-200">{t("contentManagement.sealName")}</Label>
            <Input
              value={sealName}
              onChange={(e) => {
                setSealName(e.target.value);
                setSealNameError("");
              }}
              placeholder="Enter seal name"
              className="dark:bg-gray-700 dark:border-gray-600 dark:text-white"
            />

            {sealNameError && (
              <p className="text-sm text-red-500">{sealNameError}</p>
            )}
          </div>
        )}

        {/* UPLOAD BUTTON (MAIN UX CONTROL) */}
        {file && (
          <Button
            className="w-full bg-primary hover:bg-primary/90"
            onClick={uploadSeal}
            disabled={isProcessing || !file}
          >
            {isCreatingSeal && "Creating seal..."}
            {isUploading && `Uploading ${uploadProgress}%`}
            {!isProcessing && t("contentManagement.saveSeal")}
          </Button>
        )}
      </CardContent>
    </Card>
  );
};

export default SealCard;