import { type Component, For } from "solid-js";
import { ThemeToggle } from "../components/ThemeToggle";
import { store, restoreTask, deleteTaskPermanently, setMatrixScaleDays } from "@/store";
import { Trash2, Undo2, ArrowLeftRight, Hash } from "lucide-solid";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { toast } from "solid-sonner";
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
import { pb } from "@/lib/pocketbase";
import { upsertTagDefinition, removeTagDefinition, renameTagDefinition } from "@/store";
import { createSignal } from "solid-js";

export const SettingsView: Component = () => {
    return (
        <div class="w-full max-w-2xl mx-auto py-4 sm:py-10 px-4 sm:px-0 space-y-8 sm:space-y-12 animate-in fade-in slide-in-from-bottom-2 duration-500 min-w-0 overflow-hidden text-balance">
            <header class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div class="min-w-0 flex-1">
                    <h1 class="text-2xl sm:text-4xl font-black tracking-tighter">Settings</h1>
                    <p class="text-[10px] sm:text-xs text-muted-foreground truncate opacity-70 font-mono tracking-tight" title={pb.authStore.model?.email}>
                        {pb.authStore.model?.email}
                    </p>
                </div>
                <Button
                    variant="outline"
                    size="sm"
                    class="w-full sm:w-auto font-black uppercase tracking-widest text-[10px] h-10 sm:h-8 rounded-xl shadow-sm border-border/60"
                    onClick={() => { pb.authStore.clear(); location.reload(); }}
                >
                    Sign Out
                </Button>
            </header>

            <div class="grid gap-6">
                <section class="p-4 sm:p-5 rounded-2xl border border-border bg-card shadow-sm">
                    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <div class="space-y-0.5">
                            <h3 class="text-base font-semibold">Appearance</h3>
                            <p class="text-sm text-muted-foreground">Select your preferred color scheme.</p>
                        </div>
                        <div class="flex justify-start sm:justify-end">
                            <ThemeToggle />
                        </div>
                    </div>
                </section>

                {/* Matrix Configuration */}
                <section class="p-4 sm:p-5 rounded-2xl border border-border bg-card shadow-sm space-y-4">
                    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <div class="space-y-0.5 min-w-0">
                            <h3 class="text-base font-semibold flex items-center gap-2">
                                <ArrowLeftRight size={16} />
                                Matrix Horizon
                            </h3>
                            <p class="text-sm text-muted-foreground truncate sm:whitespace-normal">Adjust the time scale for your strategy grid.</p>
                        </div>
                        <div class="w-full sm:w-[120px] shrink-0">
                            <Select
                                value={store.matrixScaleDays.toString()}
                                onChange={(val) => val && setMatrixScaleDays(parseInt(val))}
                                options={["7", "14", "30", "60", "90"]}
                                placeholder="Select days"
                                itemComponent={(props) => <SelectItem item={props.item}>{props.item.rawValue} days</SelectItem>}
                            >
                                <SelectTrigger class="h-9 w-full">
                                    <span class="text-sm font-medium">{store.matrixScaleDays} days</span>
                                </SelectTrigger>
                                <SelectContent />
                            </Select>
                        </div>
                    </div>
                </section>

                <section class="p-4 sm:p-5 rounded-2xl border border-border bg-card shadow-sm space-y-4">
                    <div class="space-y-0.5">
                        <h3 class="text-base font-semibold flex items-center gap-2">
                            <Hash size={16} />
                            Global Tags
                        </h3>
                        <p class="text-sm text-muted-foreground">Manage your global tag definitions and values.</p>
                    </div>

                    <div class="space-y-2">
                        <For each={Object.entries(store.tagDefinitions || {}).sort((a, b) => a[0].localeCompare(b[0]))} fallback={
                            <div class="text-center py-8 text-muted-foreground text-sm italic border border-dashed border-border rounded-xl">
                                No specific tag definitions found.
                            </div>
                        }>
                            {([tagName, val]) => {
                                const [isEditingName, setIsEditingName] = createSignal(false);
                                const [tempName, setTempName] = createSignal(tagName);

                                const handleRename = () => {
                                    if (tempName() && tempName() !== tagName) {
                                        renameTagDefinition(tagName, tempName());
                                    }
                                    setIsEditingName(false);
                                };

                                return (
                                    <div class="flex flex-col sm:flex-row sm:items-center justify-between p-3 rounded-xl bg-muted/30 border border-border/50 gap-3 sm:gap-4">
                                        <div class="flex items-center gap-3 min-w-0 flex-1">
                                            <div class={cn("w-2 h-2 rounded-full shrink-0", val > 5 ? "bg-green-500" : val < 5 ? "bg-red-500" : "bg-gray-400")} />

                                            {isEditingName() ? (
                                                <input
                                                    class="flex h-7 min-w-0 w-full rounded-md border border-input bg-background px-2 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                                                    value={tempName()}
                                                    onInput={(e) => setTempName(e.currentTarget.value)}
                                                    onBlur={handleRename}
                                                    onKeyDown={(e) => e.key === "Enter" && handleRename()}
                                                    autofocus
                                                />
                                            ) : (
                                                <span
                                                    class="font-medium cursor-pointer hover:underline decoration-dashed underline-offset-4 truncate"
                                                    onClick={() => setIsEditingName(true)}
                                                    title="Click to rename"
                                                >
                                                    {tagName}
                                                </span>
                                            )}
                                        </div>

                                        <div class="flex items-center grow sm:grow-0 justify-between sm:justify-end gap-3 sm:gap-4 shrink-0 border-t sm:border-t-0 pt-2 sm:pt-0 border-border/20">
                                            <div class="flex items-center gap-2">
                                                <span class="text-[10px] text-muted-foreground font-bold uppercase tracking-wider">Val</span>
                                                <select
                                                    value={String(val)}
                                                    onChange={(e) => upsertTagDefinition(tagName, parseInt(e.currentTarget.value))}
                                                    class="flex h-8 w-16 items-center justify-between rounded-md border border-input bg-background px-2 py-1 text-xs shadow-sm ring-offset-background focus:outline-none focus:ring-1 focus:ring-ring appearance-none"
                                                >
                                                    <For each={["10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"]}>
                                                        {(v) => <option value={v}>{v}</option>}
                                                    </For>
                                                </select>
                                            </div>

                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                class="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
                                                onClick={() => {
                                                    if (confirm(`Delete tag "${tagName}" globally? This will remove it from all tasks.`)) {
                                                        removeTagDefinition(tagName);
                                                    }
                                                }}
                                            >
                                                <Trash2 size={14} />
                                            </Button>
                                        </div>
                                    </div>
                                );
                            }}
                        </For>
                    </div>
                </section>

                <section class="p-4 sm:p-5 rounded-2xl border border-border bg-card shadow-sm space-y-4 min-w-0 overflow-hidden">
                    <div class="space-y-0.5 min-w-0">
                        <h3 class="text-base font-semibold flex items-center gap-2">
                            <Trash2 size={16} />
                            Trash
                        </h3>
                        <p class="text-sm text-muted-foreground truncate">Items are permanently deleted after 7 days.</p>
                    </div>

                    <div class="space-y-2">
                        <For each={store.tasks.filter(t => t.deletedAt)} fallback={
                            <div class="text-center py-8 text-muted-foreground text-sm italic border border-dashed border-border rounded-xl">
                                Trash is empty.
                            </div>
                        }>
                            {(task) => {
                                const daysLeft = Math.ceil(((task.deletedAt || 0) + (7 * 24 * 60 * 60 * 1000) - Date.now()) / (1000 * 60 * 60 * 24));
                                return (
                                    <div class="flex flex-col sm:flex-row sm:items-center justify-between p-3.5 rounded-2xl bg-muted/20 border border-border/40 group hover:bg-muted/40 transition-all gap-3 min-w-0">
                                        <div class="min-w-0 flex-1 px-1">
                                            <p class="font-semibold truncate text-sm sm:text-base">{task.title || "Untitled"}</p>
                                            <p class="text-[11px] text-muted-foreground opacity-70">Expires in {Math.max(0, daysLeft)} days</p>
                                        </div>
                                        <div class="flex items-center justify-end gap-2 shrink-0 border-t sm:border-t-0 pt-3 sm:pt-0 border-border/10">
                                            <Button
                                                variant="secondary"
                                                size="sm"
                                                class="h-9 px-4 text-[10px] font-bold uppercase tracking-widest hover:bg-green-500/10 hover:text-green-600 bg-background/50 border border-border/50 transition-all rounded-xl shadow-sm"
                                                onClick={() => {
                                                    restoreTask(task.id);
                                                    toast.success("Task restored");
                                                }}
                                            >
                                                <Undo2 size={14} class="mr-2" />
                                                Recover
                                            </Button>
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                class="h-9 w-9 hover:bg-red-500/10 hover:text-red-600 rounded-xl border border-border/50 bg-background/30"
                                                onClick={() => {
                                                    if (confirm("Permanently delete this task? This cannot be undone.")) {
                                                        deleteTaskPermanently(task.id);
                                                        toast.error("Task permanently deleted");
                                                    }
                                                }}
                                            >
                                                <Trash2 size={14} />
                                            </Button>
                                        </div>
                                    </div>
                                );
                            }}
                        </For>
                    </div>
                </section>


            </div>
        </div>
    );
};
