import { useMutation, useQuery } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { ArrowLeft, Save, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useParams } 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 { deleteTenant, fetchTenant, updateTenant } from "../../lib/adminApi";

function TenantDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const tenantId = useMemo(() => id ?? "", [id]);

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

  const [name, setName] = useState("");
  const [slug, setSlug] = useState("");
  const [description, setDescription] = useState("");
  const [status, setStatus] = useState("active");

  useEffect(() => {
    if (!tenantQuery.data) {
      return;
    }
    setName(tenantQuery.data.name);
    setSlug(tenantQuery.data.slug);
    setDescription(tenantQuery.data.description ?? "");
    setStatus(tenantQuery.data.status);
  }, [tenantQuery.data]);

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

  const deleteMutation = useMutation({
    mutationFn: () => deleteTenant(tenantId),
    onSuccess: () => {
      navigate("/tenants");
    },
  });

  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("이 테넌트를 삭제할까요?")) {
      return;
    }
    deleteMutation.mutate();
  };

  return (
    <div className="space-y-8">
      <header className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-2">
          <div className="flex items-center gap-2 text-sm text-[var(--color-muted)]">
            <Link to="/tenants" className="inline-flex items-center gap-2">
              <ArrowLeft size={14} />
              Tenants
            </Link>
            <span>/</span>
            <span className="text-foreground">Detail</span>
          </div>
          <h2 className="text-3xl font-semibold">테넌트 상세</h2>
          <p className="text-sm text-[var(--color-muted)]">
            테넌트 정보를 수정하거나 삭제할 수 있습니다.
          </p>
        </div>
        <Badge variant="muted">Admin only</Badge>
      </header>

      <Card className="bg-[var(--color-panel)]">
        <CardHeader>
          <CardTitle>Tenant profile</CardTitle>
          <CardDescription>Slug와 상태 변경은 바로 적용됩니다.</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">
              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)} />
          </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>

      <div className="flex flex-wrap items-center justify-between gap-3">
        <Button
          variant="outline"
          onClick={handleDelete}
          disabled={deleteMutation.isPending}
        >
          <Trash2 size={16} />
          삭제
        </Button>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => navigate("/tenants")}>
            취소
          </Button>
          <Button
            onClick={() => updateMutation.mutate()}
            disabled={
              updateMutation.isPending ||
              tenantQuery.isLoading ||
              name.trim() === ""
            }
          >
            <Save size={16} />
            저장
          </Button>
        </div>
      </div>
    </div>
  );
}

export default TenantDetailPage;
