import { useMutation } 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 { Badge } from "../../../components/ui/badge";
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 } from "../../../lib/adminApi";

function TenantCreatePage() {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [slug, setSlug] = useState("");
  const [description, setDescription] = useState("");
  const [status, setStatus] = useState("active");

  const mutation = useMutation({
    mutationFn: () =>
      createTenant({
        name,
        slug: slug || undefined,
        description: description || undefined,
        status,
      }),
    onSuccess: () => {
      navigate("/tenants");
    },
  });

  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 items-center gap-2 text-sm text-[var(--color-muted)]">
          <span>Tenants</span>
          <span>/</span>
          <span className="text-foreground">Create</span>
        </div>
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="text-3xl font-semibold">테넌트 추가</h2>
            <p className="text-sm text-[var(--color-muted)]">
              글로벌 운영 기준의 신규 테넌트를 등록합니다.
            </p>
          </div>
          <Badge variant="muted">Admin only</Badge>
        </div>
      </header>

      <Card className="bg-[var(--color-panel)]">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Building2 size={18} />
            Tenant Profile
          </CardTitle>
          <CardDescription>
            필수 정보만 입력해도 생성 가능합니다. Slug는 없으면 자동 생성됩니다.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              Tenant 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">Slug</Label>
            <Input
              value={slug}
              onChange={(e) => setSlug(e.target.value)}
              placeholder="tenant-slug"
            />
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">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">Status</Label>
            <div className="flex gap-3">
              <Button
                type="button"
                variant={status === "active" ? "default" : "outline"}
                onClick={() => setStatus("active")}
              >
                Active
              </Button>
              <Button
                type="button"
                variant={status === "inactive" ? "default" : "outline"}
                onClick={() => setStatus("inactive")}
              >
                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} />
            정책 메모
          </CardTitle>
          <CardDescription>
            Tenant 권한 정책은 추후 Keto 연계로 확장 예정입니다.
          </CardDescription>
        </CardHeader>
        <CardContent className="text-sm text-[var(--color-muted)]">
          생성 직후에는 기본 활성 상태로 부여되며, 필요 시 상태를 수정하세요.
        </CardContent>
      </Card>

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

export default TenantCreatePage;
