import json
import os
import tkinter as tk
from tkinter import ttk, messagebox, filedialog


class App081:
    """チェックリスト"""

    DEFAULT_FILE = os.path.join(os.path.expanduser("~"), ".checklist.json")

    def __init__(self, root):
        self.root = root
        self.root.title("チェックリスト")
        self.root.geometry("560x520")
        self.root.configure(bg="#f8f9fc")
        # tasks: list of dict(text, done)
        self.tasks = []
        self._build_ui()
        self._load_default()
        self._refresh_view()

    def _build_ui(self):
        """UIを構築する"""
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(
            title_frame, text="チェックリスト",
            font=("Noto Sans JP", 16, "bold"),
            bg="#3776ab", fg="white"
        ).pack()

        main = tk.Frame(self.root, bg="#f8f9fc", padx=16, pady=12)
        main.pack(fill=tk.BOTH, expand=True)

        # 入力欄
        form = tk.Frame(main, bg="#f8f9fc")
        form.pack(fill=tk.X, pady=(0, 6))
        self.task_var = tk.StringVar()
        e = ttk.Entry(form, textvariable=self.task_var, font=("Noto Sans JP", 11))
        e.pack(side=tk.LEFT, fill=tk.X, expand=True)
        e.bind("<Return>", lambda ev: self.add_task())
        ttk.Button(form, text="追加", command=self.add_task).pack(side=tk.LEFT, padx=4)

        # ボタン
        btns = tk.Frame(main, bg="#f8f9fc")
        btns.pack(fill=tk.X, pady=4)
        ttk.Button(btns, text="完了切替", command=self.toggle_done).pack(side=tk.LEFT, padx=2)
        ttk.Button(btns, text="削除", command=self.delete_selected).pack(side=tk.LEFT, padx=2)
        ttk.Button(btns, text="完了済を一括削除", command=self.clear_done).pack(side=tk.LEFT, padx=2)
        ttk.Button(btns, text="保存", command=self.save_tasks).pack(side=tk.RIGHT, padx=2)
        ttk.Button(btns, text="読込", command=self.load_tasks).pack(side=tk.RIGHT, padx=2)

        # リスト
        list_frame = ttk.LabelFrame(main, text="タスク一覧", padding=4)
        list_frame.pack(fill=tk.BOTH, expand=True, pady=4)
        self.listbox = tk.Listbox(list_frame, font=("Noto Sans JP", 11),
                                   bg="white", relief=tk.FLAT, selectmode=tk.SINGLE,
                                   activestyle="none")
        self.listbox.pack(fill=tk.BOTH, expand=True, side=tk.LEFT)
        self.listbox.bind("<Double-Button-1>", lambda e: self.toggle_done())
        sb = ttk.Scrollbar(list_frame, command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=sb.set)
        sb.pack(side=tk.RIGHT, fill=tk.Y)

        # プログレスバー + ステータス
        status = tk.Frame(main, bg="#f8f9fc")
        status.pack(fill=tk.X, pady=(4, 0))
        self.progress = ttk.Progressbar(status, mode="determinate", maximum=100)
        self.progress.pack(fill=tk.X, side=tk.TOP)
        self.status_var = tk.StringVar()
        tk.Label(status, textvariable=self.status_var, bg="#f8f9fc",
                 font=("Noto Sans JP", 10)).pack(anchor="w", pady=(2, 0))

    def add_task(self):
        """タスクを追加する"""
        text = self.task_var.get().strip()
        if not text:
            return
        self.tasks.append({"text": text, "done": False})
        self.task_var.set("")
        self._refresh_view()

    def toggle_done(self):
        """選択タスクの完了状態を切り替え"""
        sel = self.listbox.curselection()
        if not sel:
            return
        idx = sel[0]
        self.tasks[idx]["done"] = not self.tasks[idx]["done"]
        self._refresh_view()
        if idx < self.listbox.size():
            self.listbox.selection_set(idx)

    def delete_selected(self):
        """選択タスクを削除"""
        sel = self.listbox.curselection()
        if not sel:
            return
        del self.tasks[sel[0]]
        self._refresh_view()

    def clear_done(self):
        """完了済タスクを一括削除"""
        before = len(self.tasks)
        self.tasks = [t for t in self.tasks if not t["done"]]
        if before != len(self.tasks):
            self._refresh_view()

    def save_tasks(self):
        """タスクをファイルに保存"""
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json")],
            initialfile="checklist.json",
        )
        if not path:
            return
        try:
            with open(path, "w", encoding="utf-8") as f:
                json.dump(self.tasks, f, ensure_ascii=False, indent=2)
            # デフォルトとしても保存
            try:
                with open(self.DEFAULT_FILE, "w", encoding="utf-8") as f:
                    json.dump(self.tasks, f, ensure_ascii=False, indent=2)
            except OSError:
                pass
            messagebox.showinfo("完了", f"保存しました: {path}")
        except OSError as e:
            messagebox.showerror("エラー", f"保存失敗: {e}")

    def load_tasks(self):
        """タスクをファイルから読み込み"""
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
            if not isinstance(data, list):
                raise ValueError
            self.tasks = [
                {"text": str(d.get("text", "")), "done": bool(d.get("done", False))}
                for d in data if isinstance(d, dict)
            ]
            self._refresh_view()
        except (OSError, ValueError, json.JSONDecodeError) as e:
            messagebox.showerror("エラー", f"読込失敗: {e}")

    def _load_default(self):
        """デフォルト保存ファイルがあれば自動読み込み"""
        if os.path.exists(self.DEFAULT_FILE):
            try:
                with open(self.DEFAULT_FILE, "r", encoding="utf-8") as f:
                    data = json.load(f)
                if isinstance(data, list):
                    self.tasks = [
                        {"text": str(d.get("text", "")), "done": bool(d.get("done", False))}
                        for d in data if isinstance(d, dict)
                    ]
            except (OSError, json.JSONDecodeError):
                pass

    def _refresh_view(self):
        """リストとプログレスバーを更新"""
        self.listbox.delete(0, tk.END)
        for t in self.tasks:
            mark = "[x]" if t["done"] else "[ ]"
            self.listbox.insert(tk.END, f"{mark} {t['text']}")
            if t["done"]:
                self.listbox.itemconfig(tk.END, fg="#888")
        total = len(self.tasks)
        done = sum(1 for t in self.tasks if t["done"])
        ratio = (done / total * 100) if total else 0
        self.progress["value"] = ratio
        self.status_var.set(f"完了 {done} / {total} 件 ({ratio:.0f}%)")


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()
