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

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

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

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

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

  useEffect(() => {
    if (tenantQuery.data) {
      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("Are you sure you want to delete this tenant?")) {
      deleteMutation.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">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">
          <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>
    </>
  );
}
