"""Dua tampilan Tkinter; SQL hanya berada dalam repository.py."""
from pathlib import Path
import sqlite3
import tkinter as tk
from tkinter import ttk, messagebox
from repository import Library


def build_window(root, library):
    root.title("Perpustakaan Mini · Data Latihan")
    root.geometry("760x510")
    notebook = ttk.Notebook(root)
    notebook.pack(fill="both", expand=True, padx=12, pady=12)
    books_frame, loans_frame = ttk.Frame(notebook), ttk.Frame(notebook)
    notebook.add(books_frame, text="Buku")
    notebook.add(loans_frame, text="Pinjaman")
    status = tk.StringVar(root, value="Gunakan data peminjam sintetis.")
    ttk.Label(root, textvariable=status).pack(pady=6)
    title, stock, query, borrower = [tk.StringVar(root) for _ in range(4)]
    stock.set("1")

    def field(parent, label, variable):
        ttk.Label(parent, text=label).pack(side="left", padx=3)
        ttk.Entry(parent, textvariable=variable, width=20).pack(side="left", padx=3)

    add_bar = ttk.Frame(books_frame)
    add_bar.pack(fill="x", pady=6)
    field(add_bar, "Judul", title)
    field(add_bar, "Stok", stock)
    search_bar = ttk.Frame(books_frame)
    search_bar.pack(fill="x", pady=6)
    field(search_bar, "Cari judul", query)
    books = ttk.Treeview(books_frame, columns=("id", "title", "stock"), show="headings", height=9)
    for key, label, width in [("id", "ID", 60), ("title", "Judul", 350), ("stock", "Stok", 80)]:
        books.heading(key, text=label)
        books.column(key, width=width)
    books.pack(fill="both", expand=True)
    borrow_bar = ttk.Frame(books_frame)
    borrow_bar.pack(fill="x", pady=8)
    field(borrow_bar, "Peminjam latihan", borrower)
    loans = ttk.Treeview(loans_frame, columns=("id", "title", "borrower", "state"), show="headings")
    for key, label in [("id", "ID pinjaman"), ("title", "Buku"), ("borrower", "Peminjam"), ("state", "Status")]:
        loans.heading(key, text=label)
        loans.column(key, width=155)
    loans.pack(fill="both", expand=True, pady=6)

    def refresh():
        for tree in (books, loans):
            for ident in tree.get_children():
                tree.delete(ident)
        for row in library.books(query.get()):
            books.insert("", "end", iid=str(row[0]), values=row)
        for row in library.loans():
            loans.insert("", "end", iid=str(row[0]), values=(*row[:3], "Kembali" if row[3] else "Aktif"))

    def safe(action):
        def handler():
            try:
                action()
                refresh()
                status.set("Aksi berhasil; data tersimpan di SQLite.")
            except (ValueError, OSError, sqlite3.Error) as error:
                status.set("Aksi belum berhasil; periksa pesan.")
                messagebox.showerror("Perpustakaan", str(error), parent=root)
        return handler

    def add():
        library.add_book(title.get(), int(stock.get()))
        title.set("")

    def borrow():
        selection = books.selection()
        if not selection:
            raise ValueError("Pilih satu buku dahulu.")
        library.borrow(int(selection[0]), borrower.get())

    def give_back():
        selection = loans.selection()
        if not selection:
            raise ValueError("Pilih satu pinjaman dahulu.")
        library.give_back(int(selection[0]))

    buttons = {}
    for parent, label, handler in [(add_bar, "Tambah", add), (search_bar, "Cari", refresh),
                                   (borrow_bar, "Pinjam", borrow), (loans_frame, "Kembali", give_back)]:
        button = ttk.Button(parent, text=label, command=safe(handler))
        button.pack(side="left", padx=4, pady=4)
        buttons[label] = button

    def export():
        path = library.path.with_name("laporan-pinjaman.csv")
        if path.exists() and not messagebox.askyesno("Laporan", "Ganti laporan CSV latihan sebelumnya?", parent=root):
            return
        library.export(path)

    ttk.Button(loans_frame, text="Ekspor CSV", command=safe(export)).pack(side="left", padx=4, pady=4)
    refresh()
    return {"title": title, "stock": stock, "borrower": borrower, "query": query,
            "books": books, "loans": loans, "buttons": buttons, "refresh": refresh}


def main():
    root = tk.Tk()
    try:
        library = Library(Path(__file__).with_name("library.db"))
        build_window(root, library)
    except (OSError, sqlite3.Error) as error:
        messagebox.showerror("Database tidak dapat dibuka", str(error), parent=root)
        root.destroy()
        return
    root.mainloop()


if __name__ == "__main__":
    main()
