import { useState, useId, type FormEvent } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Check, X } from "lucide-react";

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

export default function JoinTab({ projectName }: { projectName: string }) {
  const qc = useQueryClient();
  const qId = useId();
  const aId = useId();
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

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

  const { data: applies = [], isLoading: loadingApplies } = useQuery({
    queryKey: ["workspace", projectName, "join-applies"],
    queryFn: async () => {
      const res = await client.workspaceListJoinApplies(projectName, { status: "pending" });
      return res.data;
    },
    retry: false,
  });

  const [enabled, setEnabled] = useState(strategy?.enabled ?? false);
  const [requireApproval, setRequireApproval] = useState(strategy?.require_approval ?? true);
  const [requireQuestion, setRequireQuestion] = useState(strategy?.require_question ?? false);
  const [question, setQuestion] = useState(strategy?.question ?? "");

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

    const form = new FormData(event.currentTarget);
    const answer = (form.get("answer") as string) || null;

    try {
      await client.workspaceUpdateJoinStrategy(projectName, {
        enabled,
        require_approval: requireApproval,
        require_question: requireQuestion,
        question: requireQuestion ? question : null,
        answer,
      });
      await qc.invalidateQueries({ queryKey: ["workspace", projectName, "join-strategy"] });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to update join strategy.");
    } finally {
      setSubmitting(false);
    }
  };

  const approveApply = useMutation({
    mutationFn: async ({ username, approved }: { username: string; approved: boolean }) => {
      await client.workspaceApproveJoin(projectName, username, { approved, reason: null });
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["workspace", projectName, "join-applies"] }),
  });

  if (isLoading) return <FormSkeleton />;

  return (
    <div className="max-w-2xl space-y-8">
      {/* Join strategy card */}
      <div className="rounded-xl border border-border bg-card p-6">
        <div className="mb-6">
          <h2 className="text-sm font-semibold text-foreground mb-1">Join settings</h2>
          <p className="text-xs text-muted-foreground">Control how users can join this workspace.</p>
        </div>

        <form className="space-y-6" onSubmit={(e) => void handleSubmit(e)}>
          {/* Enable toggle */}
          <label className="flex items-start gap-3 cursor-pointer">
            <input
              checked={enabled}
              className="mt-0.5 size-4 rounded border-border accent-primary"
              onChange={(e) => setEnabled(e.target.checked)}
              type="checkbox"
            />
            <div>
              <span className="text-sm font-medium text-foreground">Enable public join</span>
              <p className="text-xs text-muted-foreground">When enabled, users can request to join this workspace.</p>
            </div>
          </label>

          {enabled && (
            <div className="space-y-5 border-t border-border pt-5">
              {/* Require approval */}
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                  checked={requireApproval}
                  className="mt-0.5 size-4 rounded border-border accent-primary"
                  onChange={(e) => setRequireApproval(e.target.checked)}
                  type="checkbox"
                />
                <div>
                  <span className="text-sm font-medium text-foreground">Require admin approval</span>
                  <p className="text-xs text-muted-foreground">Workspace admins must approve join requests.</p>
                </div>
              </label>

              {/* Require question */}
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                  checked={requireQuestion}
                  className="mt-0.5 size-4 rounded border-border accent-primary"
                  onChange={(e) => setRequireQuestion(e.target.checked)}
                  type="checkbox"
                />
                <div>
                  <span className="text-sm font-medium text-foreground">Require answer to question</span>
                  <p className="text-xs text-muted-foreground">Users must answer a question when requesting to join.</p>
                </div>
              </label>

              {requireQuestion && (
                <>
                  <div>
                    <label className="text-sm font-medium text-foreground" htmlFor={qId}>Question</label>
                    <Input
                      className="mt-2 h-10 text-sm"
                      id={qId}
                      name="question"
                      onChange={(e) => setQuestion(e.target.value)}
                      placeholder="e.g. Why do you want to join?"
                      value={question}
                    />
                  </div>

                  {strategy?.has_answer && (
                    <div>
                      <label className="text-sm font-medium text-foreground" htmlFor={aId}>
                        Expected answer <span className="font-normal text-muted-foreground">— optional</span>
                      </label>
                      <Input
                        className="mt-2 h-10 text-sm"
                        id={aId}
                        name="answer"
                        placeholder="Answer that auto-approves requests"
                      />
                    </div>
                  )}
                </>
              )}
            </div>
          )}

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

          <Button className="h-10 px-5 text-sm" disabled={submitting} type="submit">
            {submitting ? "Saving..." : "Save changes"}
          </Button>
        </form>
      </div>

      {/* Pending requests card */}
      {enabled && requireApproval && (
        <div className="rounded-xl border border-border bg-card overflow-hidden">
          <div className="border-b border-border px-5 py-3">
            <h2 className="text-sm font-semibold text-foreground">
              Pending join requests
              {applies.length > 0 && (
                <span className="ml-2 font-normal text-muted-foreground">({applies.length})</span>
              )}
            </h2>
          </div>

          {loadingApplies ? (
            <div className="px-5 py-3 space-y-3">
              {Array.from({ length: 2 }).map((_, i) => (
                <div className="h-10 animate-pulse rounded-lg bg-muted/50" key={i} />
              ))}
            </div>
          ) : applies.length > 0 ? (
            applies.map((apply) => (
              <div
                className="flex items-center gap-3 border-b border-border/60 px-5 py-3 last:border-b-0 transition-colors hover:bg-muted/30"
                key={apply.username}
              >
                <div className="min-w-0 flex-1">
                  <span className="text-sm font-medium text-foreground">{apply.username}</span>
                  {apply.message && (
                    <p className="mt-0.5 truncate text-xs text-muted-foreground">{apply.message}</p>
                  )}
                </div>
                <span className="shrink-0 text-xs text-muted-foreground">
                  {new Date(apply.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                </span>
                <div className="flex shrink-0 items-center gap-2">
                  <Button
                    aria-label={`Approve ${apply.username}`}
                    className="h-8 px-3 text-xs"
                    onClick={() => approveApply.mutate({ username: apply.username, approved: true })}
                    size="sm"
                    type="button"
                  >
                    <Check aria-hidden="true" className="mr-1 size-3.5" /> Approve
                  </Button>
                  <Button
                    aria-label={`Reject ${apply.username}`}
                    className="h-8 px-3 text-xs"
                    onClick={() => approveApply.mutate({ username: apply.username, approved: false })}
                    size="sm"
                    type="button"
                    variant="outline"
                  >
                    <X aria-hidden="true" className="mr-1 size-3.5" /> Reject
                  </Button>
                </div>
              </div>
            ))
          ) : (
            <div className="py-16 text-center">
              <p className="text-sm text-muted-foreground">No pending requests</p>
              <p className="mt-1 text-xs text-muted-foreground/60">New join requests will appear here.</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
