'use client';

import React, { useEffect, useState, useCallback } from "react";
import { motion } from "framer-motion";
import { Container, Row, Col, Card, Nav, Tab, Placeholder } from 'react-bootstrap';
import HeaderTop from "@/components/HeaderTop";
import HeaderSticky from "@/components/HeaderSticky";
import Link from "next/link";
import { useToast } from "@/context/ToastContext";
import { unixToDateTime,excerptFromHtml } from "@/lib/function";

type BlogData = {
  sb_id: number;
  sb_sbt_id: number;
  sb_title: string;
  sb_content: string;
  sb_path: string;
  sb_date: number;
  sb_photo?: string;
  sb_photo_width?: number;
  sb_photo_height?: number;
};
type TypeData = {sbt_id: number;sbt_title: string;};

export default function BlogPage() {
  const { showToast } = useToast();
  const [blogs, setBlogs] = useState<BlogData[]>([]);
  const [latestBlog, setLatestBlog] = useState<BlogData | null>(null);
  const [blogType, setBlogType] = useState<TypeData[]>([]);
  const [isLoading, setLoading] = useState(true);
  const fetchAllBlog = useCallback(async (status?: number) => {
    try {
      const res = await fetch("/api/blog/list", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status })
      });
      const json = await res.json();
      if (res.ok && Array.isArray(json.data)) {
        setBlogs(json.data);
        setLatestBlog(json.data[0]);
      }
    } catch {
      showToast("Blog List: Getting failed..", "danger");
    } finally {
      setLoading(false);
    }
  }, [showToast]);
  const fetchBlogType = useCallback(async () => {
    try {
      const res = await fetch("/api/blog/type");
      const json = await res.json();
      if (res.ok && Array.isArray(json.data)) {
        setBlogType(json.data);
      }
    } catch {
      showToast("Blog Type: Getting failed..", "danger");
    } finally {
      setLoading(false);
    }
  }, [showToast]);  
  useEffect(() => {
    fetchAllBlog(1);
    fetchBlogType();
  }, [fetchAllBlog,fetchBlogType]);
  function getRandomPosts(arr: BlogData[], count: number) {
    const shuffled = [...arr];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled.slice(0, count);
  }
  const filteredPosts = getRandomPosts(blogs, 4);
  return (
    <React.Fragment>
        <section className="section-default">
          <video className="position-absolute top-0 start-0 w-100 h-100 object-fit-cover" poster="https://media.vensysco.com/contact-video.webp" preload="metadata" autoPlay loop muted playsInline>
            <source src="https://media.vensysco.com/contact-video.mp4" type="video/mp4" />
            Your browser does not support the video tag.
          </video>
          <Container className="py-3 py-md-5 position-relative">
              <HeaderTop />
              <HeaderSticky />
              <Row className='flex-fill align-items-end align-items-md-center justify-content-center justify-content-md-start text-center text-md-start my-5'>
                <Col md={5}>
                  <motion.h1 className="display-5 fw-bold" whileInView={{y:[-30,0]}} transition={{duration:1.8}}>
                    Insights & Industry Updates
                  </motion.h1>                    
                </Col>
              </Row>
          </Container>
        </section>        
        {isLoading ? (
        <React.Fragment>
        <Container className="py-3 py-md-5" >                
          <Card className='bg-light flex-md-row align-items-center rounded-4 border-0 shadow-sm'>
            <Card.Body className="flex-fill p-3 p-md-5">
                <motion.h2 className="fs-5">
                  <Placeholder xs={4} bg="secondary" />
                </motion.h2>            
                <motion.h3 className="fs-2 text-danger">
                  <Placeholder xs={12} bg="danger" />
                </motion.h3>
                <motion.p className="fw-bold">
                  <Placeholder xs={12} bg="dark" />
                  <Placeholder xs={10} bg="dark" />
                </motion.p>
                <Row className="g-3 align-items-center justify-content-between">
                  <motion.div className="col">
                    <Placeholder xs={6} bg="danger" />
                  </motion.div>
                  <Col className="text-end">
                    <Placeholder xs={6} bg="secondary" />
                  </Col>
                </Row>
            </Card.Body>
            <Placeholder xs={12} bg="secondary" className="rounded-4 w-md-50" style={{height:"260px"}} />
          </Card>
        </Container>         
        <Container className="py-3 py-md-5">          
          <Tab.Container id="blog-tabs" defaultActiveKey="tab-1">
            <Row>
              <Col md={3}>
                <Nav variant="pills" className="flex-column">
                  {[...Array(6)].map((_, index) => (
                  <motion.div key={index} className="nav-item mb-2">
                    <Nav.Link eventKey={`tab-${index}`}>
                      {index === 1 ? <Placeholder xs={12} bg="light" className="rounded-pill" /> : <Placeholder xs={12} bg="danger" className="rounded-pill" />}
                    </Nav.Link>
                  </motion.div>
                  ))}
                </Nav>
              </Col>
              <Col md={9}>
                <Tab.Content>
                  {[...Array(6)].map((_, index) => (
                    <Tab.Pane key={index} eventKey={`tab-${index}`}>
                      <Row xs={1} sm={2} md={2} className="g-4">
                      {[...Array(4)].map((_, index) => (
                          <Col key={index}>
                            <Card className="h-100 rounded-4 overflow-hidden">
                              <Placeholder xs={12} bg="secondary" className="card-img-top" style={{height:"150px"}} />
                              <Card.Body>
                                <Card.Title>
                                  <Placeholder xs={12} bg="danger" />
                                </Card.Title>
                                <Card.Text className="fw-bold">
                                  <Placeholder xs={12} bg="dark" />
                                  <Placeholder xs={10} bg="dark" />
                                </Card.Text>
                                <Row className="g-3 align-items-center justify-content-between">
                                  <motion.div className="col">
                                    <Placeholder xs={6} bg="danger" />
                                  </motion.div>
                                  <Col className="text-end">
                                    <Placeholder xs={6} bg="secondary" />
                                  </Col>
                                </Row>
                              </Card.Body>
                            </Card>
                          </Col>
                        ))}
                      </Row>
                    </Tab.Pane>
                  ))}
                </Tab.Content>
              </Col>
            </Row>
          </Tab.Container>
        </Container>
        <Container className="py-3 py-md-5">
          <Row xs={1} sm={2} md={2} className="g-4">
          {[...Array(4)].map((_, index) => (
              <Col key={index}>
                <Card className="h-100 rounded-4 overflow-hidden">
                  <Placeholder xs={12} bg="secondary" className="card-img-top" style={{height:"150px"}} />
                  <Card.Body>
                    <Card.Title>
                      <Placeholder xs={12} bg="danger" />
                    </Card.Title>
                    <Card.Text className="fw-bold">
                      <Placeholder xs={12} bg="dark" />
                      <Placeholder xs={10} bg="dark" />
                    </Card.Text>
                    <Row className="g-3 align-items-center justify-content-between">
                      <motion.div className="col">
                        <Placeholder xs={6} bg="danger" />
                      </motion.div>
                      <Col className="text-end">
                        <Placeholder xs={6} bg="secondary" />
                      </Col>
                    </Row>
                  </Card.Body>
                </Card>
              </Col>
            ))}
          </Row>
        </Container>
        </React.Fragment>
        ) : (
        <React.Fragment>
        <Container className="py-3 py-md-5" >
          {latestBlog &&                  
          <Card className='bg-light flex-md-row align-items-center rounded-4 border-0 shadow-sm'>
            <Card.Body className="flex-fill p-3 p-md-5">
                <motion.h2 className="fs-5">Latest Posts</motion.h2>            
                <motion.h3 className="fs-2 text-danger">{latestBlog.sb_title}</motion.h3>
                <motion.p className="fw-bold">{excerptFromHtml(latestBlog.sb_content, 20)}</motion.p>
                <Row className="g-3 align-items-center justify-content-between">
                  <motion.div className="col" whileInView={{x:[100,0]}} transition={{duration:1.8}}>
                    <Link href={`/blog/${latestBlog.sb_path}`} className="link-danger">
                      Read More <i className="bi bi-arrow-right"></i>
                    </Link>
                  </motion.div>
                  <Col className="text-secondary text-end">{unixToDateTime(latestBlog.sb_date,'date')}</Col>
                </Row>
            </Card.Body>
            <motion.img className="img-fluid rounded-4 w-md-50" src={latestBlog.sb_photo} alt={latestBlog.sb_title} width={latestBlog.sb_photo_width} height={latestBlog.sb_photo_height} whileInView={{scale:[1.1,1]}} transition={{duration:2}} />                 
          </Card>}
        </Container>         
        <Container className="py-3 py-md-5">          
          <Tab.Container id="blog-tabs" defaultActiveKey="tab-1">
            <Row>
              <Col md={3}>
                <Nav variant="pills" className="flex-column">
                  {blogType.map((category,index) => (
                  <motion.div key={index} className="nav-item mb-2" whileInView={{y:[20,0]}} transition={{duration:1.8}}>
                    <Nav.Link eventKey={`tab-${index}`}>{category.sbt_title}</Nav.Link>
                  </motion.div>
                  ))}
                </Nav>
              </Col>
              <Col md={9}>
                <Tab.Content>
                  {blogType.map((category,index) => (
                    <Tab.Pane key={index} eventKey={`tab-${index}`}>
                      <Row xs={1} sm={2} md={2} className="g-4">
                      {blogs
                        .filter(post => post.sb_sbt_id === category.sbt_id )
                        .map((post,index) => (
                          <Col key={index}>
                            <Card className="h-100 rounded-4 overflow-hidden">
                              <motion.img className="img-fluid card-img-top" src={post.sb_photo} alt={post.sb_title} width={post.sb_photo_width} height={post.sb_photo_height} whileInView={{scale:[1.2,1]}} transition={{duration:1.6}} />
                              <Card.Body>
                                <Card.Title className="text-danger">{post.sb_title}</Card.Title>
                                <Card.Text className="fw-bold">{excerptFromHtml(post.sb_content, 20)}</Card.Text>
                                <Row className="g-3 align-items-center justify-content-between">
                                  <motion.div className="col" whileInView={{x:[100,0]}} transition={{duration:1.8}}>
                                    <Link href={`/blog/${post.sb_path}`} className="link-danger">Read More <i className="bi bi-arrow-right"></i></Link>
                                  </motion.div>
                                  <Col className="text-secondary text-end">{unixToDateTime(post.sb_date,'date')}</Col>
                                </Row>
                              </Card.Body>
                            </Card>
                          </Col>
                        ))}
                      </Row>
                    </Tab.Pane>
                  ))}
                </Tab.Content>
              </Col>
            </Row>
          </Tab.Container>
        </Container>
        <Container className="py-3 py-md-5">
          <Row xs={1} sm={2} md={2} className="g-4">
          {filteredPosts.map((post,index) => (
              <Col key={index}>
                <Card className="h-100 rounded-4 overflow-hidden">
                  <motion.img className="img-fluid card-img-top" src={post.sb_photo} alt={post.sb_title} width={post.sb_photo_width} height={post.sb_photo_height} whileInView={{scale:[1.2,1]}} transition={{duration:2}} />
                  <Card.Body>
                    <Card.Title className="text-danger">{post.sb_title}</Card.Title>
                    <Card.Text className="fw-bold">{excerptFromHtml(post.sb_content, 20)}</Card.Text>
                    <Row className="g-3 align-items-center justify-content-between">
                      <motion.div className="col" whileInView={{x:[100,0]}} transition={{duration:1.8}}>
                        <Link href={`/blog/${post.sb_path}`} className="link-danger">Read More <i className="bi bi-arrow-right"></i></Link>
                      </motion.div>
                      <Col className="text-secondary text-end">{unixToDateTime(post.sb_date,'date')}</Col>
                    </Row>
                  </Card.Body>
                </Card>
              </Col>
            ))}
          </Row>
        </Container>
        </React.Fragment>
        )}
        <Container className="py-3 py-md-5 text-center">
          <motion.h2 className="display-3 fw-bold text-danger mb-4">
            Need Help Setting Up Your Examination Process?
          </motion.h2>
          <motion.p>Contact our team for consultation and customized solutions.</motion.p>
          <Link href="/contact-us">
            <motion.button className="btn btn-lg btn-outline-danger rounded-pill" whileInView={{y:[100,0]}} transition={{duration:1.8}}>Schedule a Consultation</motion.button>
          </Link>
        </Container>
    </React.Fragment>
  );
}