'use client';

import * as React from 'react';
import NextLink from 'next/link';

import { navigation } from '@/app/_components/Footer';
import {
  DoubleQuoteLeft,
  DoubleQuoteRight,
  UserFace1,
  UserFace2,
  UserFace3,
  UserFace4,
  UserFace5,
  UserFace6,
  UserFace7,
  UserFace8,
  UserFace9,
} from '@/components/Icon';

export default function UserStory() {
  return (
    <>
      <section className="my-8 flex w-full max-w-7xl flex-col items-center px-6 md:px-8">
        <h2 className="pb-4 pt-4 md:pt-8 lg:pt-16 text-center font-bold leading-normal">
          “We build with TiDB”
        </h2>
        <div className="flex justify-center pb-8 text-center text-sm leading-8 text-darkgrey-100">
          <div className="max-w-5xl">
            Tens of thousands of developers and startups are building
            applications with TiDB
          </div>
        </div>
        <div className="flex w-auto flex-wrap items-center gap-4 pb-8">
          {navigation.social.slice(0, 3).map((item) => (
            <NextLink
              key={item.name}
              href={item.href}
              target="_blank"
              className="w-fit text-gray-500 hover:text-gray-400"
            >
              <span className="sr-only">{item.name}</span>
              <item.icon className="h-auto max-h-5 w-5" aria-hidden="true" />
            </NextLink>
          ))}
        </div>
        <PostCardList />
      </section>
    </>
  );
}

const PostCard = (props: {
  title: string;
  name: string;
  content: string | React.ReactNode;
  avatar: (props: React.SVGProps<SVGSVGElement>) => React.ReactNode;
  business: string;
  primaryColor?: string;
  secondaryColor?: string;
}) => {
  return (
    <div
      className="flex w-auto flex-col rounded-3xl p-5 md:max-w-md"
      style={{
        background: `linear-gradient(90deg, rgba(12, 166, 242, 0.075) -1.46%, rgba(10, 173, 196, 0.075) 19.31%, rgba(0, 111, 194, 0.075) 30.37%, rgba(12, 166, 242, 0.075) 40.95%, rgba(1, 236, 176, 0.075) 95.03%, rgba(0, 242, 97, 0.075) 100%)`,
      }}
    >
      <div className="flex flex-row justify-between pb-4">
        <div className="flex flex-row gap-6">
          <props.avatar className="inline-block h-16 w-16 rounded-full border border-darkgrey-500" />
          <div className="flex flex-col justify-around text-xs font-bold">
            <div>@{props.name}</div>
            <div>{props.title}</div>
            <div>
              <span
                className={`inline-flex items-center rounded-full bg-[${props.secondaryColor}] bg-opacity-40 px-2 py-1 font-medium leading-none text-[${props.primaryColor}]`}
                style={{
                  backgroundColor: props.secondaryColor + '36',
                  color: props.primaryColor,
                }}
              >
                {props.business}
              </span>
            </div>
          </div>
        </div>
      </div>
      <div className="whitespace-break-spaces text-sm italic leading-8">
        <DoubleQuoteLeft className="-mt-4 mr-4 inline h-4 w-auto" />
        {props.content}
        <DoubleQuoteRight className="-mb-2 ml-4 inline h-4 w-auto" />
      </div>
    </div>
  );
};

const PostCardList = (props: any) => {
  const [postsMemo, maxColPosts] = React.useMemo(() => {
    const postsArray = generate2DArray(sortedMockPosts, 3);
    const maxColPosts = Math.max(...postsArray.map((posts) => posts.length));

    return [postsArray, maxColPosts];
  }, []);

  return (
    <>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
        {postsMemo.map((posts: any, postsIdx: number) => (
          <div
            key={postsIdx}
            className={
              postsIdx + 1 >= posts.length
                ? 'grid gap-4 md:col-span-2 md:grid-cols-2 lg:col-span-1 lg:grid-cols-1'
                : 'grid gap-4'
            }
          >
            {posts.map((post: any, postIdx: number) => (
              <PostCard
                key={post.id}
                title={post.title}
                name={post.name}
                content={post.content}
                business={post.business}
                avatar={getFaceById(post.id - 1, faceList).icon}
                primaryColor={getFaceById(post.id - 1, faceList).primaryColor}
                secondaryColor={
                  getFaceById(post.id - 1, faceList).secondaryColor
                }
              />
            ))}
            {posts.length < maxColPosts &&
              new Array(maxColPosts - posts.length)
                .fill(0)
                .map((_, idx) => (
                  <div
                    key={`${postsIdx}-${idx}`}
                    className="hidden md:h-48 lg:block"
                  />
                ))}
          </div>
        ))}
      </div>
    </>
  );
};

const faceList = [
  {
    id: 1,
    icon: UserFace1,
    primaryColor: '#11A6ED',
    secondaryColor: '#3BBDFB',
  },
  {
    id: 2,
    icon: UserFace2,
    primaryColor: '#FFE790',
    secondaryColor: '#D6B12C',
  },
  {
    id: 3,
    icon: UserFace3,
    primaryColor: '#52CC7A',
    secondaryColor: '#C1FF90',
  },
  {
    id: 4,
    icon: UserFace4,
    primaryColor: '#DD7514',
    secondaryColor: '#E3A152',
  },
  {
    id: 5,
    icon: UserFace5,
    primaryColor: '#2E6BE5',
    secondaryColor: '#9990FF',
  },
  {
    id: 6,
    icon: UserFace6,
    primaryColor: '#1CCFBC',
    secondaryColor: '#56B286',
  },
  {
    id: 7,
    icon: UserFace7,
    primaryColor: '#FF8888',
    secondaryColor: '#FF9090',
  },
  {
    id: 8,
    icon: UserFace8,
    primaryColor: '#AA95FF',
    secondaryColor: '#C8BAF0',
  },
  {
    id: 9,
    icon: UserFace9,
    primaryColor: '#A9C941',
    secondaryColor: '#A9C941',
  },
];

const getFaceById = (id: number, faces: (typeof faceList)[0][]) => {
  const faceListLength = faces.length;
  const remainder = id % faceListLength;
  // const quotient = Math.floor(id / faceListLength);
  const face = faces[remainder];
  return face;
};

const POSTS = [
  {
    id: 1,
    name: 'Kentaro Kitagawa',
    title: 'Senior DBA, LINE Corporation',
    content: (
      <>
        Scale-in and scale-out in a cluster configuration is also{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[0].primaryColor,
          }}
        >
          easy
        </b>
        , and the ecosystem is very rich, with operation monitoring tools such
        as Grafana being able to be installed immediately with the installation
        command (TiUP).
      </>
    ),
    business: 'Internet',
  },
  {
    id: 2,
    name: 'Thomas Yu',
    title: 'Founder, KNN3 Networks',
    content: (
      <>
        TiDB Serverless is especially beneficial for experimental or early-stage
        features. It&apos;s{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[1].primaryColor,
          }}
        >
          cost-effective
        </b>{' '}
        for startups, scalable, and development-friendly.
      </>
    ),
    business: 'Web 3',
  },
  {
    id: 3,
    name: 'Sky Dong',
    title: 'Founding Engineer, Chaintool',
    content: (
      <>
        The ease and comfort of getting started are paramount for us, and the{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[2].primaryColor,
          }}
        >
          fully managed
        </b>{' '}
        operations of TiDB Serverless allow us to focus more on our core
        business, ensuring that our development resources are utilized where
        they matter most.
      </>
    ),
    business: 'Web 3',
  },
  {
    id: 4,
    name: 'Boris Savelev',
    title: 'SRE Manager, Bolt',
    content: (
      <>
        In the following years, we will definitely migrate more clusters from
        MySQL to TiDB, use TiCDC to set up multi-region clusters on AWS for
        failover, and try TiFlash for instant analytical{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[3].primaryColor,
          }}
        >
          queries
        </b>
        .
      </>
    ),
    business: 'Logistics',
  },
  {
    id: 5,
    name: 'Henry Qin',
    title: 'Software Engineer',
    content: (
      <>
        TiDB&apos;s architecture, sort of a SQL layer on top of a key value
        store, was{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[4].primaryColor,
          }}
        >
          more scalable
        </b>{' '}
        and more likely to cause fewer problems down the line. With TiDB, we
        don&apos;t need to worry about cross-charge transactions. That&apos;s
        huge.
      </>
    ),
    business: 'FinTech',
  },
  {
    id: 6,
    name: 'Kaustav Chakravorty',
    title: 'Senior Architect, Flipkart',
    content: (
      <>
        The NO.1 benefit is{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[5].primaryColor,
          }}
        >
          simplicity
        </b>
        . With TiDB, our applications can retain their SQL data model and the
        ACID guarantees. We don&apos;t have to implement any kind of sharding
        logic, and the database management becomes simpler too.
      </>
    ),
    business: 'E-Commerce',
  },
  {
    id: 7,
    name: 'Godwin',
    title: 'Project Owner of AI-Mon',
    content: (
      <>
        With TiDB Serverless, setting up a database is as easy as clicking a
        button. It handles analytics{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[6].primaryColor,
          }}
        >
          seamlessly
        </b>
        , without the need for manual scaling.
      </>
    ),
    business: 'AI App',
  },
  {
    id: 8,
    name: 'Eliotte',
    title: 'Hackathon AI Track Winner, Quizmefy',
    content: (
      <>
        We heavily utilized TiDB&apos;s serverless feature to power our backend.
        This allowed us to scale our backend to handle thousands of requests per
        second effortlessly while keeping{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[7].primaryColor,
          }}
        >
          costs low
        </b>
        , as we only pay for what we use.
      </>
    ),
    business: 'AI App',
  },
  {
    id: 9,
    name: 'Yaohui Sun',
    title: ' Data Platform Lead, Chainbase',
    content: (
      <>
        TiDB Serverless&apos;s{' '}
        <b
          className={`font-bold`}
          style={{
            color: faceList[8].primaryColor,
          }}
        >
          automatic scaling
        </b>{' '}
        capabilities allow us to swiftly scale up to meet performance demands
        and scale down during quieter periods for optimizing costs.
      </>
    ),
    business: 'Web 3',
  },
];

const sortedMockPosts = POSTS.sort((a, b) => a.name.localeCompare(b.name));

function generate2DArray(sortedArray: any[], divisor: number) {
  const dividend = sortedArray.length;
  const quotient = Math.floor(dividend / divisor);
  const remainder = dividend % divisor;

  const array = [];
  let startIndex = 0;

  for (let i = 0; i < divisor; i++) {
    const subArrayLength = quotient + (i < remainder ? 1 : 0);
    const subArray = sortedArray.slice(startIndex, startIndex + subArrayLength);
    array.push(subArray);
    startIndex += subArrayLength;
  }

  return array;
}
