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 {
  formatDomainConflictMessage,
  type ServerDomainConflict,
} from "../utils/domainTags";
import {
  getOrgUnitTypeOptionsForTenantType,
  mergeTenantOrgConfig,
  readTenantOrgConfig,
  removeTenantOrgConfig,
  shouldAllowHanmacOrgConfig,
  TENANT_VISIBILITY_OPTIONS,
  type TenantVisibility,
} from "../utils/orgConfig";
import { isSeedTenant } from "../utils/protectedTenants";

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

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

  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");
  const [worksmobileExcluded, setWorksmobileExcluded] = useState(false);

  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);
      setWorksmobileExcluded(orgConfig.worksmobileExcluded);
    }
  }, [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 orgUnitTypeOptions = getOrgUnitTypeOptionsForTenantType(type);

  const updateMutation = useMutation({
    mutationFn: (overrideForceDomains?: string[]) => {
      const baseConfig = tenantQuery.data?.config;
      const config = canEditOrgConfig
        ? mergeTenantOrgConfig(baseConfig, {
            orgUnitType,
            visibility: tenantVisibility,
            worksmobileExcluded,
          })
        : 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;

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

  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="mt-4 bg-[var(--color-panel)]">
        <CardHeader className="px-5 py-3">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div>
              <CardTitle className="text-lg">
                {t("ui.admin.tenants.profile.title", "테넌트 프로필")}
              </CardTitle>
              <CardDescription>
                {t(
                  "ui.admin.tenants.profile.subtitle",
                  "슬러그 및 상태 변경은 즉시 적용됩니다.",
                )}
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-3 px-5 pb-4">
          {loadError && (
            <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {loadError}
            </div>
          )}
          <div
            data-testid="tenant-profile-primary-row"
            className="grid gap-3 lg:grid-cols-[minmax(180px,1fr)_minmax(160px,0.8fr)_minmax(320px,1.4fr)]"
          >
            <div data-testid="tenant-name-slot" className="space-y-1">
              <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 data-testid="tenant-slug-slot" className="space-y-1">
              <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 data-testid="tenant-parent-picker-slot" className="min-w-0">
              <ParentTenantSelector
                id="parentId"
                label={t(
                  "ui.admin.tenants.profile.form.parent",
                  "상위 테넌트 (선택)",
                )}
                value={parentId}
                onChange={setParentId}
                tenants={parentQuery.data?.items ?? []}
                noneLabel={t("ui.common.none", "없음 (최상위)")}
                excludeTenantId={tenantId}
                compact
                controlTestId="tenant-parent-picker-control"
              />
            </div>
          </div>
          <div
            data-testid="tenant-profile-config-row"
            className="grid gap-3 lg:grid-cols-[minmax(190px,1fr)_minmax(150px,0.8fr)_minmax(150px,0.8fr)_minmax(190px,0.9fr)]"
          >
            <div data-testid="tenant-type-slot" className="space-y-1">
              <Label className="text-sm font-semibold">
                {t("ui.admin.tenants.profile.type", "테넌트 유형")}
              </Label>
              <select
                id="type"
                data-testid="tenant-type-select"
                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>
            {canEditOrgConfig && (
              <>
                <div
                  data-testid="tenant-org-unit-type-slot"
                  className="space-y-1"
                >
                  <Label className="text-sm font-semibold">
                    {t(
                      "ui.admin.tenants.profile.org_unit_type",
                      "조직 세부타입",
                    )}
                  </Label>
                  <select
                    data-testid="tenant-org-unit-type-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>
                    {orgUnitTypeOptions.map((option) => (
                      <option key={option} value={option}>
                        {option}
                      </option>
                    ))}
                  </select>
                </div>
                <div data-testid="tenant-visibility-slot" className="space-y-1">
                  <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
                  data-testid="tenant-worksmobile-excluded-slot"
                  className="space-y-1"
                >
                  <Label className="text-sm font-semibold">
                    {t(
                      "ui.admin.tenants.profile.worksmobile_sync",
                      "WORKS 연동",
                    )}
                  </Label>
                  <select
                    id="worksmobileExcluded"
                    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={worksmobileExcluded ? "excluded" : "enabled"}
                    onChange={(event) =>
                      setWorksmobileExcluded(event.target.value === "excluded")
                    }
                  >
                    <option value="enabled">
                      {t(
                        "ui.admin.tenants.profile.worksmobile_enabled",
                        "연동",
                      )}
                    </option>
                    <option value="excluded">
                      {t(
                        "ui.admin.tenants.profile.worksmobile_excluded",
                        "제외",
                      )}
                    </option>
                  </select>
                </div>
              </>
            )}
          </div>
          <div className="grid gap-3 lg:grid-cols-[minmax(260px,0.9fr)_minmax(360px,1.4fr)_auto]">
            <div className="space-y-1">
              <Label className="text-sm font-semibold">
                {t("ui.admin.tenants.profile.description", "설명")}
              </Label>
              <Textarea
                rows={2}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>
            <div className="space-y-1">
              <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"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-sm font-semibold">
                {t("ui.admin.tenants.profile.status", "상태")}
              </Label>
              <div className="flex gap-2">
                <Button
                  type="button"
                  size="sm"
                  variant={status === "active" ? "default" : "outline"}
                  onClick={() => setStatus("active")}
                >
                  {t("ui.common.status.active", "활성")}
                </Button>
                <Button
                  type="button"
                  size="sm"
                  variant={status === "inactive" ? "default" : "outline"}
                  onClick={() => setStatus("inactive")}
                >
                  {t("ui.common.status.inactive", "비활성")}
                </Button>
              </div>
            </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-4 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>
    </>
  );
}
