import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { Save, Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Button } from "../../../components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../../../components/ui/card";
import { Input } from "../../../components/ui/input";
import { Label } from "../../../components/ui/label";
import { Textarea } from "../../../components/ui/textarea";
import { toast } from "../../../components/ui/use-toast";
import {
  approveTenant,
  deleteTenant,
  fetchAllTenants,
  fetchTenant,
  updateTenant,
} from "../../../lib/adminApi";
import { t } from "../../../lib/i18n";
import { DomainTagInput } from "../components/DomainTagInput";
import { ParentTenantSelector } from "../components/ParentTenantSelector";
import {
  type ServerDomainConflict,
  formatDomainConflictMessage,
} from "../utils/domainTags";
import {
  ORG_UNIT_TYPE_OPTIONS,
  TENANT_VISIBILITY_OPTIONS,
  type TenantVisibility,
  mergeTenantOrgConfig,
  readTenantOrgConfig,
  removeTenantOrgConfig,
  shouldAllowHanmacOrgConfig,
} from "../utils/orgConfig";
import { isSeedTenant } from "../utils/protectedTenants";

export function TenantProfilePage() {
  const { tenantId } = useParams<{ tenantId: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  if (!tenantId) {
    return (
      <div>{t("msg.admin.tenants.missing_id", "테넌트 ID가 없습니다.")}</div>
    );
  }

  const tenantQuery = useQuery({
    queryKey: ["tenant", tenantId],
    queryFn: () => fetchTenant(tenantId),
  });

  const parentQuery = useQuery({
    queryKey: ["tenants", "list-all"],
    queryFn: () => fetchAllTenants(),
  });

  const [name, setName] = useState("");
  const [type, setType] = useState("COMPANY");
  const [slug, setSlug] = useState("");
  const [description, setDescription] = useState("");
  const [status, setStatus] = useState("active");
  const [domains, setDomains] = useState<string[]>([]);
  const [forceDomainConflicts, setForceDomainConflicts] = useState<string[]>(
    [],
  );
  const [parentId, setParentId] = useState("");
  const [orgUnitType, setOrgUnitType] = useState("");
  const [tenantVisibility, setTenantVisibility] =
    useState<TenantVisibility>("public");

  useEffect(() => {
    if (tenantQuery.data) {
      const orgConfig = readTenantOrgConfig(tenantQuery.data.config);
      setName(tenantQuery.data.name);
      setType(tenantQuery.data.type || "COMPANY");
      setSlug(tenantQuery.data.slug);
      setDescription(tenantQuery.data.description ?? "");
      setStatus(tenantQuery.data.status);
      setDomains(tenantQuery.data.domains ?? []);
      setForceDomainConflicts([]);
      setParentId(tenantQuery.data.parentId ?? "");
      setOrgUnitType(orgConfig.orgUnitType);
      setTenantVisibility(orgConfig.visibility);
    }
  }, [tenantQuery.data]);

  const allTenants = parentQuery.data?.items ?? [];
  const orgConfigCandidate = tenantQuery.data
    ? {
        ...tenantQuery.data,
        parentId: parentId || undefined,
        slug,
      }
    : undefined;
  const canEditOrgConfig = orgConfigCandidate
    ? shouldAllowHanmacOrgConfig(orgConfigCandidate, [
        ...allTenants,
        orgConfigCandidate,
      ])
    : false;

  const updateMutation = useMutation({
    mutationFn: (overrideForceDomains?: string[]) => {
      const baseConfig = tenantQuery.data?.config;
      const config = canEditOrgConfig
        ? mergeTenantOrgConfig(baseConfig, {
            orgUnitType,
            visibility: tenantVisibility,
          })
        : removeTenantOrgConfig(baseConfig);

      return updateTenant(tenantId, {
        name,
        type,
        slug,
        description: description || undefined,
        status,
        parentId: parentId || undefined,
        domains,
        forceDomainConflicts: overrideForceDomains ?? forceDomainConflicts,
        config,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenants"] });
      queryClient.invalidateQueries({ queryKey: ["tenant", tenantId] });
      toast.success(t("msg.info.saved_success", "저장되었습니다."));
    },
    onError: (
      err: AxiosError<{
        code?: string;
        error?: string;
        conflicts?: ServerDomainConflict[];
      }>,
    ) => {
      const conflicts = err.response?.data?.conflicts ?? [];
      if (
        err.response?.data?.code === "tenant_domain_conflict" &&
        conflicts.length > 0
      ) {
        const nextForceDomains = Array.from(
          new Set([...forceDomainConflicts, ...conflicts.map((c) => c.domain)]),
        );
        const message = conflicts.map(formatDomainConflictMessage).join("\n");
        if (window.confirm(message)) {
          setForceDomainConflicts(nextForceDomains);
          updateMutation.mutate(nextForceDomains);
        }
        return;
      }
      toast.error(
        err.response?.data?.error ||
          t("err.common.unknown", "오류가 발생했습니다."),
      );
    },
  });

  const approveMutation = useMutation({
    mutationFn: () => approveTenant(tenantId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenants"] });
      queryClient.invalidateQueries({ queryKey: ["tenant", tenantId] });
      toast.success(
        t("msg.admin.tenants.approve_success", "테넌트가 승인되었습니다."),
      );
    },
    onError: (err: AxiosError<{ error?: string }>) => {
      toast.error(
        err.response?.data?.error ||
          t("err.common.unknown", "오류가 발생했습니다."),
      );
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () => deleteTenant(tenantId),
    onSuccess: () => {
      navigate("/tenants");
      toast.success(
        t("msg.admin.tenants.delete_success", "테넌트가 삭제되었습니다."),
      );
    },
  });

  const errorMsg = (updateMutation.error as AxiosError<{ error?: string }>)
    ?.response?.data?.error;
  const loadError = (tenantQuery.error as AxiosError<{ error?: string }>)
    ?.response?.data?.error;
  const isProtectedSeedTenant = tenantQuery.data
    ? isSeedTenant(tenantQuery.data)
    : false;

  const handleDelete = () => {
    if (isProtectedSeedTenant) {
      return;
    }
    if (
      window.confirm(
        t("msg.admin.tenants.delete_confirm", "삭제하시겠습니까?", {
          name: tenantQuery.data?.name ?? "",
        }),
      )
    ) {
      deleteMutation.mutate();
    }
  };

  const handleApprove = () => {
    if (
      window.confirm(
        t("msg.admin.tenants.approve_confirm", "이 테넌트를 승인하시겠습니까?"),
      )
    ) {
      approveMutation.mutate();
    }
  };

  return (
    <>
      <Card className="bg-[var(--color-panel)] mt-6">
        <CardHeader>
          <CardTitle>
            {t("ui.admin.tenants.profile.title", "테넌트 프로필")}
          </CardTitle>
          <CardDescription>
            {t(
              "ui.admin.tenants.profile.subtitle",
              "슬러그 및 상태 변경은 즉시 적용됩니다.",
            )}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {loadError && (
            <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {loadError}
            </div>
          )}
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("ui.admin.tenants.profile.name", "테넌트 이름")}{" "}
              <span className="text-destructive">*</span>
            </Label>
            <Input value={name} onChange={(e) => setName(e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("ui.admin.tenants.profile.type", "테넌트 유형")}
            </Label>
            <select
              id="type"
              className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
              value={type}
              onChange={(e) => setType(e.target.value)}
            >
              <option value="COMPANY">
                {t("domain.tenant_type.company", "COMPANY (일반 기업)")}
              </option>
              <option value="COMPANY_GROUP">
                {t(
                  "domain.tenant_type.company_group",
                  "COMPANY_GROUP (그룹사/지주사)",
                )}
              </option>
              <option value="ORGANIZATION">
                {t(
                  "domain.tenant_type.organization",
                  "ORGANIZATION (정규 조직)",
                )}
              </option>
              <option value="USER_GROUP">
                {t(
                  "domain.tenant_type.user_group",
                  "USER_GROUP (내부 부서/팀)",
                )}
              </option>
              <option value="PERSONAL">
                {t(
                  "domain.tenant_type.personal",
                  "PERSONAL (개인 워크스페이스)",
                )}
              </option>
            </select>
          </div>
          <div
            data-testid="tenant-parent-org-config-layout"
            className="grid gap-4 md:grid-cols-4"
          >
            <div
              data-testid="tenant-parent-picker-slot"
              className={canEditOrgConfig ? "md:col-span-2" : "md:col-span-4"}
            >
              <ParentTenantSelector
                id="parentId"
                label={t(
                  "ui.admin.tenants.profile.form.parent",
                  "상위 테넌트 (선택)",
                )}
                value={parentId}
                onChange={setParentId}
                tenants={parentQuery.data?.items ?? []}
                noneLabel={t("ui.common.none", "없음 (최상위)")}
                helpText={t(
                  "ui.admin.tenants.profile.form.parent_help",
                  "하위 조직을 종속시킬 경우 상위 테넌트를 선택해주세요.",
                )}
                excludeTenantId={tenantId}
              />
            </div>
            {canEditOrgConfig && (
              <>
                <div
                  data-testid="tenant-org-unit-type-slot"
                  className="space-y-2"
                >
                  <Label className="text-sm font-semibold">
                    {t(
                      "ui.admin.tenants.profile.org_unit_type",
                      "조직 세부타입",
                    )}
                  </Label>
                  <select
                    className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                    value={orgUnitType}
                    onChange={(event) => setOrgUnitType(event.target.value)}
                  >
                    <option value="">{t("ui.common.none", "없음")}</option>
                    {ORG_UNIT_TYPE_OPTIONS.map((option) => (
                      <option key={option} value={option}>
                        {option}
                      </option>
                    ))}
                  </select>
                </div>
                <div data-testid="tenant-visibility-slot" className="space-y-2">
                  <Label className="text-sm font-semibold">
                    {t("ui.admin.tenants.profile.visibility", "공개 범위")}
                  </Label>
                  <select
                    className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                    value={tenantVisibility}
                    onChange={(event) =>
                      setTenantVisibility(
                        event.target.value as TenantVisibility,
                      )
                    }
                  >
                    {TENANT_VISIBILITY_OPTIONS.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </>
            )}
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("ui.admin.tenants.profile.slug", "슬러그 (Slug)")}
            </Label>
            <Input value={slug} onChange={(e) => setSlug(e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("ui.admin.tenants.profile.description", "설명")}
            </Label>
            <Textarea
              rows={3}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t(
                "ui.admin.tenants.profile.allowed_domains",
                "허용된 도메인 (콤마로 구분)",
              )}
            </Label>
            <DomainTagInput
              id="tenant-domains"
              value={domains}
              onChange={setDomains}
              tenants={parentQuery.data?.items ?? []}
              currentTenantId={tenantId}
              confirmedConflicts={forceDomainConflicts}
              onConfirmedConflictsChange={setForceDomainConflicts}
              placeholder="example.com, example.kr"
            />
            <p className="text-xs text-muted-foreground">
              {t(
                "ui.admin.tenants.profile.allowed_domains_help",
                "이 도메인을 가진 이메일로 가입한 사용자는 자동으로 이 테넌트에 배정됩니다.",
              )}
            </p>
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("ui.admin.tenants.profile.status", "상태")}
            </Label>
            <div className="flex gap-3">
              <Button
                type="button"
                variant={status === "active" ? "default" : "outline"}
                onClick={() => setStatus("active")}
              >
                {t("ui.common.status.active", "활성")}
              </Button>
              <Button
                type="button"
                variant={status === "inactive" ? "default" : "outline"}
                onClick={() => setStatus("inactive")}
              >
                {t("ui.common.status.inactive", "비활성")}
              </Button>
            </div>
          </div>
          {errorMsg && (
            <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {errorMsg}
            </div>
          )}
        </CardContent>
      </Card>

      <div className="mt-8 flex flex-wrap items-center justify-between gap-3">
        <Button
          variant="outline"
          onClick={handleDelete}
          disabled={deleteMutation.isPending || isProtectedSeedTenant}
          title={
            isProtectedSeedTenant
              ? t(
                  "msg.admin.tenants.seed_delete_blocked",
                  "초기 설정 테넌트는 삭제할 수 없습니다.",
                )
              : undefined
          }
        >
          <Trash2 size={16} />
          {t("ui.common.delete", "삭제")}
        </Button>
        <div className="flex items-center gap-2">
          {status === "pending" && (
            <Button
              variant="default"
              className="bg-green-600 hover:bg-green-700"
              onClick={handleApprove}
              disabled={approveMutation.isPending}
            >
              {t("ui.admin.tenants.profile.approve_button", "테넌트 승인")}
            </Button>
          )}
          <Button variant="outline" onClick={() => navigate("/tenants")}>
            {t("ui.common.cancel", "취소")}
          </Button>
          <Button
            onClick={() => updateMutation.mutate(undefined)}
            disabled={
              updateMutation.isPending ||
              tenantQuery.isLoading ||
              name.trim() === ""
            }
          >
            <Save size={16} />
            {t("ui.common.save", "저장")}
          </Button>
        </div>
      </div>
    </>
  );
}
