import { useState, useId, type FormEvent } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import AvatarUploader from "@/components/ui/avatar-uploader";

function SettingsSkeleton({ rows = 3 }: { rows?: number }) {
  return (
    <div className="space-y-4" aria-busy="true" aria-label="Loading settings">
      {Array.from({ length: rows }).map((_, i) => (
        <div className="h-9 animate-pulse rounded-lg bg-muted/50" key={i} />
      ))}
    </div>
  );
}

export default function GeneralTab({ projectName }: { projectName: string }) {
  const qc = useQueryClient();
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const nameId = useId();
  const descId = useId();
  const avatarId = useId();

  const { data: workspace, isLoading } = useQuery({
    queryKey: ["workspace", projectName],
    queryFn: async () => {
      const res = await client.workspaceGetWorkspace(projectName);
      return res.data;
    },
    retry: false,
  });

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError("");
    setSubmitting(true);

    const form = new FormData(event.currentTarget);
    const name = (form.get("name") as string) || null;
    const description = (form.get("description") as string) || null;
    const avatarUrl = (form.get("avatar_url") as string) || null;

    try {
      await client.workspaceUpdateWorkspace(projectName, {
        name,
        description,
        avatar_url: avatarUrl,
      });
      await qc.invalidateQueries({ queryKey: ["workspace", projectName] });
      await qc.invalidateQueries({ queryKey: ["workspace", "my"] });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to update workspace.");
    } finally {
      setSubmitting(false);
    }
  };

  if (isLoading) return <SettingsSkeleton />;

  return (
    <form className="max-w-2xl space-y-8" onSubmit={(e) => void handleSubmit(e)}>
      {/* Identity card */}
      <div className="rounded-xl border border-border bg-card p-6 space-y-5">
        <div>
          <h2 className="text-sm font-semibold text-foreground mb-1">Workspace identity</h2>
          <p className="text-xs text-muted-foreground">These details identify your workspace across the platform.</p>
        </div>

        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium text-foreground" htmlFor={nameId}>Name</label>
            <Input className="mt-1 h-9 text-sm" defaultValue={workspace?.name ?? ""} id={nameId} name="name" />
            <p className="mt-1 text-xs text-muted-foreground">Changing the name will also change the workspace URL.</p>
          </div>

          <div>
            <label className="text-sm font-medium text-foreground" htmlFor={descId}>
              Description <span className="font-normal text-muted-foreground">— optional</span>
            </label>
            <Textarea
              className="mt-1 min-h-[72px] text-sm"
              defaultValue={workspace?.description ?? ""}
              id={descId}
              name="description"
              placeholder="A brief description of the workspace"
            />
          </div>

          <div>
            <label className="text-sm font-medium text-foreground" htmlFor={avatarId}>
              Avatar <span className="font-normal text-muted-foreground">— optional</span>
            </label>
            <div className="mt-1">
              <AvatarUploader
                currentUrl={workspace?.avatar_url}
                label="Workspace avatar"
                onUploaded={() => {
                  qc.invalidateQueries({ queryKey: ["workspace", projectName] });
                  qc.invalidateQueries({ queryKey: ["workspace", "my"] });
                }}
                uploadEndpoint={`/api/v1/workspace/${projectName}/avatar`}
              />
            </div>
          </div>
        </div>
      </div>

      {error && <p className="text-sm text-destructive bg-destructive/10 rounded-lg px-4 py-3" role="alert">{error}</p>}

      <div className="flex items-center gap-3">
        <Button className="h-10 px-5 text-sm" disabled={submitting} type="submit">
          {submitting ? "Saving..." : "Save changes"}
        </Button>
        {submitting && <span className="text-xs text-muted-foreground">Updating workspace...</span>}
      </div>
    </form>
  );
}
