import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { PageTransition } from "@/components/layout/PageTransition";
import { BackLink } from "@/components/layout/BackLink";
import { Card } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { Skeleton } from "@/components/ui/Skeleton";
import { Badge } from "@/components/ui/Badge";
import { useSkill, useUpdateSkill, useUpdateSkillPackage } from "@/hooks/useSkills";
import { useToastStore } from "@/stores/toastStore";
import { formatFileSize } from "@/utils/formatters";
import { translateError } from "@/utils/translateError";

export function EditSkillPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const addToast = useToastStore((s) => s.addToast);
  const { data: skill, isLoading, refetch } = useSkill(id ?? "");
  const updateMutation = useUpdateSkill(id ?? "");
  const updatePackageMutation = useUpdateSkillPackage(id ?? "");
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [zipFile, setZipFile] = useState<File | null>(null);

  const handleToggleVisibility = async () => {
    if (!skill) return;
    try {
      await updateMutation.mutateAsync({ isPrivate: !skill.isPrivate });
      addToast({
        type: "success",
        message: skill.isPrivate
          ? t("editSkill.nowPublic", "Skill is now public")
          : t("editSkill.nowPrivate", "Skill is now private"),
      });
      refetch();
    } catch (err) {
      const fallback = t("editSkill.visibilityFailed", "Failed to update visibility");
      const message = translateError(err, fallback);
      addToast({ type: "error", message });
    }
  };

  const handleUploadPackage = async () => {
    if (!zipFile) return;
    try {
      await updatePackageMutation.mutateAsync({ zipFile });
      addToast({
        type: "success",
        message: t("editSkill.packageUpdated", "Skill package updated"),
      });
      setZipFile(null);
      if (fileInputRef.current) fileInputRef.current.value = "";
      refetch();
    } catch (err) {
      const fallback = t("editSkill.packageFailed", "Failed to update package");
      const message = translateError(err, fallback);
      addToast({ type: "error", message });
    }
  };

  if (isLoading) {
    return (
      <PageTransition>
        <div className="h-full overflow-y-auto py-4">
          <Card className="mx-auto max-w-2xl">
            <Skeleton lines={8} />
          </Card>
        </div>
      </PageTransition>
    );
  }

  if (!skill) {
    return (
      <PageTransition>
        <div className="h-full overflow-y-auto py-4">
          <p className="py-20 text-center text-meta">
            {t("editSkill.notFound", "Skill not found")}
          </p>
        </div>
      </PageTransition>
    );
  }

  const backTarget = `/skills/${encodeURIComponent(skill.name ?? id ?? "")}`;

  return (
    <PageTransition>
      <div className="h-full overflow-y-auto py-4">
        <nav className="mb-4">
          <BackLink
            label={t("editSkill.backToSkill", "Back to {{name}}", { name: skill.name })}
            to={backTarget}
          />
        </nav>

        <h1 className="mb-8 font-display text-3xl font-semibold tracking-tight text-strong sm:text-4xl">
          <span className="font-mono text-xs uppercase tracking-[0.18em] text-accent block mb-1.5">
            {t("editSkill.titlePrefix", "EDIT")}
          </span>
          {skill.name}
        </h1>

        <div className="mx-auto max-w-2xl space-y-6">
          {/* Visibility toggle */}
          <Card>
            <h3 className="mb-4 font-mono text-[10px] font-semibold uppercase tracking-[0.16em] text-meta border-b border-dashed border-subtle pb-3">
              {t("editSkill.visibilityHeading", "Visibility")}
            </h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="font-text text-sm text-strong">
                  {t("editSkill.currentVisibility", "Current visibility:")}{" "}
                  <Badge color={skill.isPrivate ? "cyan" : "green"}>
                    {skill.isPrivate
                      ? t("editSkill.badgePrivate", "Private")
                      : t("editSkill.badgePublic", "Public")}
                  </Badge>
                </p>
                <p className="mt-1 font-text text-xs text-meta">
                  {skill.isPrivate
                    ? t(
                        "editSkill.privateDesc",
                        "Only you can see this skill. Make it public to share with others.",
                      )
                    : t(
                        "editSkill.publicDesc",
                        "This skill is visible to everyone. Make it private to hide it.",
                      )}
                </p>
              </div>
              <Button
                variant="secondary"
                size="sm"
                onClick={handleToggleVisibility}
                loading={updateMutation.isPending}
              >
                {skill.isPrivate
                  ? t("editSkill.makePublic", "Make Public")
                  : t("editSkill.makePrivate", "Make Private")}
              </Button>
            </div>
          </Card>

          {/* Upload new package */}
          <Card>
            <h3 className="mb-4 font-mono text-[10px] font-semibold uppercase tracking-[0.16em] text-meta border-b border-dashed border-subtle pb-3">
              {t("editSkill.updatePackageHeading", "Update Package")}
            </h3>
            <p className="mb-4 font-text text-xs text-meta">
              {t(
                "editSkill.updatePackageDesc",
                "Upload a new ZIP package to replace the current skill contents. Tags, description, and metadata are extracted from the SKILL.md inside the ZIP.",
              )}
            </p>

            <div className="space-y-4">
              <div
                onClick={() => fileInputRef.current?.click()}
                className="flex cursor-pointer flex-col items-center justify-center rounded border-2 border-dashed border-accent/20 bg-page/50 px-6 py-8 transition-colors hover:border-accent/40"
              >
                {zipFile ? (
                  <div className="text-center">
                    <p className="font-mono text-sm text-accent">{zipFile.name}</p>
                    <p className="mt-1 text-xs text-meta">{formatFileSize(zipFile.size)}</p>
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        setZipFile(null);
                        if (fileInputRef.current) fileInputRef.current.value = "";
                      }}
                      className="mt-2 text-xs text-danger hover:underline cursor-pointer"
                    >
                      {t("common.remove", "Remove")}
                    </button>
                  </div>
                ) : (
                  <div className="text-center">
                    <p className="font-text text-sm text-meta">
                      {t("editSkill.selectZip", "Click to select a .zip file")}
                    </p>
                    <p className="mt-1 text-xs text-meta/60">
                      {t("editSkill.zipSizeHint", ".zip files up to 50 MB")}
                    </p>
                  </div>
                )}
              </div>
              <input
                ref={fileInputRef}
                type="file"
                accept=".zip"
                onChange={(e) => {
                  const f = e.target.files?.[0];
                  if (f) setZipFile(f);
                }}
                className="hidden"
              />

              {zipFile && (
                <div className="flex justify-end">
                  <Button
                    onClick={handleUploadPackage}
                    loading={updatePackageMutation.isPending}
                  >
                    {t("editSkill.uploadPackage", "Upload Package")}
                  </Button>
                </div>
              )}
            </div>
          </Card>
        </div>
      </div>
    </PageTransition>
  );
}
