import React, { useState, useRef, useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";

import { Button } from "@/shared/common/ui/button";
import { Upload } from "lucide-react";

import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/shared/common/ui/tabs";
import { Input } from "@/shared/common/ui/input";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import {
  deactivateSignature,
  deactivateTeeter,
  SignatureAndTeeterService,
} from "@/record-management/services/api/signatureAndTeeterService";
import {
  useSignatureListWithPresigned,
  useTeetersListWithPresigned,
} from "../hooks/useSignatureAndTeeterWithPresigned";
import { useTranslation } from "react-i18next";
import { useDelegations } from "../hooks/useDelegations";
import SignatureForm from "./signatureForm";
import DelegationView from "@/record-management/common/DelegationView";
import { XSSUploadValidator } from "@/shared/services/validation/XSSUploadValidator";
import { SVGContentValidator } from "@/shared/services/validation/SVGContentValidator";
import { EmbeddedContentValidator } from "@/shared/services/validation/EmbeddedContentValidator";
import { MagicByteDetector } from "@/shared/services/validation/MagicByteDetector";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import StampGenerator, {
  type StampBlock,
} from "./StampGenerator";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";

export type UploadedTeeter = {
  id: string;
  url: string;
  name?: string;
  locale?: string;
};

type TeeterLanguage = "am" | "en" | "both";
type TeeterUploadLocale = "am" | "en" | null;

const UploadTeeterAndSignature = () => {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [uploadStatus, setUploadStatus] = useState<string>("");
  const [isUploading, setIsUploading] = useState(false);
  const [customFileName, setCustomFileName] = useState<string>("");
  const { t } = useTranslation();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const queryClient = useQueryClient();
  const { userDetails, selectedPosition } = useAuthUser();
  const employeeId = userDetails?.employee?.[0]?.id ?? "";
  const employeePositionId =
    userDetails?.employee?.filter((e) => e.positions?.length > 0)?.[0]
      ?.positions?.[0]?.employeePositionId ?? "";
  const { data: signatureData } = useSignatureListWithPresigned(employeeId);
  const { data: teeterData } = useTeetersListWithPresigned();
  const { handleError } = useErrorHandler(t);
  const signatureUrl = signatureData?.presignedSignatureUrl ?? null;
  const signatureId = signatureData?.signatureId ?? null;
  const teeters = teeterData?.presignedTeeters ?? [];
  const [localSignatureUrl, setLocalSignatureUrl] = useState<string | null>(
    null,
  );
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions?.some((pos) => pos.hasDelegated),
  );
  const [openSignatureForm, setOpenSignatureForm] = useState(false);
  const [showLanguagePicker, setShowLanguagePicker] = useState(false);
  const [teeterLanguage, setTeeterLanguage] = useState<TeeterLanguage | "">("");
  const [uploadLocale, setUploadLocale] = useState<"am" | "en" | "">("");
  const [stampBlocks, setStampBlocks] = useState<StampBlock[] | null>(null);
  const [generatedTeeterPreview, setGeneratedTeeterPreview] = useState<
    string | null
  >(null);

  const resolveGeneratedTeeterLocale = (
    language: TeeterLanguage | "",
  ): TeeterUploadLocale | undefined => {
    if (language === "am" || language === "en") {
      return language;
    }
    if (language === "both") {
      return null;
    }
    return undefined;
  };

  const buildStampBlocks = (language: TeeterLanguage): StampBlock[] => {
    const personName = userDetails?.name;
    const positionName = selectedPosition?.name;

    if (!personName || !positionName) {
      return [];
    }

    if (language === "am") {
      return [{ name: personName.am, position: positionName.am }];
    }
    if (language === "en") {
      return [{ name: personName.en, position: positionName.en }];
    }
    return [
      { name: personName.am, position: positionName.am },
      { name: personName.en, position: positionName.en },
    ];
  };

  const handleStartGenerateTeeter = () => {
    setShowLanguagePicker(true);
    setTeeterLanguage("");
    setStampBlocks(null);
    setGeneratedTeeterPreview(null);
  };

  const handleConfirmGenerateTeeter = () => {
    if (!teeterLanguage) return;
    const blocks = buildStampBlocks(teeterLanguage);
    if (
      blocks.length === 0 ||
      blocks.some((b) => !b.name?.trim() || !b.position?.trim())
    ) {
      setUploadStatus(t("signatureUpload.missingEmployeeData"));
      return;
    }
    setStampBlocks(blocks);
    setShowLanguagePicker(false);
  };

  const handleCancelGenerateTeeter = () => {
    setShowLanguagePicker(false);
    setTeeterLanguage("");
    setStampBlocks(null);
    setGeneratedTeeterPreview(null);
    setUploadLocale("");
  };

  const handleGeneratedTeeterUpload = async () => {
    if (!generatedTeeterPreview) {
      setUploadStatus(t("signatureUpload.selectPngFirst"));
      return;
    }

    setIsUploading(true);
    setUploadStatus(t("signatureUpload.uploading"));

    try {
      const blob = await (await fetch(generatedTeeterPreview)).blob();
      const generatedName = getGeneratedTeeterFileName();
      const file = new File([blob], generatedName, {
        type: "image/png",
      });

      const generatedLocale = resolveGeneratedTeeterLocale(teeterLanguage);
      if (generatedLocale === undefined) {
        setUploadStatus(t("signatureUpload.selectTeeterLanguage"));
        return;
      }

      await SignatureAndTeeterService.teeter.uploadAndCreate(
        file,
        generatedName,
        employeePositionId,
        generatedLocale,
      );
      queryClient.invalidateQueries({ queryKey: ["teetersListWithPresigned"] });
      setCustomFileName("");
      setStampBlocks(null);
      setGeneratedTeeterPreview(null);
      setUploadStatus(t("signatureUpload.uploadSuccess"));
    } catch (error) {
      handleError(error);
      setUploadStatus(t("signatureUpload.uploadFailed"));
    } finally {
      setIsUploading(false);
    }
  };

  const handleDrawnSignatureUpload = async (
    dataUrl: string,
    fileName: string,
  ) => {
    setIsUploading(true);
    setUploadStatus(t("signatureUpload.uploading"));

    try {
      // convert dataUrl -> file
      const blob = await (await fetch(dataUrl)).blob();
      const file = new File(
        [blob],
        fileName?.trim() ? `${fileName}.png` : getFileName("signature"),
        { type: "image/png" },
      );

      await SignatureAndTeeterService.signature.uploadAndCreate(
        file,
        file.name,
        employeeId,
      );

      queryClient.invalidateQueries({
        queryKey: ["signatureListWithPresigned"],
      });

      setLocalSignatureUrl(dataUrl); // local preview
      setUploadStatus(t("signatureUpload.uploadSuccess"));
      setOpenSignatureForm(false);
    } catch (err) {
      handleError(err);
      console.error("Signature upload failed", err);
      setUploadStatus(t("signatureUpload.uploadFailed"));
    } finally {
      setIsUploading(false);
    }
  };

  // sync with API data
  useEffect(() => {
    if (signatureUrl) {
      setLocalSignatureUrl(signatureUrl);
    }
  }, [signatureUrl]);
  const getBaseName = () => userDetails?.username ?? "file";
  const getFileName = (type: "signature" | "teeter") => {
    const fallback = getBaseName();
    const namePart = customFileName.trim() || fallback;
    return `${namePart}.png`;
  };

  const getGeneratedTeeterFileName = () => {
    const fallback = getBaseName();
    const base = (customFileName.trim() || fallback)
      .toLowerCase()
      .replace(/\s+/g, "-");
    const languageSuffix =
      teeterLanguage === "am"
        ? "amharic"
        : teeterLanguage === "en"
          ? "english"
          : "amharic-english";
    return `${base}-${languageSuffix}.png`;
  };

  const handleTeeterRemove = async (id: string) => {
    try {
      setUploadStatus(t("signatureUpload.removing"));
      await deactivateTeeter(id);
      queryClient.invalidateQueries({ queryKey: ["teetersListWithPresigned"] });
      setUploadStatus(t("signatureUpload.removedSuccess"));
    } catch (err) {
      console.error(t("signatureUpload.removeTeeterFailed"), err);
      setUploadStatus(t("signatureUpload.removeFailed"));
    }
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadStatus("");

    // Step 1: Validate file metadata (name, extension, MIME type, size)
    const validationResult = await XSSUploadValidator.validateFileForUpload(
      file,
      {
        allowedMimeTypes: ["image/jpeg", "image/png", "image/gif"],
        allowedExtensions: [".jpg", ".jpeg", ".png", ".gif"],
        maxSizeMB: 10,
        uploadContext: "signature",
      },
    );

    if (!validationResult.isValid) {
      const errorMsg =
        validationResult.clientValidation.fileName?.error ||
        validationResult.clientValidation.extension?.error ||
        validationResult.clientValidation.mimeType?.error ||
        validationResult.clientValidation.size?.error ||
        "File validation failed";
      setUploadStatus(errorMsg);
      setSelectedFile(null);
      setPreviewUrl(null);
      if (fileInputRef.current) fileInputRef.current.value = "";
      return;
    }

    // Step 2: Read file content and validate magic bytes
    try {
      const fileBuffer = await file.arrayBuffer();
      const uint8Array = new Uint8Array(fileBuffer);

      // Detect actual file type from magic bytes
      const detectedType = MagicByteDetector.detectFileType(uint8Array);

      // If magic bytes can't be detected, allow the file if declared type is allowed
      // This prevents false positives for valid image files with non-standard headers
      if (!detectedType) {
        const allowedMimes = ["image/jpeg", "image/png", "image/gif"];
        if (!allowedMimes.includes(file.type)) {
          setUploadStatus(
            `File type ${file.type} is not allowed. Only PNG, JPEG, and GIF images are supported.`,
          );
          setSelectedFile(null);
          setPreviewUrl(null);
          if (fileInputRef.current) fileInputRef.current.value = "";
          console.warn(`File type not allowed: ${file.name} (${file.type})`);
          return;
        }
        // Allow the file to proceed with declared type console.log(`Magic byte detection skipped for file: ${file.name}. Using declared type: ${file.type}`);
      }

      // Check if detected type matches declared type (only if detected)
      if (detectedType) {
        const mimeMatch = MagicByteDetector.validateMimeTypeMatch(
          uint8Array,
          file.type,
        );

        if (!mimeMatch) {
          const detectedMime =
            typeof detectedType === "string"
              ? detectedType
              : detectedType?.mime;
          const detectedDesc =
            MagicByteDetector.getFileTypeDescription(detectedMime);
          setUploadStatus(
            `File type mismatch detected. File appears to be ${detectedDesc}, not an image. Upload blocked for security.`,
          );
          setSelectedFile(null);
          setPreviewUrl(null);
          if (fileInputRef.current) fileInputRef.current.value = "";
          console.warn(
            `File type mismatch: declared=${file.type}, detected=${detectedMime}`,
          );
          return;
        }
      }

      // Step 3: Scan for embedded XSS attacks (MUST happen regardless of magic byte detection)
      const contentStr = new TextDecoder().decode(uint8Array);

      // Check for XSS patterns using the validator
      const hasXSSPatterns = EmbeddedContentValidator.containsXSSPatterns(
        contentStr,
        file.type,
      );

      // Additional aggressive check for common attack vectors
      const maliciousPatterns = [
        /<script/i,
        /javascript:/i,
        /on\w+\s*=/i, // onclick=, onload=, etc.
        /<iframe/i,
        /<object/i,
        /<embed/i,
        /eval\(/i,
        /expression\(/i,
        /vbscript:/i,
        /data:text\/html/i,
        /alert\(/i,
        /document\.domain/i,
        /document\.write/i,
      ];

      const hasAggressivePatterns = maliciousPatterns.some((pattern) =>
        pattern.test(contentStr),
      );

      if (hasXSSPatterns || hasAggressivePatterns) {
        const threatLevel = EmbeddedContentValidator.getThreatLevel(
          contentStr,
          file.type,
        );
        setUploadStatus(
          `File contains potentially malicious content (Threat Level: ${threatLevel}). Upload blocked for security.`,
        );
        setSelectedFile(null);
        setPreviewUrl(null);
        if (fileInputRef.current) fileInputRef.current.value = "";
        console.warn(
          `XSS threat detected in file: ${file.name}, Threat Level: ${threatLevel}, Patterns found: ${hasXSSPatterns ? "validator" : ""} ${hasAggressivePatterns ? "aggressive" : ""}`,
        );
        return;
      }

      // Step 4: Additional SVG-specific validation if file is SVG
      if (
        file.type === "image/svg+xml" ||
        file.name.toLowerCase().endsWith(".svg")
      ) {
        const svgValidation = SVGContentValidator.validateSVGContent(
          uint8Array,
          file.name,
        );
        if (!svgValidation.isValid) {
          setUploadStatus(svgValidation.error || "SVG file validation failed");
          setSelectedFile(null);
          setPreviewUrl(null);
          if (fileInputRef.current) fileInputRef.current.value = "";
          console.warn(`SVG validation failed for file: ${file.name}`);
          return;
        }
      }

      // All validations passed - create preview
      const preview = URL.createObjectURL(file);
      setSelectedFile(file);
      setPreviewUrl(preview);
    } catch (error) {
      const errorMsg =
        error instanceof Error
          ? error.message
          : "Failed to validate file content";
      setUploadStatus(`Error validating file: ${errorMsg}`);
      setSelectedFile(null);
      setPreviewUrl(null);
      if (fileInputRef.current) fileInputRef.current.value = "";
      console.error("File content validation error:", error);
    }
  };

  const handleUpload = async (type: "signature" | "teeter") => {
    if (!selectedFile)
      return setUploadStatus(t("signatureUpload.selectPngFirst"));

    setIsUploading(true);
    setUploadStatus(t("signatureUpload.uploading"));

    try {
      if (type === "signature") {
        if (signatureUrl) {
          setUploadStatus(t("signatureUpload.signatureExists"));
          setIsUploading(false);
          return;
        }

        await SignatureAndTeeterService.signature.uploadAndCreate(
          selectedFile,
          getFileName("signature"),
          employeeId,
        );
        queryClient.invalidateQueries({
          queryKey: ["signatureListWithPresigned"],
        });
      } else {
        await SignatureAndTeeterService.teeter.uploadAndCreate(
          selectedFile,
          getFileName("teeter"),
          employeePositionId,
          uploadLocale || undefined,
        );
        queryClient.invalidateQueries({
          queryKey: ["teetersListWithPresigned"],
        });
      }
      setCustomFileName("");
      setSelectedFile(null);
      setPreviewUrl(null);
      setUploadStatus(t("signatureUpload.uploadSuccess"));
      if (fileInputRef.current) fileInputRef.current.value = "";
    } catch (error) {
      handleError(error);
      setUploadStatus(t("signatureUpload.uploadFailed"));
    } finally {
      setIsUploading(false);
    }
  };

  const handleRemove = async () => {
    if (!signatureId) return;

    try {
      setUploadStatus(t("signatureUpload.removing"));
      await deactivateSignature(signatureId);
      queryClient.invalidateQueries({
        queryKey: ["signatureListWithPresigned"],
      });
      setUploadStatus(t("signatureUpload.removedSuccess"));
      setLocalSignatureUrl(null);
    } catch (error) {
      console.error(t("signatureUpload.removeFailed"), error);
      setUploadStatus(t("signatureUpload.removeTeeterFailed"));
    }
  };

  return isDelegated ? (
    <DelegationView />
  ) : (
    <div className="p-4 w-full max-w-screen-md mx-auto mt-3">
      <Tabs
        defaultValue="signature"
        className="w-full bg-white dark:bg-gray-800 rounded-lg shadow-lg">
        <TabsList className="flex w-full rounded-t-lg bg-gradient-to-r from-primary-400 to-primary-600 text-white font-semibold dark:from-gray-700 dark:to-gray-600 dark:text-gray-200">
          <TabsTrigger
            value="signature"
            className="w-1/2 py-1 hover:bg-primary-500 dark:hover:bg-gray-500 cursor-pointer dark:text-gray-200 dark:data-[state=active]:bg-gray-600">
            {t("signatureUpload.signature")}
          </TabsTrigger>
          <TabsTrigger
            value="teeter"
            className="w-1/2 py-1 hover:bg-primary-500 dark:hover:bg-gray-500 cursor-pointer dark:text-gray-200 dark:data-[state=active]:bg-gray-600">
            {t("signatureUpload.teeter")}
          </TabsTrigger>
        </TabsList>

        {/* Signature Tab */}
        <TabsContent value="signature" className="p-4 space-y-6">
          {localSignatureUrl ? (
            // same uploaded signature section you already have
            <div className="space-y-3">
              <p className="text-sm text-gray-600 dark:text-gray-300">
                {t("signatureUpload.uploadSignature")}
              </p>
              <div className="w-full max-w-xs mx-auto border border-gray-200 dark:border-gray-600 rounded-lg p-4 dark:bg-gray-700">
                <img
                  src={localSignatureUrl}
                  alt="Uploaded signature"
                  className="max-h-32 w-full object-contain"
                />
              </div>
              <Button
                onClick={handleRemove}
                className="bg-red-600 text-white hover:bg-red-700 w-full">
                {t("signatureUpload.remove")}
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              {!openSignatureForm ? (
                // 👉 File upload section
                <div className="border-2 border-dashed border-primary-300 dark:border-primary-600 rounded-lg p-6 text-center space-y-4">
                  <Input
                    type="text"
                    placeholder={t("signatureUpload.enterFileName")}
                    value={customFileName}
                    onChange={(e) => setCustomFileName(e.target.value)}
                    className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
                  />
                  <Input
                    type="file"
                    accept="image/png"
                    onChange={handleFileChange}
                    className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
                  />

                  {previewUrl && (
                    <div className="space-y-2">
                      <p className="text-sm text-gray-600 dark:text-gray-300">
                        {t("signatureUpload.preview")}:
                      </p>
                      <div className="w-full max-w-xs mx-auto border border-gray-200 dark:border-gray-600 rounded-lg p-4 dark:bg-gray-700">
                        <img
                          src={previewUrl}
                          alt="Signature Preview"
                          className="max-h-32 w-full object-contain"
                        />
                      </div>
                    </div>
                  )}

                  <Button
                    onClick={() => handleUpload("signature")}
                    disabled={!selectedFile || isUploading}
                    className="bg-primary-600 text-white disabled:bg-primary-300 w-full">
                    {isUploading
                      ? t("signatureUpload.uploading")
                      : t("signatureUpload.upload")}{" "}
                    <Upload />
                  </Button>

                  <Button
                    onClick={() => setOpenSignatureForm(true)}
                    className="bg-blue-600 text-white w-full hover:bg-blue-700">
                    {t("signatureUpload.openSignatureForm")}
                  </Button>
                </div>
              ) : (
                // 👉 Signature form section
                <div className="border-2 border-dashed border-primary-300 dark:border-primary-600 rounded-lg p-6 space-y-4">
                  <Input
                    type="text"
                    placeholder={t("signatureUpload.enterFileName")}
                    value={customFileName}
                    onChange={(e) => setCustomFileName(e.target.value)}
                    className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
                  />

                  <SignatureForm
                    onSubmit={(dataUrl) =>
                      handleDrawnSignatureUpload(dataUrl, customFileName)
                    }
                    onCancel={() => setOpenSignatureForm(false)}
                  />
                </div>
              )}
            </div>
          )}
        </TabsContent>

        {/* Teeter Tab */}
        <TabsContent value="teeter" className="p-4 space-y-6">
          {teeters.length > 0 && (
            <div className="space-y-6">
              {teeters.map(({ id, url }) => (
                <div key={id} className="space-y-3">
                  <p className="text-sm text-gray-600 dark:text-gray-300">
                    {t("signatureUpload.uploadTeeter")}
                  </p>
                  <div className="w-full max-w-xs mx-auto border border-gray-200 dark:border-gray-600 rounded-lg p-4 dark:bg-gray-700">
                    <img
                      src={url}
                      alt="Uploaded teeter"
                      className="max-h-32 w-full object-contain"
                    />
                  </div>
                  <Button
                    onClick={() => handleTeeterRemove(id)}
                    className="bg-red-600 text-white hover:bg-red-700 w-full">
                    {t("signatureUpload.remove")}
                  </Button>
                </div>
              ))}
            </div>
          )}

          <div className="border-2 border-dashed border-primary-300 dark:border-primary-600 rounded-lg p-6 text-center space-y-4">
            {!stampBlocks && !showLanguagePicker && (
              <Button
                type="button"
                onClick={handleStartGenerateTeeter}
                className="w-full bg-blue-600 text-white hover:bg-blue-700"
              >
                {t("signatureUpload.generateTeeter")}
              </Button>
            )}

            {showLanguagePicker && (
              <div className="space-y-4 text-left">
                <p className="text-sm font-medium text-gray-700 dark:text-gray-200">
                  {t("signatureUpload.selectTeeterLanguage")}
                </p>
                <Select
                  value={teeterLanguage}
                  onValueChange={(value) =>
                    setTeeterLanguage(value as TeeterLanguage)
                  }
                >
                  <SelectTrigger className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600">
                    <SelectValue
                      placeholder={t("signatureUpload.selectTeeterLanguage")}
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="am">
                      {t("signatureUpload.languageAmharic")}
                    </SelectItem>
                    <SelectItem value="en">
                      {t("signatureUpload.languageEnglish")}
                    </SelectItem>
                    <SelectItem value="both">
                      {t("signatureUpload.languageBoth")}
                    </SelectItem>
                  </SelectContent>
                </Select>
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleCancelGenerateTeeter}
                    className="flex-1 dark:border-gray-600 dark:text-gray-200"
                  >
                    {t("signatureUpload.cancelGenerateTeeter")}
                  </Button>
                  <Button
                    type="button"
                    onClick={handleConfirmGenerateTeeter}
                    disabled={!teeterLanguage}
                    className="flex-1 bg-primary-600 text-white disabled:bg-primary-300"
                  >
                    {t("signatureUpload.confirmGenerateTeeter")}
                  </Button>
                </div>
              </div>
            )}

            {stampBlocks && (
              <div className="space-y-4 text-left">
                <StampGenerator
                  blocks={stampBlocks}
                  onPreviewChange={setGeneratedTeeterPreview}
                />
                <Button
                  type="button"
                  onClick={() => void handleGeneratedTeeterUpload()}
                  disabled={!generatedTeeterPreview || isUploading}
                  className="w-full bg-primary-600 text-white disabled:bg-primary-300"
                >
                  {isUploading
                    ? t("signatureUpload.uploading")
                    : t("signatureUpload.uploadGeneratedTeeter")}{" "}
                  <Upload className="ml-2 h-4 w-4" />
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleCancelGenerateTeeter}
                  className="w-full dark:border-gray-600 dark:text-gray-200"
                >
                  {t("signatureUpload.cancelGenerateTeeter")}
                </Button>
              </div>
            )}

            {!stampBlocks && (
              <>
                <Input
                  type="text"
                  placeholder={t("signatureUpload.enterFileName")}
                  value={customFileName}
                  onChange={(e) => setCustomFileName(e.target.value)}
                  className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
                />
                <div className="text-left space-y-1">
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-200">
                    {t("signatureUpload.selectTeeterLanguage")}
                  </p>
                  <Select
                    value={uploadLocale}
                    onValueChange={(v) => setUploadLocale(v as "am" | "en")}
                  >
                    <SelectTrigger className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600">
                      <SelectValue
                        placeholder={t("signatureUpload.selectTeeterLanguage")}
                      />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="am">
                        {t("signatureUpload.languageAmharic")}
                      </SelectItem>
                      <SelectItem value="en">
                        {t("signatureUpload.languageEnglish")}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <Input
                  type="file"
                  accept="image/png"
                  onChange={handleFileChange}
                  ref={fileInputRef}
                  className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
                />
                <p className="text-primary-700 dark:text-primary-400 font-medium">
                  {t("signatureUpload.uploadTeeterNote")}
                </p>

                {previewUrl && (
                  <div className="space-y-2">
                    <p className="text-sm text-gray-600 dark:text-gray-300">
                      {t("signatureUpload.preview")}:
                    </p>
                    <div className="w-full max-w-xs mx-auto border border-gray-200 dark:border-gray-600 rounded-lg p-4 dark:bg-gray-700">
                      <img
                        src={previewUrl}
                        alt="Teeter Preview"
                        className="max-h-32 w-full object-contain"
                      />
                    </div>
                  </div>
                )}
                <Button
                  onClick={() => handleUpload("teeter")}
                  disabled={!selectedFile || isUploading}
                  className="bg-primary-600 text-white disabled:bg-primary-300 w-full">
                  {isUploading
                    ? t("signatureUpload.uploading")
                    : t("signatureUpload.upload")}{" "}
                  <Upload />
                </Button>
              </>
            )}
          </div>
        </TabsContent>
      </Tabs>

      {/* Upload Status */}
      {uploadStatus && (
        <p
          className={`mt-4 text-center font-semibold ${uploadStatus.includes("failed") ? "text-red-600 dark:text-red-400" : "text-primary-700 dark:text-primary-400"
            }`}>
          {uploadStatus}
        </p>
      )}
    </div>
  );
};

export default UploadTeeterAndSignature;
