"use client";
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, Search, Star, Tag } from "lucide-react";
import { notesApi } from "@/lib/api";
import { Note } from "@/types";
import { PageHeader, Modal, EmptyState, Spinner, ConfirmDialog } from "@/components/ui";
import { timeAgo, truncate } from "@/lib/utils";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

const COLORS = ["#3b82f6","#22c55e","#f59e0b","#ef4444","#a78bfa","#06b6d4","#ec4899"];

function NoteEditor({ note, onClose }: { note?: Note; onClose: () => void }) {
  const qc = useQueryClient();
  const [content, setContent] = useState(note?.content || "");
  const [tagInput, setTagInput] = useState("");
  const [tags, setTags] = useState<string[]>(note?.tags || []);
  const { register, handleSubmit } = useForm({
    defaultValues: { title: note?.title || "", category: note?.category || "", is_favorite: note?.is_favorite || false },
  });
  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) =>
      note ? notesApi.update(note.id, data) : notesApi.create(data),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["notes"] }); toast.success(note ? "Not güncellendi." : "Not kaydedildi."); onClose(); },
  });
  const addTag = () => {
    if (tagInput.trim() && !tags.includes(tagInput.trim())) {
      setTags([...tags, tagInput.trim()]);
      setTagInput("");
    }
  };
  return (
    <form onSubmit={handleSubmit((d) => mutation.mutate({ ...d, content, tags }))} className="space-y-4">
      <div><label className="form-label">Başlık *</label><input {...register("title", { required: true })} className="kaplan-input" placeholder="Not başlığı" autoFocus /></div>
      <div><label className="form-label">İçerik</label><textarea value={content} onChange={(e) => setContent(e.target.value)} rows={8} className="kaplan-textarea font-mono text-sm" placeholder="Notunuzu buraya yazın..." /></div>
      <div className="grid grid-cols-2 gap-3">
        <div><label className="form-label">Kategori</label><input {...register("category")} className="kaplan-input" placeholder="ör: Fikirler" /></div>
        <div>
          <label className="form-label">Etiketler</label>
          <div className="flex gap-1.5">
            <input value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addTag(); }}} className="kaplan-input flex-1" placeholder="Etiket ekle + Enter" />
            <button type="button" onClick={addTag} className="btn-secondary px-3">+</button>
          </div>
          {tags.length > 0 && <div className="flex flex-wrap gap-1.5 mt-2">{tags.map((t) => (<span key={t} className="badge badge-blue gap-1">{t}<button type="button" onClick={() => setTags(tags.filter((x) => x !== t))} className="ml-1 text-xs">×</button></span>))}</div>}
        </div>
      </div>
      <div className="flex items-center gap-2">
        <input {...register("is_favorite")} type="checkbox" id="fav" className="w-4 h-4 rounded" />
        <label htmlFor="fav" className="text-sm text-surface-400 cursor-pointer flex items-center gap-1.5"><Star size={14} /> Favorilere ekle</label>
      </div>
      <div className="flex gap-3 justify-end pt-2"><button type="button" onClick={onClose} className="btn-secondary">İptal</button><button type="submit" disabled={mutation.isPending} className="btn-primary">{mutation.isPending && <Spinner size={14} />}{note ? "Güncelle" : "Kaydet"}</button></div>
    </form>
  );
}

export default function NotlarPage() {
  const qc = useQueryClient();
  const [modal, setModal] = useState<{ open: boolean; note?: Note }>({ open: false });
  const [deleteModal, setDeleteModal] = useState<{ open: boolean; noteId?: number }>({ open: false });
  const [search, setSearch] = useState("");
  const [filterFav, setFilterFav] = useState(false);
  const [filterCategory, setFilterCategory] = useState("");

  const { data: notes = [], isLoading } = useQuery<Note[]>({
    queryKey: ["notes", filterFav, filterCategory],
    queryFn: () => notesApi.list({ ...(filterFav ? { favorite: true } : {}), ...(filterCategory ? { category: filterCategory } : {}), ...(search ? { search } : {}) }),
  });

  const favMutation = useMutation({ mutationFn: (id: number) => notesApi.toggleFavorite(id), onSuccess: () => qc.invalidateQueries({ queryKey: ["notes"] }) });
  const deleteMutation = useMutation({ mutationFn: (id: number) => notesApi.delete(id), onSuccess: () => { qc.invalidateQueries({ queryKey: ["notes"] }); toast.success("Not silindi."); setDeleteModal({ open: false }); } });

  const categories = [...new Set(notes.map((n) => n.category).filter(Boolean))] as string[];

  return (
    <div className="space-y-5 animate-fade-in">
      <PageHeader title="Not Defteri" subtitle={`${notes.length} not`} action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={16} /> Yeni Not</button>} />
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-48"><Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-surface-500" /><input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Not ara..." className="kaplan-input pl-8 h-8 text-xs w-full" /></div>
        <button onClick={() => setFilterFav(!filterFav)} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs border transition-colors ${filterFav ? "bg-amber-500/15 border-amber-500/30 text-amber-400" : "border-surface-500 text-surface-400 hover:text-surface-200"}`}><Star size={12} /> Favoriler</button>
        {categories.length > 0 && <select value={filterCategory} onChange={(e) => setFilterCategory(e.target.value)} className="kaplan-select h-8 text-xs w-36"><option value="">Tüm Kategoriler</option>{categories.map((c) => <option key={c} value={c}>{c}</option>)}</select>}
      </div>
      {isLoading ? <div className="flex justify-center py-12"><Spinner /></div> : notes.length === 0 ? (
        <EmptyState icon="📝" title="Henüz not yok" description="Düşüncelerinizi, fikirlerinizi kaydedin." action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={14} /> Not Al</button>} />
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
          {notes.map((note, i) => (
            <div key={note.id} className="kaplan-card hover:border-surface-400 transition-all cursor-pointer group space-y-3" style={{ borderLeftColor: COLORS[i % COLORS.length], borderLeftWidth: "3px" }}>
              <div className="flex items-start justify-between gap-2">
                <h3 className="font-semibold text-surface-100 line-clamp-1">{note.title}</h3>
                <div className="flex gap-1 flex-shrink-0">
                  <button onClick={() => favMutation.mutate(note.id)} className={`p-1 rounded transition-colors ${note.is_favorite ? "text-amber-400" : "text-surface-600 hover:text-amber-400"}`}><Star size={14} fill={note.is_favorite ? "currentColor" : "none"} /></button>
                </div>
              </div>
              {note.content && <p className="text-sm text-surface-500 line-clamp-3 leading-relaxed">{truncate(note.content.replace(/<[^>]+>/g, ""), 120)}</p>}
              <div className="flex flex-wrap gap-1.5">
                {note.category && <span className="badge badge-blue text-xs">{note.category}</span>}
                {note.tags?.map((t) => <span key={t} className="badge badge-gray text-xs"><Tag size={9} className="mr-0.5" />{t}</span>)}
              </div>
              <div className="flex items-center justify-between pt-1 border-t border-surface-600">
                <span className="text-xs text-surface-600">{timeAgo(note.updated_at)}</span>
                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button onClick={() => setModal({ open: true, note })} className="btn-ghost text-xs px-2 py-1">Düzenle</button>
                  <button onClick={() => setDeleteModal({ open: true, noteId: note.id })} className="btn-ghost text-xs px-2 py-1 text-red-400">Sil</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
      <Modal open={modal.open} onClose={() => setModal({ open: false })} title={modal.note ? "Notu Düzenle" : "Yeni Not"} size="lg"><NoteEditor note={modal.note} onClose={() => setModal({ open: false })} /></Modal>
      <ConfirmDialog open={deleteModal.open} onClose={() => setDeleteModal({ open: false })} onConfirm={() => deleteModal.noteId && deleteMutation.mutate(deleteModal.noteId)} title="Notu Sil" description="Bu notu silmek istediğinizden emin misiniz?" loading={deleteMutation.isPending} />
    </div>
  );
}
