"use client";

import { Quiz } from "@/components/lab-quiz/quiz";
import Markdown from "@/components/markdown/markdown";
import { useUploadImages } from "@/components/pages/writer-tools/hooks";
import { Textarea } from "@/components/ui/textarea";
import type { QuizPart } from "@/lib/api/labs.v2";
import { cn } from "@/lib/utils";
import {
  type SetStateAction,
  startTransition,
  useEffect,
  useRef,
  useState,
} from "react";
import yaml from "yaml";

export function QuizWriter() {
  const [quizYaml, setQuizYaml] = useState(exampleQuiz);
  const [quiz, setQuiz] = useState<QuizPart | undefined>();

  const quizYamlRef = useRef(quizYaml);
  useEffect(() => {
    quizYamlRef.current = quizYaml;
  });

  const handleQuizYamlChange = (action: SetStateAction<string>) => {
    function handleNew(yamlString: string) {
      setQuizYaml(yamlString);
      startTransition(() => {
        try {
          setQuiz({
            type: "quiz",
            title: "",
            public: true,
            content: yaml.parse(yamlString),
          });
        } catch {}
      });
    }

    if (typeof action === "string") {
      handleNew(action);
    } else {
      handleNew(action(quizYamlRef.current));
    }
  };

  useEffect(() => {
    handleQuizYamlChange(quizYaml);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const {
    handlePaste,
    handleDrop,
    handleDragOver,
    handleDragStart,
    handleDragStop,
    draggingOver,
  } = useUploadImages(handleQuizYamlChange);

  return (
    <div className="p-8 h-content">
      <div className="grid grid-cols-2 gap-8 h-full">
        <Textarea
          className={cn(
            "size-full resize-none",
            draggingOver &&
              "selection:bg-transparent caret-transparent ring-2 focus-visible:ring-2"
          )}
          value={quizYaml}
          onChange={(e) => handleQuizYamlChange(e.target.value)}
          onPaste={handlePaste}
          onDragOver={handleDragOver}
          onDragEnter={handleDragStart}
          onDragLeave={handleDragStop}
          onDrop={handleDrop}
        />
        <Markdown className="h-full overflow-y-auto">
          {quiz && <Quiz quiz={quiz} preview />}
        </Markdown>
      </div>
    </div>
  );
}

const exampleQuiz = `title: PingCAP Certified TiDB Practitioner Exam
description: Select the most correct answer.
allow_repeat_submission: true
evaluate_immediately: true
show_correct_answer: false

questions:
  - type: MultipleChoice
    question: Which scenarios listed below are suitable for using TiDB? (Select four items)
    options:
      - id: 1
        text: Online order history data repository for end user inquiry.
        correct: true
      - id: 2
        text: Storage database designed to host a vast amount of large binary files, including images and movies.
      - id: 3
        text: Transaction support for a payment system which requires more than 100,000 QPS.
        correct: true
      - id: 4
        text: Merge multiple sharded databases (schemas) from several MySQL-compatible servers into a single database (schema) under a single TiDB cluster.
        correct: true
      - id: 5
        text: Consolidate various databases (schemas) of distinct applications running on different MySQL-compatible servers into multiple databases (schemas) under a single TiDB cluster.
        correct: true
    explanation: |
      TiDB's architecture is designed for large scale, and is very good at storing and retrieving historical data, compared to single node databases. As a distributed database, TiDB is also very good at handling high concurrent workloads.

      However, TiDB is not designed for storing large binary files, images, and movies; those files should be handled by other object storage services instead of a RDBMS.

  - type: SingleChoice
    question: In TiDB Cloud Starter and Essential, which cluster components are automatically provisioned and managed by the service?
    options:
      - id: 1
        text: TiFlash servers
      - id: 2
        text: TiKV servers
      - id: 3
        text: Placement Driver servers
      - id: 4
        text: Only TiDB servers and TiKV servers
      - id: 5
        text: All of the above
        correct: true
    explanation: |
      In TiDB Cloud Starter and Essential, the configuration of TiFlash servers, TiKV servers, Placement Driver servers, and TiDB servers is managed automatically by the service.

  - type: SingleChoice
    question: In TiDB's storage architecture using row store and Multi Raft Group, what is the fundamental unit used for data sharding and replication?
    options:
      - id: 1
        text: Cell
      - id: 2
        text: Region or TiKV Region
        correct: true
      - id: 3
        text: Block
      - id: 4
        text: RDD
    explanation: |
      In TiDB's storage architecture using row store and Multi Raft Group, the fundamental unit used for data sharding and replication is called Region or TiKV Region.

  - type: SingleChoice
    question: If all TiDB servers (SQL layer) lose power at the same time and their disks are damaged, the data stored in them will be lost.
    options:
      - id: 1
        text: "True"
      - id: 2
        text: "False"
        correct: true
    explanation: |
      The TiDB servers (SQL layer) do NOT store business data. It is stateless. TiKV (row store) is the one responsible for storing business data.

  - type: SingleChoice
    question: Which of the following database access protocols is TiDB Server (SQL layer) compatible with?
    options:
      - id: 1
        text: MySQL
        correct: true
      - id: 2
        text: Oracle
      - id: 3
        text: DynamoDB
      - id: 4
        text: PostgreSQL
    explanation: |
      TiDB is compatible with MySQL protocol.

  - type: MultipleChoice
    question: Which of the following characteristics are unique to TiDB compared to traditional relational database management systems (RDBMS)? (Select two items)
    options:
      - id: 1
        text: Components are decoupled, providing good scalability, both scale-in and scale-out.
        correct: true
      - id: 2
        text: Support ACID, ensuring strong transaction consistency.
      - id: 3
        text: A stateless SQL layer that parses SQL statements and executes them in a distributed manner.
        correct: true
      - id: 4
        text: TiDB cluster must rely on shared storage to function.
    explanation: |
      In TiDB, components are decoupled into the SQL layer (TiDB servers), storage layer (TiKV servers), Placement Driver servers, etc. Each component can be scaled horizontally. However, traditional RDBMS usually runs on a single node, which does not provide good scalability.

      Both TiDB and traditional RDBMS support ACID.

      TiDB has a stateless SQL layer (TiDB server) to parse the SQL statements and execute the statements. Single-node traditional RDBMS does NOT have the feature.

      TiDB cluster does NOT rely on shared storage to function, nor does most traditional RDBMS.

  - type: SingleChoice
    question: Which of the following is responsible for data persistence in TiDB cluster?
    options:
      - id: 1
        text: SQL layer
      - id: 2
        text: MyISAM
      - id: 3
        text: InnoDB
      - id: 4
        text: TiKV (row store)
        correct: true
    explanation: |
      TiKV (row store) is responsible for data persistence in TiDB cluster.

  - type: SingleChoice
    question: The TiDB server (SQL layer) is capable of parsing and generating execution plans for SQL statements.
    options:
      - id: 1
        text: "True"
        correct: true
      - id: 2
        text: "False"
    explanation: |
      TiDB server includes related modules such as parser, logistical optimizer and physical optimizer, to parse and generate execution plans for SQL statements.

  - type: MultipleChoice
    question: Which of the following workloads are certain to benefit from migrating to TiDB or TiDB Cloud?
    options:
      - id: 1
        text: A system operates 24/7 with high IO activity.
        correct: true
      - id: 2
        text: A database will not exceed 10 GB in size and the request is infrequent.
        correct: true
      - id: 3
        text: A database has already been partitioned into multiple shards, with each shard having its own replicas. Due to performance reasons, the database needs to add more shards once again.
        correct: true
      - id: 4
        text: The database has already reached a size of 500 GB and is continuing to expand rapidly.
        correct: true
      - id: 5
        text: A large scale analytical only workload.
    explanation: |
      TiDB, as a distributed database, is able to handle 24/7 high IO throughput, and is capable of handling large volumes of data as a whole. A database with many shards is almost certain to benefit from migrating to TiDB or TiDB Cloud, since there are no shards in TiDB. A huge database, such as the one with more than 500 GB and is growing rapidly, can definitely benefit from migrating to TiDB or TiDB Cloud.

      A small database (for example, less than 10 GB), and has an infrequent request can benefit from migrating to TiDB Cloud Starter. Also, customers may not benefit from migrating to TiDB or TiDB Cloud, if they have an analytical-only workload.

  - type: SingleChoice
    question: Which of the following statements is correct?
    options:
      - id: 1
        text: Multiple TiDB server instances can participate in executing a single SQL query.
      - id: 2
        text: Multiple TiKV server instances can participate in executing a single SQL query.
        correct: true
      - id: 3
        text: Multiple TiFlash server instances can NOT participate in executing a single SQL query.
      - id: 4
        text: No correct answer.
    explanation: |
      A single query will only be sent to one TiDB server. The TiDB server will generate an execution plan, which may involve multiple TiKV servers (using expression push down) and/or TiFlash servers (using massively parallel processing or 'MPP' for short) to finish the job together.

  - type: SingleChoice
    question: What is auto-sharding in TiDB?
    options:
      - id: 1
        text: A method of automatically distributing data across multiple TiKV nodes.
        correct: true
      - id: 2
        text: A feature that helps TiDB automatically scale up or down according to user needs.
      - id: 3
        text: A technique that simplifies the process of data replication for TiDB.
      - id: 4
        text: A way of improving data partitioning in Placement Driver.
    explanation: |
      In TiDB, data is automatically distributed to multiple TiKV nodes.

      Database sharding is a data architecture strategy that increases database performance by splitting up data into chunks and then spreading these chunks "intelligently" across multiple database servers (or database instances). These chunks of data are called shards, while each shard contains a subset of our data. All shards represent the entire set of data, and each row of data exists in only one shard.

      TiDB, as a distributed SQL database, natively supports auto sharding and simplifies scalability and maintenance.

      You may refer to this blog (https://www.pingcap.com/blog/database-sharding-defined) for more comprehensive explanations.

  - type: SingleChoice
    question: What happens when you try to connect to a TiDB Cloud Starter cluster with SSL disabled?
    options:
      - id: 1
        text: The connection succeeds but with a warning message.
      - id: 2
        text: The connection fails with an error because SSL is required for TiDB Cloud Starter clusters.
        correct: true
      - id: 3
        text: The connection automatically falls back to an unencrypted connection.
      - id: 4
        text: The connection succeeds without any issues.
    explanation: |
      TiDB Cloud Starter requires SSL connections for security. Attempting to connect with \`--ssl-mode=DISABLED\` will result in an error: "Connections using insecure transport are prohibited."

  - type: SingleChoice
    question: True or False. Data replication between the two storage layers of TiDB, row store (TiKV) and columnar store (TiFlash), requires the use of a third-party ETL tool.
    options:
      - id: 1
        text: "True"
      - id: 2
        text: "False"
        correct: true
    explanation: |
      Raft protocol is used to manage the data replication. The data replication process is transparent to TiDB users.

  - type: SingleChoice
    question: True or False. TiDB supports strong transactional consistency across tables.
    options:
      - id: 1
        text: "True"
        correct: true
      - id: 2
        text: "False"
    explanation: |
      TiDB supports ACID. "C" stands for strong consistency. (A - Atomicity; I - Isolation; D - Durability)

  - type: SingleChoice
    question: True or False. In a TiDB cluster, the number of TiDB server instances must be equal to the number of TiKV server instances.
    options:
      - id: 1
        text: "True"
      - id: 2
        text: "False"
        correct: true
    explanation: |
      You can have two TiDB server instances and three TiKV server instances in your deployment.

  - type: SingleChoice
    question: Which of the server instances in the TiDB cluster is stateless?
    options:
      - id: 1
        text: Placement Driver server instance
      - id: 2
        text: TiKV server (row store) instance
      - id: 3
        text: TiDB server (SQL layer) instance
        correct: true
      - id: 4
        text: MVCC server instance
    explanation: |
      TiDB Server is stateless - there is no business data stored on TiDB.

  - type: SingleChoice
    question: Which component is considered unnecessary or optional in scenarios that involve only online transactions? Choose the most appropriate answer.
    options:
      - id: 1
        text: Placement Driver server
      - id: 2
        text: TiDB server (SQL layer)
      - id: 3
        text: TiKV server (row store)
      - id: 4
        text: TiFlash server (columnar store)
        correct: true
    explanation: |
      You do NOT have to start the TiFlash server if you have no analytical transactions.

  - type: SingleChoice
    question: Regarding Request Units (RU) in the context of TiDB Cloud, which statement is correct?
    options:
      - id: 1
        text: "Write operations do not consume any RU."
      - id: 2
        text: "Read operations do not consume any RU."
      - id: 3
        text: "TiDB Cloud Starter includes a monthly allocation of free RU."
        correct: true
      - id: 4
        text: "In TiDB Cloud Starter, users can set RU rate limits for specific SQL commands."
    explanation: |
      | RU Type    | Rough Definition                                                                     |
      | ---------- | :----------------------------------------------------------------------------------- |
      | 1 Read RU  | \`0.5 x # of batch PointGet + 0.125 x # of PointGet + # of 64K data + 0.3 x CPU (ms)\` |
      | 1 Write RU | \`(0.5 x # of batch PointGet + 0.5 x # of PointGet + # of 2K data ) x 3\`              |

  - type: MultipleChoice
    question: Which of the following statements are correct regarding the TiKV servers at the row storage layer? (Choose two items)
    options:
      - id: 1
        text: The TiKV server stores data in the form of key-value pairs.
        correct: true
      - id: 2
        text: The database becomes unavailable during the scaling-in and scaling-out process of the TiKV servers.
      - id: 3
        text: The TiKV server ensures the durability of data.
        correct: true
      - id: 4
        text: The TiKV server uses the MySQL storage engine for data storage.
    explanation: |
      TiKV server stores data in key-value pairs. The key-value pairs are replicated to multiple nodes by Raft protocol to ensure the durability of data. TiKV uses RocksDB to persist data to disks. TiKV supports online scaling-in and scaling out.

  - type: SingleChoice
    question: TiDB Cloud clusters support both public and private network connection types.
    options:
      - id: 1
        text: "True"
        correct: true
      - id: 2
        text: "False"
    explanation: |
      TiDB Cloud clusters support both public and private network connection types.

      ![starter-connect-methods.jpg 70%](https://lab-static.pingcap.com/images/2025/11/18/724569d619c6850877608947c662edff50462206.jpg)
`;
