import { useState } from "preact/hooks";
import Input from "../components/form/Input.tsx";
import Button from "../components/form/Button.tsx";
import ThemeToggle from "./ThemeToggle.tsx";

interface SharePasswordFormProps {
  id: string;
  title: string;
}

export default function SharePasswordFrame(props: SharePasswordFormProps) {
  const [password, setPassword] = useState("");
  const [error, setError] = useState(false);

  const handleSubmit = async () => {
    if (!password) {
      setError(true);
      return;
    }
    const resp = await fetch("/api/share/verify", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: props.id, password }),
    });
    const respJson = await resp.json();
    if (respJson.success) {
      location.reload();
    } else {
      setError(true);
    }
  };

  return (
    <div className="flex flex-col items-center justify-center h-full">
      <div className="absolute top-4 right-4">
        <ThemeToggle />
      </div>
      <div className="w-[320px] max-w-[90%]">
        <h2 className="text-xl font-medium mb-1 text-center">{props.title}</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-6 text-center">
          This post is password protected.
        </p>
        <Input
          type="password"
          placeholder="Enter password"
          error={error}
          value={password}
          onInput={(e) => {
            setError(false);
            setPassword((e.target as HTMLInputElement).value);
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") handleSubmit();
          }}
        />
        <Button
          type="button"
          variant="primary"
          className="w-full mt-3"
          onClick={handleSubmit}
        >
          View Post
        </Button>
      </div>
    </div>
  );
}
