import { useMutation, useQuery } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { Building2, Sparkles } from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } 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 { createTenant, fetchAllTenants } 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,
  shouldAllowHanmacOrgConfig,
} from "../utils/orgConfig";

function TenantCreatePage() {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [type, setType] = useState("COMPANY");
  const [slug, setSlug] = useState("");
  const [parentId, setParentId] = useState("");
  const [parentStepConfirmed, setParentStepConfirmed] = useState(false);
  const [orgUnitType, setOrgUnitType] = useState("");
  const [visibility, setVisibility] = useState<TenantVisibility>("public");
  const [description, setDescription] = useState("");
  const [status, setStatus] = useState("active");
  const [domains, setDomains] = useState<string[]>([]);
  const [forceDomainConflicts, setForceDomainConflicts] = useState<string[]>(
    [],
  );

  const parentQuery = useQuery({
    queryKey: ["tenants", "all"],
    queryFn: () => fetchAllTenants(),
  });
  const tenants = parentQuery.data?.items ?? [];
  const selectedParentTenant = tenants.find((tenant) => tenant.id === parentId);
  const canConfigureHanmacOrg = useMemo(() => {
    if (!selectedParentTenant) return false;
    if (selectedParentTenant.slug.toLowerCase() === "hanmac-family") {
      return true;
    }
    return shouldAllowHanmacOrgConfig(selectedParentTenant, tenants);
  }, [selectedParentTenant, tenants]);
  const canEditTenantDetails =
    parentStepConfirmed || Boolean(selectedParentTenant);
  const parentContextLabel = selectedParentTenant
    ? canConfigureHanmacOrg
      ? t(
          "ui.admin.tenants.create.parent_context.hanmac",
          "한맥가족 하위 테넌트",
        )
      : t("ui.admin.tenants.create.parent_context.general", "일반 하위 테넌트")
    : parentStepConfirmed
      ? t("ui.admin.tenants.create.parent_context.root", "최상위 테넌트")
      : t(
          "ui.admin.tenants.create.parent_context.pick_required",
          "상위 테넌트 선택 필요",
        );
  const handleParentChange = (nextParentId: string) => {
    setParentId(nextParentId);
    setParentStepConfirmed(false);
  };

  const mutation = useMutation({
    mutationFn: (overrideForceDomains?: string[]) =>
      createTenant({
        name,
        type,
        slug: slug || undefined,
        parentId: parentId || undefined,
        description: description || undefined,
        status,
        domains,
        config: canConfigureHanmacOrg
          ? mergeTenantOrgConfig(undefined, { orgUnitType, visibility })
          : undefined,
        forceDomainConflicts: overrideForceDomains ?? forceDomainConflicts,
      }),
    onSuccess: () => {
      navigate("/tenants");
    },
    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);
          mutation.mutate(nextForceDomains);
        }
      }
    },
  });

  const errorMsg = (mutation.error as AxiosError<{ error?: string }>)?.response
    ?.data?.error;

  return (
    <div className="space-y-8">
      <header className="space-y-2">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="space-y-2">
            <h2 className="text-3xl font-semibold">
              {t("ui.admin.tenants.create.title", "테넌트 생성")}
            </h2>
            <p className="text-sm text-[var(--color-muted)]">
              {t(
                "msg.admin.tenants.create.subtitle",
                "새로운 테넌트를 시스템에 등록합니다.",
              )}
            </p>
          </div>
        </div>
      </header>

      <Card className="bg-[var(--color-panel)]">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Building2 size={18} />
            {t("ui.admin.tenants.create.profile.title", "Tenant Profile")}
          </CardTitle>
          <CardDescription>
            {t(
              "msg.admin.tenants.create.profile.subtitle",
              "필수 정보만 입력해도 생성 가능합니다. Slug는 없으면 자동 생성됩니다.",
            )}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div
            data-testid="tenant-parent-org-config-layout"
            className="grid gap-4 md:grid-cols-4"
          >
            <div
              data-testid="tenant-parent-picker-slot"
              className={
                canConfigureHanmacOrg ? "md:col-span-2" : "md:col-span-4"
              }
            >
              <ParentTenantSelector
                id="parentId"
                label={t(
                  "ui.admin.tenants.create.form.parent",
                  "상위 테넌트 (선택)",
                )}
                value={parentId}
                onChange={handleParentChange}
                tenants={tenants}
                noneLabel={t("ui.common.none", "없음")}
                contextLabel={parentContextLabel}
                orgChartPickerLabel={t(
                  "ui.admin.tenants.create.form.pick_hanmac_parent",
                  "한맥가족에서 선택",
                )}
                localPickerLabel={t(
                  "ui.admin.tenants.create.form.pick_other_parent",
                  "다른 테넌트 선택",
                )}
                localTenantFilter={(tenant) =>
                  tenant.slug.toLowerCase() !== "hanmac-family" &&
                  !shouldAllowHanmacOrgConfig(tenant, tenants)
                }
                labelAction={
                  !selectedParentTenant ? (
                    <Button
                      type="button"
                      variant={parentStepConfirmed ? "default" : "outline"}
                      size="sm"
                      onClick={() => setParentStepConfirmed(true)}
                    >
                      {t(
                        "ui.admin.tenants.create.form.root_tenant",
                        "최상위 테넌트로 생성",
                      )}
                    </Button>
                  ) : null
                }
              />
            </div>
            {canConfigureHanmacOrg && (
              <>
                <div
                  data-testid="tenant-org-unit-type-slot"
                  className="space-y-2"
                >
                  <Label
                    htmlFor="tenant-org-unit-type"
                    className="text-sm font-semibold"
                  >
                    {t(
                      "ui.admin.tenants.profile.org_unit_type",
                      "조직 세부타입",
                    )}
                  </Label>
                  <select
                    id="tenant-org-unit-type"
                    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
                    htmlFor="tenant-visibility"
                    className="text-sm font-semibold"
                  >
                    {t("ui.admin.tenants.profile.visibility", "공개 범위")}
                  </Label>
                  <select
                    id="tenant-visibility"
                    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={visibility}
                    onChange={(event) =>
                      setVisibility(event.target.value as TenantVisibility)
                    }
                  >
                    {TENANT_VISIBILITY_OPTIONS.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </>
            )}
          </div>
          {canEditTenantDetails && (
            <>
              <div className="space-y-2">
                <Label htmlFor="tenant-name" className="text-sm font-semibold">
                  {t("ui.admin.tenants.create.form.name", "테넌트 이름")}{" "}
                  <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="tenant-name"
                  name="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder={t(
                    "ui.admin.tenants.create.form.name_placeholder",
                    "테넌트 이름을 입력하세요",
                  )}
                />
              </div>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label
                    htmlFor="tenant-type"
                    className="text-sm font-semibold"
                  >
                    {t("ui.admin.tenants.create.form.type", "테넌트 유형")}
                  </Label>
                  <select
                    id="tenant-type"
                    name="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>
              <div className="space-y-2">
                <Label htmlFor="tenant-slug" className="text-sm font-semibold">
                  {t("ui.admin.tenants.create.form.slug", "슬러그 (Slug)")}
                </Label>
                <Input
                  id="tenant-slug"
                  name="slug"
                  value={slug}
                  onChange={(e) => setSlug(e.target.value)}
                  placeholder={t(
                    "ui.admin.tenants.create.form.slug_placeholder",
                    "tenant-slug",
                  )}
                />
              </div>
              <div className="space-y-2">
                <Label
                  htmlFor="tenant-description"
                  className="text-sm font-semibold"
                >
                  {t("ui.admin.tenants.create.form.description", "설명")}
                </Label>
                <Textarea
                  id="tenant-description"
                  name="description"
                  rows={3}
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label
                  htmlFor="tenant-domains"
                  className="text-sm font-semibold"
                >
                  {t(
                    "ui.admin.tenants.create.form.domains_label",
                    "허용된 도메인 (콤마로 구분)",
                  )}
                </Label>
                <DomainTagInput
                  id="tenant-domains"
                  value={domains}
                  onChange={setDomains}
                  tenants={tenants}
                  confirmedConflicts={forceDomainConflicts}
                  onConfirmedConflictsChange={setForceDomainConflicts}
                  placeholder={t(
                    "ui.admin.tenants.create.form.domains_placeholder",
                    "example.com, example.kr",
                  )}
                />
                <p className="text-xs text-muted-foreground">
                  {t(
                    "msg.admin.tenants.create.form.domains_help",
                    "이 도메인을 가진 이메일로 가입한 사용자는 자동으로 이 테넌트에 배정됩니다.",
                  )}
                </p>
              </div>
              <div className="space-y-2">
                <Label className="text-sm font-semibold">
                  {t("ui.admin.tenants.create.form.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>
            </>
          )}
          {!canEditTenantDetails && (
            <div className="rounded-md border border-dashed px-3 py-4 text-sm text-muted-foreground">
              {t(
                "msg.admin.tenants.create.pick_parent_first",
                "상위 테넌트를 먼저 선택하세요.",
              )}
            </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>

      <Card className="bg-[var(--color-panel)]">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles size={18} />
            {t("ui.admin.tenants.create.memo.title", "정책 메모")}
          </CardTitle>
          <CardDescription>
            {t(
              "msg.admin.tenants.create.memo.subtitle",
              "Tenant 권한 정책은 추후 Keto 연계로 확장 예정입니다.",
            )}
          </CardDescription>
        </CardHeader>
        <CardContent className="text-sm text-[var(--color-muted)]">
          {t(
            "msg.admin.tenants.create.memo.body",
            "생성 직후에는 기본 활성 상태로 부여되며, 필요 시 상태를 수정하세요.",
          )}
        </CardContent>
      </Card>

      <div className="flex items-center justify-end gap-3">
        <Button variant="outline" onClick={() => navigate("/tenants")}>
          {t("ui.common.cancel", "취소")}
        </Button>
        <Button
          onClick={() => mutation.mutate(undefined)}
          disabled={mutation.isPending || name.trim() === ""}
        >
          {t("ui.common.create", "생성")}
        </Button>
      </div>
    </div>
  );
}

export default TenantCreatePage;
