"use client"

import { useTransition } from "react"
import { Controller, useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { updateBook } from "@/lib/actions/book"
import { getPublicUrl } from "@/lib/utils/storage"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { AlertCircle, Loader2, Save } from "lucide-react"
import { updateBookSchema, UpdateBookInput } from "@/lib/schemas/books"
import Uploader from "@/components/web/uploader/Uploader"
import BookFileUploader from "@/components/web/uploader/BookFileUploader"

type BookForEdit = {
  id: string
  title: string
  author: string
  isbn: string | null
  description: string | null
  language: string | null
  publishedDate: string | null
  category: string | null
  format: "DIGITAL" | "PHYSICAL" | "BOTH"
  pages: number | null
  location: string | null
  totalCopies: number
  coverImage: string | null
  digitalAsset: { fileKey: string; format: "PDF" | "EPUB" } | null
}

const CATEGORIES = [
  "FICTION","NON_FICTION","SCI_FI","FANTASY","MYSTERY","THRILLER",
  "ROMANCE","HORROR","HISTORY","BIOGRAPHY","SCIENCE","TECHNOLOGY",
  "SELF_HELP","BUSINESS","EDUCATION","YOUNG_ADULT","CHILDRENS",
  "POETRY","DRAMA","GRAPHIC_NOVEL","REFERENCE","OTHER",
]

export function BookEditForm({ book }: { book: BookForEdit }) {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()

  const form = useForm<UpdateBookInput>({
    resolver: zodResolver(updateBookSchema),
    defaultValues: {
      title:          book.title,
      author:         book.author,
      isbn:           book.isbn          ?? "",
      description:    book.description   ?? "",
      language:       book.language      ?? "",
      publishedDate:  book.publishedDate ?? "",
      category:       (book.category as any) ?? "OTHER",
      format:         book.format,
      pages:          book.pages         ?? undefined,
      location:       book.location      ?? "",
      numberOfCopies: book.totalCopies,
      coverImage:     book.coverImage    ?? undefined,
      fileKey:        undefined,
      fileType:       book.digitalAsset?.format ?? undefined,
    },
  })

  const { isDirty } = form.formState
  const format      = form.watch("format")
  const isPhysical  = format === "PHYSICAL" || format === "BOTH"
  const isDigital   = format === "DIGITAL"  || format === "BOTH"

  function onSubmit(values: UpdateBookInput) {
    startTransition(async () => {
      const result = await updateBook(book.id, values)
      if (result.status === "success") {
        toast.success(result.message)
        router.push(`/admin/books/${book.id}`)
        router.refresh()
      } else {
        toast.error(result.message)
      }
    })
  }

  return (
    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-10">

      {/* ── Unsaved changes banner ── */}
      {isDirty && (
        <div className="flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-800 px-4 py-2.5 text-sm text-amber-700 dark:text-amber-400">
          <AlertCircle className="w-4 h-4 shrink-0" />
          You have unsaved changes.
        </div>
      )}

      {/* ══════════════════════════════════════════
          SECTION 1 — Cover image
      ══════════════════════════════════════════ */}
      <section className="space-y-4">
        <SectionHeader title="Cover Image" />

        <Controller
          name="coverImage"
          control={form.control}
          render={({ field }) => (
            <Field>
              <FieldLabel>Cover Image</FieldLabel>
              <Uploader
                initialPreview={book.coverImage ? getPublicUrl(book.coverImage) : undefined}
                onUploadComplete={(key) => field.onChange(key)}
                onDelete={() => field.onChange(undefined)}
              />
              <FieldDescription>
                JPG or PNG · Max 5MB. Leave unchanged to keep the current cover.
              </FieldDescription>
            </Field>
          )}
        />
      </section>

      {/* ══════════════════════════════════════════
          SECTION 2 — Core book details
      ══════════════════════════════════════════ */}
      <section className="space-y-6">
        <SectionHeader title="Book Details" />

        <FieldGroup className="grid grid-cols-1 md:grid-cols-2 gap-6">

          <Controller
            name="title"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="title">Title *</FieldLabel>
                <Input {...field} id="title" placeholder="Book title" aria-invalid={fieldState.invalid} />
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="author"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="author">Author *</FieldLabel>
                <Input {...field} id="author" placeholder="Author name" aria-invalid={fieldState.invalid} />
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="isbn"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="isbn">ISBN</FieldLabel>
                <Input {...field} id="isbn" placeholder="978-..." aria-invalid={fieldState.invalid} />
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="pages"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="pages">Pages</FieldLabel>
                <Input
                  {...field}
                  id="pages"
                  type="number"
                  min={1}
                  placeholder="320"
                  value={field.value ?? ""}
                  aria-invalid={fieldState.invalid}
                />
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="language"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="language">Language</FieldLabel>
                <Input {...field} id="language" placeholder="English" aria-invalid={fieldState.invalid} />
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="publishedDate"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="publishedDate">Published Date</FieldLabel>
                <Input {...field} id="publishedDate" placeholder="2023" aria-invalid={fieldState.invalid} />
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="category"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="category">Category *</FieldLabel>
                <Select name={field.name} value={field.value} onValueChange={field.onChange}>
                  <SelectTrigger id="category" aria-invalid={fieldState.invalid}>
                    <SelectValue placeholder="Select category" />
                  </SelectTrigger>
                  <SelectContent>
                    {CATEGORIES.map((c) => (
                      <SelectItem key={c} value={c}>{c.replace(/_/g, " ")}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />

          <Controller
            name="format"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel htmlFor="format">Format *</FieldLabel>
                <Select name={field.name} value={field.value} onValueChange={field.onChange}>
                  <SelectTrigger id="format" aria-invalid={fieldState.invalid}>
                    <SelectValue placeholder="Select format" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="DIGITAL">Digital</SelectItem>
                    <SelectItem value="PHYSICAL">Physical</SelectItem>
                    <SelectItem value="BOTH">Both</SelectItem>
                  </SelectContent>
                </Select>
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />
        </FieldGroup>

        {/* Description — full width */}
        <Controller
          name="description"
          control={form.control}
          render={({ field, fieldState }) => (
            <Field data-invalid={fieldState.invalid}>
              <FieldLabel htmlFor="description">Description</FieldLabel>
              <Textarea
                {...field}
                id="description"
                placeholder="Brief summary of the book..."
                rows={4}
                aria-invalid={fieldState.invalid}
              />
              {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
            </Field>
          )}
        />
      </section>

      {/* ══════════════════════════════════════════
          SECTION 3 — Physical settings (conditional)
      ══════════════════════════════════════════ */}
      {isPhysical && (
        <section className="space-y-6">
          <SectionHeader title="Physical Copy Settings" />

          <FieldGroup className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Controller
              name="location"
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel htmlFor="location">Shelf Location *</FieldLabel>
                  <Input {...field} id="location" placeholder="e.g. A3-12" aria-invalid={fieldState.invalid} />
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />

            <Controller
              name="numberOfCopies"
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel htmlFor="numberOfCopies">Total Copies *</FieldLabel>
                  <Input
                    {...field}
                    id="numberOfCopies"
                    type="number"
                    min={book.totalCopies}
                    value={field.value ?? ""}
                    aria-invalid={fieldState.invalid}
                  />
                  <FieldDescription>
                    Currently {book.totalCopies} {book.totalCopies === 1 ? "copy" : "copies"}.
                    Increase to add new ones. To reduce, remove individual copies from the detail page.
                  </FieldDescription>
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />
          </FieldGroup>
        </section>
      )}

      {/* ══════════════════════════════════════════
          SECTION 4 — Digital asset (conditional)
      ══════════════════════════════════════════ */}
      {isDigital && (
        <section className="space-y-6">
          <SectionHeader title="Digital File" />

          {/* Show current file info if one exists */}
          {book.digitalAsset && (
            <div className="flex items-center gap-3 rounded-lg border bg-muted/40 px-4 py-3 text-sm">
              <div className="flex-1 min-w-0">
                <p className="text-muted-foreground">Current file</p>
                <p className="font-mono text-xs truncate">{book.digitalAsset.fileKey}</p>
              </div>
              <Badge variant="secondary">{book.digitalAsset.format}</Badge>
            </div>
          )}

          <Controller
            name="fileKey"
            control={form.control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid}>
                <FieldLabel>
                  {book.digitalAsset ? "Replace File" : "Upload File"}
                </FieldLabel>
                <BookFileUploader
                  onUploadComplete={(key, fileType) => {
                    field.onChange(key)
                    form.setValue("fileType", fileType, { shouldDirty: true })
                  }}
                  onDelete={() => {
                    field.onChange(undefined)
                    form.setValue("fileType", undefined, { shouldDirty: true })
                  }}
                />
                <FieldDescription>
                  PDF or EPUB · Max 50MB.{" "}
                  {book.digitalAsset
                    ? "Upload a new file only if you want to replace the existing one."
                    : "Upload the digital version of this book."}
                </FieldDescription>
                {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
              </Field>
            )}
          />
        </section>
      )}

      {/* ── Actions ── */}
      <div className="flex items-center gap-3 pt-2 border-t">
        <Button type="submit" disabled={isPending || !isDirty} className="gap-2">
          {isPending
            ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</>
            : <><Save className="w-4 h-4" /> Save changes</>
          }
        </Button>
        <Button
          type="button"
          variant="outline"
          disabled={isPending}
          onClick={() => router.push(`/admin/books/${book.id}`)}
        >
          Cancel
        </Button>
        {isDirty && (
          <Button
            type="button"
            variant="ghost"
            disabled={isPending}
            onClick={() => form.reset()}
            className="text-muted-foreground"
          >
            Discard changes
          </Button>
        )}
      </div>
    </form>
  )
}

// ── Helper ────────────────────────────────────────────────────────────────────
function SectionHeader({ title }: { title: string }) {
  return (
    <div className="space-y-2">
      <h2 className="text-base font-semibold text-stone-800 dark:text-stone-200">{title}</h2>
      <Separator />
    </div>
  )
}