import { useState, useEffect, useCallback } from "react";

import {
	getEmailConfigsApi,
	createEmailConfigApi,
	updateEmailConfigApi,
	deleteEmailConfigApi,
} from "@/api/email";

import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

import {
	Dialog,
	DialogContent,
	DialogHeader,
	DialogTitle,
	DialogFooter,
} from "@/components/ui/dialog";

import { Loader2, Plus, Pencil, Trash, RefreshCw } from "lucide-react";

export default function EmailPage() {
	const [emails, setEmails] = useState<any[]>([]);
	const [loading, setLoading] = useState(true);

	const [openModal, setOpenModal] = useState(false);
	const [editing, setEditing] = useState<any>(null);

	const [searchText, setSearchText] = useState("");

	const [form, setForm] = useState({
		name: "",
		email: "",
		type: "APPOINTMENT",
		isActive: true,
	});

	const fetchAll = useCallback(async () => {
		setLoading(true);
		try {
			const res = await getEmailConfigsApi();
			setEmails(res?.data || []);
		} catch (err) {
			console.error(err);
		} finally {
			setLoading(false);
		}
	}, []);

	useEffect(() => {
		fetchAll();
	}, [fetchAll]);

	const filtered = emails.filter(
		(e) =>
			e.email.toLowerCase().includes(searchText.toLowerCase()) ||
			e.name.toLowerCase().includes(searchText.toLowerCase()),
	);

	function handleChange(e: any) {
		setForm({ ...form, [e.target.name]: e.target.value });
	}

	function openAdd() {
		setEditing(null);
		setForm({
			name: "",
			email: "",
			type: "APPOINTMENT",
			isActive: true,
		});
		setOpenModal(true);
	}

	function openEdit(item: any) {
		setEditing(item);
		setForm(item);
		setOpenModal(true);
	}

	async function handleSubmit() {
		try {
			if (editing) {
				await updateEmailConfigApi(editing.id, form);
			} else {
				await createEmailConfigApi(form);
			}

			setOpenModal(false);
			fetchAll();
		} catch (err) {
			console.error(err);
		}
	}

	async function handleDelete(id: number) {
		if (!confirm("Delete email config?")) return;
		await deleteEmailConfigApi(id);
		fetchAll();
	}

	return (
		<div className="p-6 space-y-6">
			<div className="flex justify-between items-center flex-wrap gap-3">
				<h1 className="text-2xl font-bold">Email Config</h1>

				<div className="flex gap-2 flex-wrap">
					<Input
						placeholder="Search..."
						value={searchText}
						onChange={(e) => setSearchText(e.target.value)}
						className="w-[200px]"
					/>

					<Button variant="outline" onClick={fetchAll}>
						<RefreshCw className="mr-2 h-4 w-4" />
						Refresh
					</Button>

					<Button onClick={openAdd}>
						<Plus className="mr-2 h-4 w-4" />
						Add Email
					</Button>
				</div>
			</div>

			<Card>
				<CardHeader>
					<CardTitle>Email List</CardTitle>
				</CardHeader>

				<CardContent>
					<Table>
						<TableHeader>
							<TableRow>
								<TableHead>ID</TableHead>
								<TableHead>Name</TableHead>
								<TableHead>Email</TableHead>
								<TableHead>Type</TableHead>
								<TableHead>Status</TableHead>
								<TableHead>Actions</TableHead>
							</TableRow>
						</TableHeader>

						<TableBody>
							{loading ? (
								<TableRow>
									<TableCell colSpan={6} className="text-center">
										<Loader2 className="animate-spin mx-auto" />
									</TableCell>
								</TableRow>
							) : filtered.length === 0 ? (
								<TableRow>
									<TableCell colSpan={6} className="text-center">
										No data
									</TableCell>
								</TableRow>
							) : (
								filtered.map((item) => (
									<TableRow key={item.id}>
										<TableCell>{item.id}</TableCell>
										<TableCell>{item.name}</TableCell>
										<TableCell>{item.email}</TableCell>
										<TableCell>{item.type}</TableCell>
										<TableCell>
											{item.isActive ? "Active" : "Inactive"}
										</TableCell>

										<TableCell className="flex gap-2">
											<Button
												size="sm"
												variant="outline"
												onClick={() => openEdit(item)}>
												<Pencil className="h-4 w-4" />
											</Button>

											<Button
												size="sm"
												variant="destructive"
												onClick={() => handleDelete(item.id)}>
												<Trash className="h-4 w-4" />
											</Button>
										</TableCell>
									</TableRow>
								))
							)}
						</TableBody>
					</Table>
				</CardContent>
			</Card>

			<Dialog open={openModal} onOpenChange={setOpenModal}>
				<DialogContent>
					<DialogHeader>
						<DialogTitle>{editing ? "Edit Email" : "Add Email"}</DialogTitle>
					</DialogHeader>

					<div className="space-y-4">
						<Input
							name="name"
							placeholder="Name"
							value={form.name}
							onChange={handleChange}
						/>

						<Input
							name="email"
							placeholder="Email"
							value={form.email}
							onChange={handleChange}
						/>

						<select
							name="type"
							value={form.type}
							onChange={handleChange}
							className="border rounded px-2 py-2 w-full">
							<option value="APPOINTMENT">APPOINTMENT</option>
							<option value="CANDIDATE">CANDIDATE</option>
							<option value="ACADEMICS">ACADEMICS</option>
						</select>

						<select
							name="isActive"
							value={form.isActive ? "true" : "false"}
							onChange={(e) =>
								setForm({
									...form,
									isActive: e.target.value === "true",
								})
							}
							className="border rounded px-2 py-2 w-full">
							<option value="true">Active</option>
							<option value="false">Inactive</option>
						</select>
					</div>

					<DialogFooter>
						<Button variant="outline" onClick={() => setOpenModal(false)}>
							Cancel
						</Button>
						<Button onClick={handleSubmit}>
							{editing ? "Update" : "Create"}
						</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>
		</div>
	);
}
