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,
  fetchTenant,
  fetchTenants,
  updateTenant,
} from "../../../lib/adminApi";
import { t } from "../../../lib/i18n";

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: () => fetchTenants(1000, 0),
  });

  const availableParents =
    parentQuery.data?.items?.filter((t) => t.id !== tenantId) || [];

  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("");
  const [parentId, setParentId] = useState("");

  useEffect(() => {
    if (tenantQuery.data) {
      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?.join(", ") ?? "");
      setParentId(tenantQuery.data.parentId ?? "");
    }
  }, [tenantQuery.data]);

  const updateMutation = useMutation({
    mutationFn: () =>
      updateTenant(tenantId, {
        name,
        type,
        slug,
        description: description || undefined,
        status,
        parentId: parentId || undefined,
        domains: domains
          .split(",")
          .map((d) => d.trim())
          .filter((d) => d !== ""),
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenants"] });
      queryClient.invalidateQueries({ queryKey: ["tenant", tenantId] });
      toast.success(t("msg.info.saved_success", "저장되었습니다."));
    },
    onError: (err: AxiosError<{ error?: string }>) => {
      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 handleDelete = () => {
    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="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.profile.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>
              {availableParents.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.name} ({t.slug})
                </option>
              ))}
            </select>
            <p className="text-xs text-muted-foreground mt-1">
              {t(
                "ui.admin.tenants.profile.form.parent_help",
                "하위 조직을 종속시킬 경우 상위 테넌트를 선택해주세요.",
              )}
            </p>
          </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>
            <Input
              value={domains}
              onChange={(e) => setDomains(e.target.value)}
              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}
        >
          <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()}
            disabled={
              updateMutation.isPending ||
              tenantQuery.isLoading ||
              name.trim() === ""
            }
          >
            <Save size={16} />
            {t("ui.common.save", "저장")}
          </Button>
        </div>
      </div>
    </>
  );
}
