"use client";

import {
	Badge,
	Button,
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
	Input,
	Label,
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@mdxui/primitives";
import { cn } from "@mdxui/primitives/lib/utils";
import { format } from "date-fns";
import {
	Copy,
	ExternalLink,
	Link as LinkIcon,
	Trash2,
	TrendingUp,
} from "lucide-react";
import * as React from "react";
import { toast } from "sonner";
import type { LinkShortenerProps, ShortenedLink } from "./types";

function generateShortCode(length: number = 6): string {
	const characters =
		"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	let result = "";
	for (let i = 0; i < length; i++) {
		result += characters.charAt(Math.floor(Math.random() * characters.length));
	}
	return result;
}

function isValidUrl(url: string): boolean {
	try {
		new URL(url);
		return true;
	} catch {
		return false;
	}
}

export function LinkShortener({
	baseUrl = typeof window !== "undefined"
		? window.location.origin
		: "https://example.com.ai",
	onCreate,
	onCopy,
	onDelete,
	links: externalLinks = [],
	showLinkList = true,
	maxShortCodeLength = 20,
	className,
}: LinkShortenerProps) {
	const [originalUrl, setOriginalUrl] = React.useState("");
	const [customCode, setCustomCode] = React.useState("");
	const [title, setTitle] = React.useState("");
	const [isCreating, setIsCreating] = React.useState(false);
	const [localLinks, setLocalLinks] = React.useState<ShortenedLink[]>([]);

	const links = externalLinks.length > 0 ? externalLinks : localLinks;

	const handleCreate = async () => {
		if (!originalUrl.trim()) {
			toast.error("Please enter a URL to shorten");
			return;
		}

		if (!isValidUrl(originalUrl)) {
			toast.error("Please enter a valid URL");
			return;
		}

		const shortCode = customCode.trim() || generateShortCode();

		if (shortCode.length > maxShortCodeLength) {
			toast.error(
				`Short code must be ${maxShortCodeLength} characters or less`,
			);
			return;
		}

		// Check if short code already exists
		if (links.some((link) => link.shortCode === shortCode)) {
			toast.error("This short code is already in use");
			return;
		}

		setIsCreating(true);

		const newLink: ShortenedLink = {
			id: crypto.randomUUID(),
			originalUrl: originalUrl.trim(),
			shortCode,
			shortUrl: `${baseUrl}/${shortCode}`,
			title: title.trim() || undefined,
			clicks: 0,
			createdAt: new Date(),
		};

		try {
			await onCreate?.(newLink);

			if (externalLinks.length === 0) {
				setLocalLinks((prev) => [newLink, ...prev]);
			}

			setOriginalUrl("");
			setCustomCode("");
			setTitle("");
			toast.success("Link shortened successfully!");
		} catch (error) {
			toast.error("Failed to create shortened link");
		} finally {
			setIsCreating(false);
		}
	};

	const handleCopy = (link: ShortenedLink) => {
		navigator.clipboard.writeText(link.shortUrl);
		toast.success("Link copied to clipboard!");
		onCopy?.(link);
	};

	const handleDelete = async (linkId: string) => {
		try {
			await onDelete?.(linkId);

			if (externalLinks.length === 0) {
				setLocalLinks((prev) => prev.filter((link) => link.id !== linkId));
			}

			toast.success("Link deleted");
		} catch (error) {
			toast.error("Failed to delete link");
		}
	};

	return (
		<div className={cn("space-y-6", className)}>
			<Card>
				<CardHeader>
					<CardTitle className="flex items-center gap-2">
						<LinkIcon className="size-5" />
						Shorten a Link
					</CardTitle>
					<CardDescription>
						Create a shortened URL that's easy to share
					</CardDescription>
				</CardHeader>
				<CardContent className="space-y-4">
					<div className="space-y-2">
						<Label htmlFor="original-url">Original URL</Label>
						<Input
							id="original-url"
							type="url"
							placeholder="https://example.com.ai/very/long/url"
							value={originalUrl}
							onChange={(e) => setOriginalUrl(e.target.value)}
							onKeyDown={(e) => {
								if (e.key === "Enter") {
									handleCreate();
								}
							}}
						/>
					</div>

					<div className="grid gap-4 sm:grid-cols-2">
						<div className="space-y-2">
							<Label htmlFor="custom-code">
								Custom Short Code{" "}
								<span className="text-muted-foreground">(optional)</span>
							</Label>
							<div className="flex items-center gap-2">
								<span className="text-sm text-muted-foreground">
									{baseUrl}/
								</span>
								<Input
									id="custom-code"
									placeholder="my-link"
									value={customCode}
									onChange={(e) =>
										setCustomCode(
											e.target.value.toLowerCase().replace(/[^a-z0-9-_]/g, ""),
										)
									}
									maxLength={maxShortCodeLength}
								/>
							</div>
						</div>

						<div className="space-y-2">
							<Label htmlFor="title">
								Title <span className="text-muted-foreground">(optional)</span>
							</Label>
							<Input
								id="title"
								placeholder="My Campaign Link"
								value={title}
								onChange={(e) => setTitle(e.target.value)}
							/>
						</div>
					</div>

					<Button
						onClick={handleCreate}
						disabled={isCreating || !originalUrl.trim()}
						className="w-full"
					>
						{isCreating ? "Creating..." : "Shorten Link"}
					</Button>
				</CardContent>
			</Card>

			{showLinkList && links.length > 0 && (
				<Card>
					<CardHeader>
						<CardTitle>Your Shortened Links</CardTitle>
						<CardDescription>
							{links.length} link{links.length !== 1 ? "s" : ""}
						</CardDescription>
					</CardHeader>
					<CardContent>
						<div className="rounded-md border">
							<Table>
								<TableHeader>
									<TableRow>
										<TableHead>Short Link</TableHead>
										<TableHead>Original URL</TableHead>
										<TableHead>Clicks</TableHead>
										<TableHead>Created</TableHead>
										<TableHead className="w-[100px]">Actions</TableHead>
									</TableRow>
								</TableHeader>
								<TableBody>
									{links.map((link) => (
										<TableRow key={link.id}>
											<TableCell>
												<div className="space-y-1">
													<div className="flex items-center gap-2">
														<a
															href={link.shortUrl}
															target="_blank"
															rel="noopener noreferrer"
															className="font-mono text-sm text-primary hover:underline"
														>
															{link.shortCode}
														</a>
														<Button
															variant="ghost"
															size="icon-sm"
															onClick={() => handleCopy(link)}
														>
															<Copy className="size-3" />
														</Button>
													</div>
													{link.title && (
														<div className="text-xs text-muted-foreground">
															{link.title}
														</div>
													)}
												</div>
											</TableCell>
											<TableCell>
												<a
													href={link.originalUrl}
													target="_blank"
													rel="noopener noreferrer"
													className="flex items-center gap-1 text-sm hover:underline"
												>
													<span className="max-w-[300px] truncate">
														{link.originalUrl}
													</span>
													<ExternalLink className="size-3 shrink-0" />
												</a>
											</TableCell>
											<TableCell>
												<Badge variant="secondary" className="gap-1">
													<TrendingUp className="size-3" />
													{link.clicks.toLocaleString()}
												</Badge>
											</TableCell>
											<TableCell className="text-sm text-muted-foreground">
												{format(link.createdAt, "MMM d, yyyy")}
											</TableCell>
											<TableCell>
												<Button
													variant="ghost"
													size="icon-sm"
													onClick={() => handleDelete(link.id)}
												>
													<Trash2 className="size-4 text-destructive" />
												</Button>
											</TableCell>
										</TableRow>
									))}
								</TableBody>
							</Table>
						</div>
					</CardContent>
				</Card>
			)}
		</div>
	);
}
