import { useNavigate } from "react-router-dom";
import { LoadingState } from "../components/data-states";
import { useSSHKeys } from "../hooks/use-ssh-keys";
import { SSHKeyCreateForm } from "../components/features/ssh-keys/SSHKeyCreateForm";
import { SSHKeyList } from "../components/features/ssh-keys/SSHKeyList";

export const SSHKeysPage = () => {
  const navigate = useNavigate();
  const {
    keys,
    status,
    loadKeys,
    newKeyName,
    setNewKeyName,
    generating,
    mutationError,
    signPayloads,
    signatures,
    signing,
    verifyPayloads,
    verifySignatures,
    verifyResults,
    verifying,
    handleGenerate,
    handleDelete,
    copyToClipboard,
    handleSign,
    handleVerify,
    setSignPayloads,
    setVerifyPayloads,
    setVerifySignatures,
  } = useSSHKeys();

  if (status === "loading") return <LoadingState message="Loading SSH keys..." />;

  return (
    <section className="stack">
      <div className="page-header">
        <div>
          <p className="eyebrow">Settings</p>
          <h1>SSH Keys</h1>
        </div>
        <button className="secondary-button" type="button" onClick={() => navigate("/settings")}>
          Back to settings
        </button>
      </div>

      {mutationError && <div className="error">{mutationError}</div>}

      <SSHKeyCreateForm
        newKeyName={newKeyName}
        setNewKeyName={setNewKeyName}
        generating={generating}
        onSubmit={handleGenerate}
      />

      <SSHKeyList
        keys={keys}
        status={status}
        signPayloads={signPayloads}
        signatures={signatures}
        signing={signing}
        verifyPayloads={verifyPayloads}
        verifySignatures={verifySignatures}
        verifyResults={verifyResults}
        verifying={verifying}
        onLoadKeys={loadKeys}
        onDelete={handleDelete}
        onCopy={copyToClipboard}
        onSign={handleSign}
        onVerify={handleVerify}
        onSignPayloadChange={(id, value) =>
          setSignPayloads((prev) => ({ ...prev, [id]: value }))
        }
        onVerifyPayloadChange={(id, value) =>
          setVerifyPayloads((prev) => ({ ...prev, [id]: value }))
        }
        onVerifySignatureChange={(id, value) =>
          setVerifySignatures((prev) => ({ ...prev, [id]: value }))
        }
      />
    </section>
  );
};
