"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";

export function SearchRequestModal({
	open,
	onOpenChange,
	costs,
}: {
	open: boolean;
	onOpenChange: (open: boolean) => void;
	costs: { movie: number; tv: number };
}) {
	const [query, setQuery] = useState("");
	const [results, setResults] = useState<any[]>([]);
	const [loading, setLoading] = useState(false);

	const search = async () => {
		setLoading(true);
		try {
			const res = await api.get(
				`/overseer/search?query=${encodeURIComponent(query)}`,
			);
			setResults(res.data?.results || res.data || []);
		} catch {
			toast.error("Search failed");
		} finally {
			setLoading(false);
		}
	};

	const request = async (item: any, mediaType: string) => {
		try {
			await api.post("/overseer/request", {
				mediaType,
				mediaId: item.id || item.tmdbId,
				title: item.title || item.name,
				seasons: item.seasons,
			});
			toast.success("Request sent");
			onOpenChange(false);
		} catch (e: any) {
			toast.error(e?.response?.data?.error || "Request failed");
		}
	};

	return (
		<Dialog open={open} onOpenChange={onOpenChange}>
			<DialogContent>
				<DialogHeader>
					<DialogTitle>Request content</DialogTitle>
					<DialogDescription>
						Search and send request. Movie cost {costs.movie}. TV cost{" "}
						{costs.tv}.
					</DialogDescription>
				</DialogHeader>
				<div className="space-y-3">
					<Input
						value={query}
						onChange={(e) => setQuery(e.target.value)}
						placeholder="Search movie or show"
					/>
					<Button onClick={search} disabled={loading || !query}>
						Search
					</Button>
					<div className="max-h-72 overflow-auto space-y-2">
						{results.map((r) => (
							<div
								key={r.id || r.tmdbId}
								className="flex items-center justify-between gap-2 border p-2 rounded"
							>
								<div>
									<div className="font-medium">{r.title || r.name}</div>
									<div className="text-xs text-muted-foreground">
										{r.media_type || r.mediaType}
									</div>
								</div>
								<Button
									size="sm"
									onClick={() =>
										request(r, r.media_type || r.mediaType || "movie")
									}
								>
									Request
								</Button>
							</div>
						))}
					</div>
				</div>
			</DialogContent>
		</Dialog>
	);
}
