import { Avatar, Card, List, Skeleton, Space, Switch, Button } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { LayoutActions } from "../store/layout";
import { RecipeActions } from "../store/recipe";
import { useNavigate, useLocation } from "react-router-dom";
import { BreadCrumbActions } from "../store/breadcrumb";
import { Link } from "react-router-dom";

const Layout = ({ recipes }) => {
  const layout = useSelector((state) => state.layout.layout);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const handleLayoutChange = (checked) => {
    dispatch(LayoutActions.updateLayout(checked ? "list" : "grid"));
  };
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);

  // Access query parameters using the useParams hook
  const query = searchParams.get("query");
  const handleClick = (item) => {
    dispatch(RecipeActions.updateRecipe(item));
    const bread = [
      {
        title: <Link to="/">Home</Link>,
      },
      {
        title: <Link to={`/recipes?query=${query}`}>{query}</Link>,
      },
      {
        title: item.name,
      },
    ];

    dispatch(BreadCrumbActions.updateBreadCrumb(bread));
    navigate(`/recipe/${item.id}`);
  };
  if (layout === "grid") {
    return (
      <>
        <Space direction="vertical">
          <Switch
            checkedChildren="List"
            unCheckedChildren="Grid"
            defaultChecked
            onChange={handleLayoutChange}
          />
        </Space>
        <List
          grid={{ gutter: 16, column: 4 }}
          dataSource={recipes}
          renderItem={(item) => (
            <List.Item>
              <Card
                title={
                  <Button onClick={() => handleClick(item)}>{item.name}</Button>
                }
              >
                {item.description}
              </Card>
            </List.Item>
          )}
        />
      </>
    );
  }
  return (
    <>
      <Space direction="vertical">
        <Switch
          checkedChildren="List"
          unCheckedChildren="Grid"
          defaultChecked
          onChange={handleLayoutChange}
        />
      </Space>
      <List
        className="demo-loadmore-list"
        loading={false}
        itemLayout="horizontal"
        dataSource={recipes}
        renderItem={(item) => (
          <List.Item>
            <Skeleton avatar title={false} loading={false} active>
              <List.Item.Meta
                avatar={<Avatar src={item.thumbnail_url} />}
                title={
                  <Button onClick={() => handleClick(item)}>{item.name}</Button>
                }
                description={item.description}
              />
            </Skeleton>
          </List.Item>
        )}
      />
    </>
  );
};

export default Layout;