"use client"

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldLabel } from "@/components/ui/field";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { useTransition } from "react";
import { CirclePlusIcon, Loader2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import Uploader from "@/components/web/uploader/Uploader";
import { tryCatch } from "@/hooks/try-catch";
import { toast } from "sonner";
import addBook from "@/lib/actions/book";
import { AddBookInput, addBookSchema, BookCategoryEnum, bookFormartEnum } from "@/lib/schemas/books";
import BookFileUploader from "@/components/web/uploader/BookFileUploader";
import { useRouter } from "next/navigation";

export default function AddBookForm({
    className,
    ...props
}: React.ComponentProps<"div">) {
    const [ isPending, startTransition ] = useTransition();
    const router = useRouter();

    const form = useForm<AddBookInput>({
        resolver: zodResolver(addBookSchema),
        defaultValues:{
            title: "",
            author: "",
            isbn: undefined,
            language: undefined,
            publishedDate: undefined,
            description: "",
            category: "SCIENCE",
            coverImage: undefined,
            format: "DIGITAL",
            pages: undefined,
            location: undefined,
            numberOfCopies: undefined
        }
    });

    const formatWatch = form.watch("format");

    function onSubmit(values: AddBookInput) {
        startTransition(async () => {
            const { data: result, error } = await tryCatch(addBook(values));

            console.log(result);
            console.log(error);

            if (error) {
                toast.error("An unexpected error occurred. Please try again.");
                return;
            }

            if (result?.status === "success") {
                toast.success(result?.message);
                form.reset();
                router.push("/admin/books");
            } else if (result?.status === "error") {
                toast.error(result?.message);
            }            
        })
    }

    return (
        <div className={cn("flex flex-col gap-6", className)} {...props}>
            <Card>
                <CardHeader className="text-center pb-2">
                    <CardTitle className="text-2xl font-semibold tracking-tight">
                        Add a Book
                    </CardTitle>
                    <CardDescription className="text-sm text-muted-foreground">
                        Add a book to the library.
                    </CardDescription>
                </CardHeader>

                <CardContent>
                    <form onSubmit={form.handleSubmit(onSubmit, (errors) => console.log("Validation Errors:", errors))} className="space-y-8 flex flex-col gap-4">

                        {/* ── Book Cover Upload ──────────────────────────────────────── */}
                        <section className="space-y-4 flex flex-col gap-4">
                            <SectionHeading title="Book Details" />
                            <Controller
                                name="coverImage"
                                control={form.control}
                                render={({ field, fieldState }) => (
                                    <Field>
                                        <FieldLabel htmlFor="coverImage">Cover Image</FieldLabel>
                                        <Uploader
                                            onUploadComplete={(key) => {
                                                field.onChange(key);
                                            }}
                                            onDelete={() => {
                                                field.onChange("");
                                            }}
                                        />
                                        {fieldState.error && (
                                            <p className="text-xs text-destructive mt-1">
                                                {fieldState.error.message}
                                            </p>
                                        )}
                                    </Field>
                                )}
                            />

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <Controller
                                    name="title"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="title">Title</FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="text"
                                                placeholder="e.g. The subtle art of not giving a f*ck"
                                                aria-invalid={fieldState.invalid}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />

                                <Controller
                                    name="author"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="author">Author</FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="text"
                                                placeholder="e.g. Mark Manson"
                                                aria-invalid={fieldState.invalid}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                                <Controller
                                    name="language"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="language">Language</FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="text"
                                                placeholder="e.g. English"
                                                aria-invalid={fieldState.invalid}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                                <Controller
                                    name="publishedDate"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="publishedDate">Publication Year</FieldLabel>
                                            <Input
                                                id="publishedDate"
                                                type="number"
                                                min={1000}
                                                max={new Date().getFullYear()}
                                                placeholder={`e.g. ${new Date().getFullYear()}`}
                                                aria-invalid={fieldState.invalid}
                                                value={field.value ?? ""}
                                                onChange={(e) => {
                                                    const val = e.target.value;
                                                    field.onChange(val === "" ? undefined : Number(val));
                                                }}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                                <Controller
                                    name="isbn"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="isbn">ISBN</FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="text"
                                                placeholder="e.g. 978-1492032450"
                                                aria-invalid={fieldState.invalid}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                                <Controller
                                    name="pages"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="pages">Page Numbers</FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="number"
                                                placeholder="e.g. 286"
                                                aria-invalid={fieldState.invalid}
                                                onChange={(e) => {
                                                    const val = e.target.value;
                                                    field.onChange(val === "" ? undefined : Number(val));
                                                }}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                            </div>

                            <Controller
                                name="description"
                                control={form.control}
                                render={({ field, fieldState }) => (
                                    <Field>
                                        <FieldLabel htmlFor="description">
                                            Book Description
                                        </FieldLabel>
                                        <Textarea
                                            {...field}
                                            id={field.name}
                                            placeholder="Tell readers about this book..."
                                            aria-invalid={fieldState.invalid}
                                            className="min-h-[120px] resize-none"
                                        />
                                        {fieldState.error && (
                                            <p className="text-xs text-destructive mt-1">
                                                {fieldState.error.message}
                                            </p>
                                        )}
                                    </Field>
                                )}
                            />
                        </section>

                        {/* ── Category & Other Details ───────────────────────────────── */}
                        <section className="space-y-4">
                            <SectionHeading title="Category & Other Details" />

                            {/* Category + Phone */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <Controller
                                    name="category"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="category">
                                                Book Category
                                            </FieldLabel>
                                            <Select
                                                onValueChange={field.onChange}
                                                defaultValue={field.value}
                                            >
                                                <SelectTrigger
                                                    id="category"
                                                    aria-invalid={fieldState.invalid}
                                                >
                                                    <SelectValue placeholder="Select a category" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectGroup>
                                                        <SelectLabel>Category</SelectLabel>
                                                        {BookCategoryEnum.options.map((cat) => (
                                                            <SelectItem key={cat} value={cat}>
                                                                {cat.charAt(0).toUpperCase() + cat.slice(1)}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectGroup>
                                                </SelectContent>
                                            </Select>
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                                <Controller
                                    name="format"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="format">
                                                Available Format
                                            </FieldLabel>
                                            <Select
                                                onValueChange={field.onChange}
                                                defaultValue={field.value}
                                            >
                                                <SelectTrigger
                                                    id="format"
                                                    aria-invalid={fieldState.invalid}
                                                >
                                                    <SelectValue placeholder="Select a format" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectGroup>
                                                        <SelectLabel>Format</SelectLabel>
                                                        {bookFormartEnum.options.map((fmt) => (
                                                            <SelectItem key={fmt} value={fmt}>
                                                                {fmt.charAt(0).toUpperCase() + fmt.slice(1)}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectGroup>
                                                </SelectContent>
                                            </Select>
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />

                                <Controller
                                    name="numberOfCopies"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="numberOfCopies">
                                                Number of Copies
                                            </FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="number"
                                                min={1}
                                                placeholder="1..."
                                                aria-invalid={fieldState.invalid}
                                                onChange={(e) => {
                                                    const val = e.target.value;
                                                    field.onChange(val === "" ? undefined : Number(val));
                                                }}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                                <Controller
                                    name="location"
                                    control={form.control}
                                    render={({ field, fieldState }) => (
                                        <Field>
                                            <FieldLabel htmlFor="location">
                                                Book&apos;s Location in Library
                                            </FieldLabel>
                                            <Input
                                                {...field}
                                                id={field.name}
                                                type="text"
                                                placeholder="Shelf 1, Row 2..."
                                                aria-invalid={fieldState.invalid}
                                            />
                                            {fieldState.error && (
                                                <p className="text-xs text-destructive mt-1">
                                                    {fieldState.error.message}
                                                </p>
                                            )}
                                        </Field>
                                    )}
                                />
                            </div>
                        </section>

                        <Separator />

                        {/* ── Physical and Digital copies (collapsible) ───────────────────────── */}
                        <section className="space-y-3 flex flex-col gap-6">
                            {formatWatch === "PHYSICAL" || formatWatch === "BOTH" && (
                                <section className="space-y-4">
                                    <SectionHeading title="Physical Copies" />
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <Controller
                                            name="numberOfCopies"
                                            control={form.control}
                                            render={({ field, fieldState }) => (
                                                <Field>
                                                    <FieldLabel>Number of Copies</FieldLabel>
                                                    <Input
                                                        {...field}
                                                        type="number"
                                                        min={1}
                                                        placeholder="e.g. 5"
                                                        onChange={e => field.onChange(Number(e.target.value))}
                                                        aria-invalid={fieldState.invalid}
                                                    />
                                                    {fieldState.error && (
                                                        <p className="text-xs text-destructive mt-1">{fieldState.error.message}</p>
                                                    )}
                                                </Field>
                                            )}
                                        />

                                        <Controller
                                            name="location"
                                            control={form.control}
                                            render={({ field, fieldState }) => (
                                                <Field>
                                                    <FieldLabel>Shelf Location</FieldLabel>
                                                    <Input
                                                        {...field}
                                                        placeholder="e.g. Shelf A, Row 3"
                                                        aria-invalid={fieldState.invalid}
                                                    />
                                                    {fieldState.error && (
                                                        <p className="text-xs text-destructive mt-1">{fieldState.error.message}</p>
                                                    )}
                                                </Field>
                                            )}
                                        />
                                    </div>
                                </section>
                            )}

                            {(formatWatch === "DIGITAL" || formatWatch === "BOTH") && (
                                <section className="space-y-4">
                                    <SectionHeading title="Digital File" />
                                    <Controller
                                        name="fileKey"
                                        control={form.control}
                                        render={({ fieldState }) => (
                                            <Field>
                                                <FieldLabel>Book File</FieldLabel>
                                                <BookFileUploader
                                                    onUploadComplete={(key, fileType) => {
                                                        form.setValue("fileKey", key)
                                                        form.setValue("fileType", fileType)
                                                    }}
                                                    onDelete={() => {
                                                        form.setValue("fileKey", "")
                                                        form.setValue("fileType", undefined)
                                                    }}
                                                />
                                                {fieldState.error && (
                                                    <p className="text-xs text-destructive mt-1">{fieldState.error.message}</p>
                                                )}
                                            </Field>
                                        )}
                                    />
                                </section>
                            )}
                        </section>

                        {/* ── Submit ───────────────────────────────────────────── */}
                        <Button type="submit" className="w-full" disabled={isPending}>
                            {isPending
                                ? (
                                    <>
                                        <Loader2Icon className="animate-spin" />
                                        Adding...
                                    </>
                                )
                                : (
                                    <>
                                        <CirclePlusIcon />
                                        Add Book
                                    </>
                                )
                            }
                        </Button>
                    </form>
                </CardContent>
            </Card>
        </div>
    );
}

// Small helper component for section headings
function SectionHeading({ title }: { title: string }) {
    return (
        <div className="flex items-center gap-3">
            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
                {title}
            </h3>
            <div className="h-px flex-1 bg-border" />
        </div>
    );
}