import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { authInstance, cityStore, languageStore, sightsStore } from "@shared";
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import { Button } from "@mui/material";
import { DeleteModal, LanguageSwitcher } from "@widgets";
import { Pencil, Trash2 } from "lucide-react";
import { useNavigate } from "react-router-dom";

function createData(id: number, name: string, city: string) {
  return { id, name, city };
}

const rows = (sights: any[], cities: any[]) => {
  return sights.map((sight) => {
    const city = cities.find((city) => city?.id === sight?.city_id);
    return createData(sight?.id, sight?.name, city?.name ?? "Нет данных");
  });
};

export const SightsTable = observer(() => {
  const navigate = useNavigate();
  const { language } = languageStore;
  const { sights, getSights } = sightsStore;
  const { cities, getCities } = cityStore;
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [rowId, setRowId] = useState<number | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      await getSights();
      await getCities(language);
    };
    fetchData();
  }, [language, getSights, getCities]);

  const handleDelete = async (id: number) => {
    await authInstance.delete(`/sight/${id}`);
    await getSights();
  };

  return (
    <>
      <TableContainer component={Paper}>
        <LanguageSwitcher />
        <div className="flex justify-end p-3 gap-5">
          <Button
            variant="contained"
            color="primary"
            onClick={() => navigate("/sight/create")}
          >
            Создать
          </Button>
        </div>
        <Table sx={{ minWidth: 650 }} aria-label="simple table">
          <TableHead>
            <TableRow>
              <TableCell align="center">Название</TableCell>
              <TableCell align="center">Город</TableCell>
              <TableCell align="center">Действия</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows(sights, cities[language]?.data ?? [])?.map((row) => (
              <TableRow
                key={row?.id}
                sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                className="flex items-center"
              >
                <TableCell
                  sx={{ width: "33%" }}
                  align="center"
                  component="th"
                  scope="row"
                >
                  {row?.name}
                </TableCell>
                <TableCell sx={{ width: "33%" }} align="center">
                  {row?.city}
                </TableCell>
                <TableCell align="center" className="py-3">
                  <div className="flex justify-center items-center gap-3">
                    <button
                      title="Редактировать"
                      className="rounded-md px-3 py-1.5 transition-transform transform hover:scale-105"
                      onClick={() => navigate(`/sight/${row?.id}`)}
                    >
                      <Pencil size={18} className="text-blue-500" />
                    </button>
                    <button
                      title="Удалить"
                      className="rounded-md px-3 py-1.5 transition-transform transform hover:scale-105"
                      onClick={() => {
                        setIsDeleteModalOpen(true);
                        setRowId(row?.id);
                      }}
                    >
                      <Trash2 size={18} className="text-red-500" />
                    </button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
      <DeleteModal
        open={isDeleteModalOpen}
        onDelete={async () => {
          if (rowId) {
            await handleDelete(rowId);
          }
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
        onCancel={() => setIsDeleteModalOpen(false)}
      />
    </>
  );
});
