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 {
  approveTenant,
  deleteTenant,
  fetchTenant,
  fetchTenantGroups,
  updateTenant,
} from "../../../lib/adminApi";

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

  if (!tenantId) {
    return <div>Tenant ID is missing</div>;
  }

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

  const groupsQuery = useQuery({
    queryKey: ["tenant-groups", { limit: 100 }],
    queryFn: () => fetchTenantGroups(100, 0),
  });

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

  useEffect(() => {
    if (tenantQuery.data) {
      setName(tenantQuery.data.name);
      setSlug(tenantQuery.data.slug);
      setDescription(tenantQuery.data.description ?? "");
      setStatus(tenantQuery.data.status);
      setDomains(tenantQuery.data.domains?.join(", ") ?? "");
      setTenantGroupId(tenantQuery.data.tenantGroupId ?? "");
    }
  }, [tenantQuery.data]);

  const updateMutation = useMutation({
    mutationFn: () =>
      updateTenant(tenantId, {
        name,
        slug,
        description: description || undefined,
        status,
        tenantGroupId: tenantGroupId || undefined,
        domains: domains
          .split(",")
          .map((d) => d.trim())
          .filter((d) => d !== ""),
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenants"] });
      queryClient.invalidateQueries({ queryKey: ["tenant", tenantId] });
      alert("Tenant updated successfully");
    },
  });

  const approveMutation = useMutation({
    mutationFn: () => approveTenant(tenantId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tenants"] });
      queryClient.invalidateQueries({ queryKey: ["tenant", tenantId] });
      alert("Tenant approved successfully");
    },
  });

  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("Are you sure you want to delete this tenant?")) {
      deleteMutation.mutate();
    }
  };

  const handleApprove = () => {
    if (window.confirm("Approve this tenant?")) {
      approveMutation.mutate();
    }
  };

  return (
    <>
      <Card className="bg-[var(--color-panel)] mt-6">
        <CardHeader>
          <CardTitle>Tenant profile</CardTitle>
          <CardDescription>
            Changes to slug and status are applied immediately.
          </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">Tenant Group</Label>
            <select
              value={tenantGroupId}
              onChange={(e) => setTenantGroupId(e.target.value)}
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
            >
              <option value="">그룹 없음</option>
              {groupsQuery.data?.items.map((group) => (
                <option key={group.id} value={group.id}>
                  {group.name} ({group.slug})
                </option>
              ))}
            </select>
            <p className="text-xs text-muted-foreground">
              테넌트가 속할 그룹을 지정합니다. 그룹 관리자는 소속 테넌트에 대한
              접근 권한을 가집니다.
            </p>
          </div>
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              Allowed Domains (Comma separated)
            </Label>
            <Input
              value={domains}
              onChange={(e) => setDomains(e.target.value)}
              placeholder="example.com, example.kr"
            />
            <p className="text-xs text-muted-foreground">
              Users with these email domains will be automatically assigned to
              this tenant.
            </p>
          </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="mt-8 flex flex-wrap items-center justify-between gap-3">
        <Button
          variant="outline"
          onClick={handleDelete}
          disabled={deleteMutation.isPending}
        >
          <Trash2 size={16} />
          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}
            >
              Approve Tenant
            </Button>
          )}
          <Button variant="outline" onClick={() => navigate("/tenants")}>
            Cancel
          </Button>
          <Button
            onClick={() => updateMutation.mutate()}
            disabled={
              updateMutation.isPending ||
              tenantQuery.isLoading ||
              name.trim() === ""
            }
          >
            <Save size={16} />
            Save
          </Button>
        </div>
      </div>
    </>
  );
}
