import { type FC, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import Button from "../../../../../components/Button";
import Input from "../../../../../components/Input";
import Select from "../../../../../components/Select";

type InitialValues = {
  title: string;
  fileUrl?: string;
  type: "file" | "link";
};

type Props = {
  onClose: () => void;
  onSubmit: (data: { file?: File; title: string; linkId: string }) => void;
  isSubmitting?: boolean;
  initialValues?: InitialValues;
  submitLabel?: string;
};

const TaskDetailAttachmentForm: FC<Props> = ({
  onClose,
  onSubmit,
  isSubmitting = false,
  initialValues,
  submitLabel,
}) => {
  const { t } = useTranslation("global");
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File | null>(null);
  const [title, setTitle] = useState(initialValues?.title ?? "");
  const [linkId, setLinkId] = useState(initialValues?.type === "link" ? (initialValues.fileUrl ?? "") : "");
  const isEdit = Boolean(initialValues);

  const linkItems = [{ value: "", label: t("taskmanager.task_detail.none") }];

  const canSubmit = isEdit
    ? Boolean(title.trim()) || Boolean(file)
    : Boolean(file) || Boolean(title.trim());

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0];
    if (selected) setFile(selected);
  };

  const handleSubmit = () => {
    if (!canSubmit) return;
    onSubmit({
      file: file ?? undefined,
      title: title.trim(),
      linkId,
    });
  };

  const currentFileLabel = file
    ? file.name
    : initialValues?.fileUrl
      ? initialValues.fileUrl
      : t("no_select_file");

  return (
    <div className="flex flex-col gap-3">
      <h3 className="text-xs font-bold text-center">{t("taskmanager.task_detail.attachment")}</h3>

      <div className="w-full h-8 border border-white rounded-xl items-center px-2 flex gap-2 bg-white/63">
        <button type="button" onClick={() => fileInputRef.current?.click()} className="shrink-0 h-6 rounded-lg text-[11px] px-3 bg-secondary">
          {t("select_file")}
        </button>
        <span className="text-[11px] text-description truncate">{currentFileLabel}</span>
        <input ref={fileInputRef} type="file" className="hidden" onChange={handleFileChange} />
      </div>

      <div className="flex items-center gap-2 mt-1.5">
        <div className="flex-1 border-t border-dashed border-[#D0D0D0]" />
        <span className="text-[11px] text-description">{t("taskmanager.task_detail.or")}</span>
        <div className="flex-1 border-t border-dashed border-[#D0D0D0]" />
      </div>

      <Input label={t("taskmanager.task_detail.label_title")} value={title} onChange={(e) => setTitle(e.target.value)} className="h-8 bg-white/63 border-white" labelClassName="text-xs" />

      <Select
        label={t("taskmanager.task_detail.link")}
        labelClassName="text-xs"
        value={linkId}
        onChange={(e) => setLinkId(e.target.value)}
        items={linkItems}
        className="h-8 bg-white/63 border-white text-xs rounded-xl"
      />

      <div className="flex justify-end gap-2">
        <Button type="button" onClick={onClose} disabled={isSubmitting} className="h-8 bg-[#E8E4F0] text-[#292D32] rounded-xl text-xs w-[95px]">
          {t("cancel")}
        </Button>
        <Button type="button" onClick={handleSubmit} disabled={!canSubmit || isSubmitting} isLoading={isSubmitting} className="h-8 bg-[#292D32] text-white rounded-xl text-xs disabled:opacity-50 w-[95px]">
          {submitLabel ?? t("taskmanager.task_detail.insert")}
        </Button>
      </div>
    </div>
  );
};

export default TaskDetailAttachmentForm;
