import React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "./ui/card";
import { Form, FormField, FormItem, FormLabel, FormControl, FormDescription, FormMessage } from "./ui/form";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { toast } from "sonner";
import { ScrollArea } from "./ui/scroll-area";
import { Star, Coins } from "lucide-react";

interface QuestListItem {
    id: number;
    name: string;
    description: string | null;
    triggerEvent: string;
    requirements: { target?: number };
    rewards: { xp?: number; balance?: number };
}

const questSchema = z.object({
    name: z.string().min(3, "Name must be at least 3 characters"),
    description: z.string().optional(),
    triggerEvent: z.string().min(1, "Trigger event is required"),
    target: z.number().min(1, "Target must be at least 1"),
    xpReward: z.number().min(0).optional(),
    balanceReward: z.number().min(0).optional(),
});

type QuestFormValues = z.infer<typeof questSchema>;

interface QuestFormProps {
    initialData?: QuestListItem;
    onUpdate?: () => void;
    onCancel?: () => void;
}

const TRIGGER_EVENTS = [
    { label: "XP Gain", value: "XP_GAIN" },
    { label: "Item Collect", value: "ITEM_COLLECT" },
    { label: "Item Use", value: "ITEM_USE" },
    { label: "Daily Reward", value: "DAILY_REWARD" },
    { label: "Lootbox Currency Reward", value: "LOOTBOX" },
    { label: "Exam Reward", value: "EXAM_REWARD" },
    { label: "Purchase", value: "PURCHASE" },
    { label: "Transfer In", value: "TRANSFER_IN" },
    { label: "Transfer Out", value: "TRANSFER_OUT" },
    { label: "Trade In", value: "TRADE_IN" },
    { label: "Trade Out", value: "TRADE_OUT" },
    { label: "Quest Reward", value: "QUEST_REWARD" },
    { label: "Trivia Entry", value: "TRIVIA_ENTRY" },
    { label: "Trivia Win", value: "TRIVIA_WIN" },
];

export function QuestForm({ initialData, onUpdate, onCancel }: QuestFormProps) {
    const isEditMode = initialData !== undefined;
    const [isSubmitting, setIsSubmitting] = React.useState(false);
    const form = useForm<QuestFormValues>({
        resolver: zodResolver(questSchema),
        defaultValues: {
            name: initialData?.name || "",
            description: initialData?.description || "",
            triggerEvent: initialData?.triggerEvent || "XP_GAIN",
            target: (initialData?.requirements as { target?: number })?.target || 1,
            xpReward: (initialData?.rewards as { xp?: number })?.xp || 100,
            balanceReward: (initialData?.rewards as { balance?: number })?.balance || 500,
        },
    });

    React.useEffect(() => {
        if (initialData) {
            form.reset({
                name: initialData.name || "",
                description: initialData.description || "",
                triggerEvent: initialData.triggerEvent || "XP_GAIN",
                target: (initialData.requirements as { target?: number })?.target || 1,
                xpReward: (initialData.rewards as { xp?: number })?.xp || 100,
                balanceReward: (initialData.rewards as { balance?: number })?.balance || 500,
            });
        }
    }, [initialData, form]);

    const onSubmit = async (data: QuestFormValues) => {
        setIsSubmitting(true);
        try {
            const url = isEditMode ? `/api/quests/${initialData.id}` : "/api/quests";
            const method = isEditMode ? "PUT" : "POST";

            const response = await fetch(url, {
                method: method,
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(data),
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || (isEditMode ? "Failed to update quest" : "Failed to create quest"));
            }

            toast.success(isEditMode ? "Quest updated successfully!" : "Quest created successfully!", {
                description: `${data.name} has been ${isEditMode ? "updated" : "added to the database"}.`,
            });
            form.reset({
                name: "",
                description: "",
                triggerEvent: "XP_GAIN",
                target: 1,
                xpReward: 100,
                balanceReward: 500,
            });
            onUpdate?.();
        } catch (error) {
            console.error("Submission error:", error);
            toast.error(isEditMode ? "Failed to update quest" : "Failed to create quest", {
                description: error instanceof Error ? error.message : "An unknown error occurred",
            });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Card className="glass-card overflow-hidden">
            <div className="h-1.5 bg-primary w-full" />
            <CardHeader>
                <CardTitle className="text-2xl font-bold text-primary">{isEditMode ? "Edit Quest" : "Create New Quest"}</CardTitle>
                <CardDescription>
                    {isEditMode ? "Update the quest configuration." : "Configure a new quest for the Aurora RPG academy."}
                </CardDescription>
            </CardHeader>
            <CardContent>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <FormField
                                control={form.control}
                                name="name"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Quest Name</FormLabel>
                                        <FormControl>
                                            <Input placeholder="Collector's Journey" {...field} className="bg-background/50" />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="triggerEvent"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Trigger Event</FormLabel>
                                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                                            <FormControl>
                                                <SelectTrigger className="bg-background/50">
                                                    <SelectValue placeholder="Select an event" />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent className="glass-card border-border/50">
                                                <ScrollArea className="h-48">
                                                    {TRIGGER_EVENTS.map((event) => (
                                                        <SelectItem key={event.value} value={event.value}>
                                                            {event.label}
                                                        </SelectItem>
                                                    ))}
                                                </ScrollArea>
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="description"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Description</FormLabel>
                                    <FormControl>
                                        <Textarea 
                                            placeholder="Assigns a task to the student..." 
                                            {...field} 
                                            className="min-h-[100px] bg-background/50"
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                            <FormField
                                control={form.control}
                                name="target"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Target Value</FormLabel>
                                        <FormControl>
                                            <Input 
                                                type="number" 
                                                {...field} 
                                                onChange={e => field.onChange(parseInt(e.target.value))}
                                                className="bg-background/50"
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="xpReward"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="flex items-center gap-2">
                                            <Star className="w-4 h-4 text-amber-400" />
                                            XP Reward
                                        </FormLabel>
                                        <FormControl>
                                            <Input 
                                                type="number" 
                                                {...field} 
                                                onChange={e => field.onChange(parseInt(e.target.value))}
                                                className="bg-background/50"
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="balanceReward"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="flex items-center gap-2">
                                            <Coins className="w-4 h-4 text-amber-500" />
                                            AU Reward
                                        </FormLabel>
                                        <FormControl>
                                            <Input 
                                                type="number" 
                                                {...field} 
                                                onChange={e => field.onChange(parseInt(e.target.value))}
                                                className="bg-background/50"
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        {isEditMode ? (
                            <div className="flex gap-4">
                                <Button
                                    type="submit"
                                    disabled={isSubmitting}
                                    className="flex-1 bg-primary text-primary-foreground hover:glow-primary active-press py-6 text-lg font-bold"
                                >
                                    {isSubmitting ? "Updating..." : "Update Quest"}
                                </Button>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={onCancel}
                                    className="flex-1 py-6 text-lg font-bold"
                                >
                                    Cancel
                                </Button>
                            </div>
                        ) : (
                            <Button
                                type="submit"
                                disabled={isSubmitting}
                                className="w-full bg-primary text-primary-foreground hover:glow-primary active-press py-6 text-lg font-bold"
                            >
                                {isSubmitting ? "Creating..." : "Create Quest"}
                            </Button>
                        )}
                    </form>
                </Form>
            </CardContent>
        </Card>
    );
}
