import React from "react";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/shared/common/ui/select";
import { X } from "lucide-react";

import { useSeal } from "../hooks/useSeals";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";

export interface SealOption {
  value: string;
  label: string;
}

interface SealSelectorProps {
  selectedSeal: string | null;
  onSelect: (seal: string | null) => void;
  options?: SealOption[];
}

const SealSelector: React.FC<SealSelectorProps> = ({
  selectedSeal,
  onSelect,
}) => {
  const { sealDetailsData, isLoading } = useSeal();
 const { t } = useTranslation();
  const selectedSealObj = sealDetailsData.find(
    (seal: any) => seal.id === selectedSeal
  );
  const localizedName = useLocalizedName()

  return (
    <div className="mb-6">
      <label className="block text-sm font-semibold mb-2">{t('convert.selectSealLabel')}</label>
      <div className="flex items-center gap-2">
        <div className="flex-1">
          <Select value={selectedSeal || ""} onValueChange={onSelect}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder={t('convert.selectSealPlaceholder')} />
            </SelectTrigger>
            <SelectContent>
              {isLoading && <div className="p-2">{t('convert.loadingSeals')}</div>}
              {sealDetailsData.map((seal: any) => (
                <SelectItem key={seal.id} value={seal.id}>
                  {localizedName(seal.name)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        {selectedSeal && (
          <button
            type="button"
            onClick={() => onSelect(null)}
            aria-label={t("signatureUpload.remove", "Clear")}
            title={t("signatureUpload.remove", "Clear")}
            className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-white text-slate-500 hover:border-red-300 hover:bg-red-50 hover:text-red-600 transition-colors dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:border-red-700 dark:hover:bg-red-950/30 dark:hover:text-red-300"
          >
            <X className="h-4 w-4" />
          </button>
        )}
      </div>

      {/* Show preview if one is selected */}
      {selectedSealObj && (
        <div className="mt-4 flex flex-col items-start gap-2">
          <p className="text-sm font-medium">{t('convert.selectedSealPreview')}</p>
          <img
            src={selectedSealObj.presigned}
            alt={selectedSealObj.name.am}
            className="w-48 h-48 object-contain border rounded"
          />
        </div>
      )}
    </div>
  );
};

export default SealSelector;
