import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input";
import useGroups from "@/hooks/useGroups";
import useUsers from "@/hooks/useUsers";
import {Module} from "@/interfaces";
import {Group, User} from "@/interfaces/user";
import {Disclosure, Transition} from "@headlessui/react";
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
import axios from "axios";
import clsx from "clsx";
import {capitalize} from "lodash";
import {useEffect, useRef, useState} from "react";
import {BsCheck, BsDash, BsPencil, BsPlus, BsTrash} from "react-icons/bs";
import {toast} from "react-toastify";
import Select from "react-select";
import {uuidv4} from "@firebase/util";
import {useFilePicker} from "use-file-picker";
import Modal from "@/components/Modal";

const columnHelper = createColumnHelper<Group>();

interface CreateDialogProps {
	user: User;
	users: User[];
	group?: Group;
	onClose: () => void;
}

const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
	const [name, setName] = useState<string | undefined>(group?.name || undefined);
	const [admin, setAdmin] = useState<string>(group?.admin || user.id);
	const [participants, setParticipants] = useState<string[]>(group?.participants || []);
	const {openFilePicker, filesContent} = useFilePicker({
		accept: ".txt",
		multiple: false,
	});

	useEffect(() => {
		if (filesContent.length > 0) {
			const file = filesContent[0];
			const emails = file.content
				.toLowerCase()
				.split("\n")
				.filter((x) => new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/).test(x));

			if (emails.length === 0) {
				toast.error("Please upload a .txt file containing e-mails, one per line!");
				return;
			}

			const emailUsers = [...new Set(emails)].map((x) => users.find((y) => y.email.toLowerCase() === x)).filter((x) => x !== undefined);
			const filteredUsers = emailUsers.filter(
				(x) =>
					((user.type === "developer" || user.type === "admin" || user.type === "corporate") &&
						(x?.type === "student" || x?.type === "teacher")) ||
					(user.type === "teacher" && x?.type === "student"),
			);

			setParticipants(filteredUsers.filter((x) => !!x).map((x) => x!.id));
			toast.success(
				user.type !== "teacher"
					? "Added all teachers and students found in the file you've provided!"
					: "Added all students found in the file you've provided!",
				{toastId: "upload-success"},
			);
		}
	}, [filesContent, user.type, users]);

	const submit = () => {
		if (name !== group?.name && (name === "Students" || name === "Teachers")) {
			toast.error("That group name is reserved and cannot be used, please enter another one.");
			return;
		}

		(group ? axios.patch : axios.post)(group ? `/api/groups/${group.id}` : "/api/groups", {name, admin, participants})
			.then(() => {
				toast.success(`Group "${name}" ${group ? "edited" : "created"} successfully`);
				return true;
			})
			.catch(() => {
				toast.error("Something went wrong, please try again later!");
				return false;
			})
			.finally(onClose);
	};

	return (
		<div className="flex flex-col gap-12 mt-4 w-full px-4 py-2">
			<div className="flex flex-col gap-8">
				<Input name="name" type="text" label="Name" defaultValue={name} onChange={setName} required disabled={group?.disableEditing} />
				<div className="flex flex-col gap-3 w-full">
					<label className="font-normal text-base text-mti-gray-dim">Participants</label>
					<div className="flex gap-8 w-full">
						<Select
							className="w-full"
							value={participants.map((x) => ({
								value: x,
								label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
							}))}
							placeholder="Participants..."
							defaultValue={participants.map((x) => ({
								value: x,
								label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
							}))}
							options={users
								.filter((x) => (user.type === "teacher" ? x.type === "student" : x.type === "student" || x.type === "teacher"))
								.map((x) => ({value: x.id, label: `${x.email} - ${x.name}`}))}
							onChange={(value) => setParticipants(value.map((x) => x.value))}
							isMulti
							isSearchable
							styles={{
								control: (styles) => ({
									...styles,
									backgroundColor: "white",
									borderRadius: "999px",
									padding: "1rem 1.5rem",
									zIndex: "40",
								}),
							}}
						/>
						{user.type !== "teacher" && (
							<Button className="w-full max-w-[300px]" onClick={openFilePicker} variant="outline">
								{filesContent.length === 0 ? "Upload participants .txt file" : filesContent[0].name}
							</Button>
						)}
					</div>
				</div>
			</div>
			<div className="flex w-full justify-end items-center gap-8 mt-8">
				<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={onClose}>
					Cancel
				</Button>
				<Button className="w-full max-w-[200px]" onClick={submit} disabled={!name}>
					Submit
				</Button>
			</div>
		</div>
	);
};

const filterTypes = ["corporate", "teacher"];

export default function GroupList({user}: {user: User}) {
	const [isCreating, setIsCreating] = useState(false);
	const [editingGroup, setEditingGroup] = useState<Group>();
	const [filterByUser, setFilterByUser] = useState(false);

	const {users} = useUsers();
	const {groups, reload} = useGroups(user && filterTypes.includes(user?.type) ? user.id : undefined);

	useEffect(() => {
		if (user && (user.type === "corporate" || user.type === "teacher")) {
			setFilterByUser(true);
		}
	}, [user]);

	const deleteGroup = (group: Group) => {
		if (!confirm(`Are you sure you want to delete "${group.name}"?`)) return;

		axios
			.delete<{ok: boolean}>(`/api/groups/${group.id}`)
			.then(() => toast.success(`Group "${group.name}" deleted successfully`))
			.catch(() => toast.error("Something went wrong, please try again later!"))
			.finally(reload);
	};

	const defaultColumns = [
		columnHelper.accessor("id", {
			header: "ID",
			cell: (info) => info.getValue(),
		}),
		columnHelper.accessor("name", {
			header: "Name",
			cell: (info) => info.getValue(),
		}),
		columnHelper.accessor("admin", {
			header: "Admin",
			cell: (info) => (
				<div className="tooltip" data-tip={capitalize(users.find((x) => x.id === info.getValue())?.type)}>
					{users.find((x) => x.id === info.getValue())?.name}
				</div>
			),
		}),
		columnHelper.accessor("participants", {
			header: "Participants",
			cell: (info) =>
				info
					.getValue()
					.map((x) => users.find((y) => y.id === x)?.name)
					.join(", "),
		}),
		{
			header: "",
			id: "actions",
			cell: ({row}: {row: {original: Group}}) => {
				return (
					<>
						{user && (user.type === "developer" || user.type === "admin" || user.id === row.original.admin) && (
							<div className="flex gap-2">
								{!row.original.disableEditing && (
									<div data-tip="Edit" className="cursor-pointer tooltip" onClick={() => setEditingGroup(row.original)}>
										<BsPencil className="hover:text-mti-purple-light transition ease-in-out duration-300" />
									</div>
								)}
								{!row.original.disableEditing && (
									<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteGroup(row.original)}>
										<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
									</div>
								)}
							</div>
						)}
					</>
				);
			},
		},
	];

	const table = useReactTable({
		data: groups,
		columns: defaultColumns,
		getCoreRowModel: getCoreRowModel(),
	});

	const closeModal = () => {
		setIsCreating(false);
		setEditingGroup(undefined);
		reload();
	};

	return (
		<div className="w-full h-full rounded-xl">
			<Modal isOpen={isCreating || !!editingGroup} onClose={closeModal} title={editingGroup ? `Editing ${editingGroup.name}` : "New Group"}>
				<CreatePanel
					group={editingGroup}
					user={user}
					onClose={closeModal}
					users={
						user?.type === "corporate" || user?.type === "teacher"
							? users.filter(
									(u) =>
										groups
											.filter((g) => g.admin === user.id)
											.flatMap((g) => g.participants)
											.includes(u.id) || groups.flatMap((g) => g.participants).includes(u.id),
							  )
							: users
					}
				/>
			</Modal>
			<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
				<thead>
					{table.getHeaderGroups().map((headerGroup) => (
						<tr key={headerGroup.id}>
							{headerGroup.headers.map((header) => (
								<th className="py-4" key={header.id}>
									{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
								</th>
							))}
						</tr>
					))}
				</thead>
				<tbody className="px-2">
					{table.getRowModel().rows.map((row) => (
						<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
							{row.getVisibleCells().map((cell) => (
								<td className="px-4 py-2" key={cell.id}>
									{flexRender(cell.column.columnDef.cell, cell.getContext())}
								</td>
							))}
						</tr>
					))}
				</tbody>
			</table>

			<button
				onClick={() => setIsCreating(true)}
				className="w-full py-2 bg-mti-purple-light hover:bg-mti-purple transition ease-in-out duration-300 text-white">
				New Group
			</button>
		</div>
	);
}
