import { useMutation, useQuery } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { Building2, Sparkles } from "lucide-react";
import { 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, fetchTenants } from "../../../lib/adminApi";
import { t } from "../../../lib/i18n";
import { DomainTagInput } from "../components/DomainTagInput";
import {
  type ServerDomainConflict,
  formatDomainConflictMessage,
} from "../utils/domainTags";

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

  const parentQuery = useQuery({
    queryKey: ["tenants", { limit: 1000 }],
    queryFn: () => fetchTenants(1000, 0),
  });

  const mutation = useMutation({
    mutationFn: (overrideForceDomains?: string[]) =>
      createTenant({
        name,
        type,
        slug: slug || undefined,
        parentId: parentId || undefined,
        description: description || undefined,
        status,
        domains,
        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 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 className="space-y-2">
              <Label htmlFor="parentId" className="text-sm font-semibold">
                {t("ui.admin.tenants.create.form.parent", "상위 테넌트 (선택)")}
              </Label>
              <select
                id="parentId"
                name="parentId"
                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={parentId}
                onChange={(e) => setParentId(e.target.value)}
              >
                <option value="">{t("ui.common.none", "없음")}</option>
                {parentQuery.data?.items?.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.name} ({t.slug})
                  </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={parentQuery.data?.items ?? []}
              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>

          {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;
