import { useState, useEffect } from 'react';
import { useAuth } from '../../../stores/auth';
import { getPosts, deletePost, ApiError } from '../../../lib/api';
import type { Post } from '../../../lib/types';

export default function Dashboard() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const logout = useAuth(s => s.logout);

  async function loadPosts() {
    setLoading(true);
    setError('');
    try {
      setPosts(await getPosts());
    } catch (e) {
      setError(e instanceof ApiError ? e.message : 'Failed to load posts.');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { loadPosts(); }, []);

  async function handleDelete(slug: string) {
    if (!confirm(`Are you sure you want to delete "${slug}"?`)) return;
    try {
      await deletePost(slug);
      loadPosts();
    } catch {
      setError('Failed to delete post.');
    }
  }

  function handleLogout() {
    logout();
    window.location.href = '/';
  }

  return (
    <>
      <div className="flex justify-end mb-4">
        <button onClick={handleLogout} className="text-red hover:text-maroon transition-colors font-medium">
          Logout
        </button>
      </div>

      {/* Quick Links */}
      <div className="grid md:grid-cols-3 gap-8 mb-12">
        <QuickLink href="/admin/editor" icon="write" title="Write Post" desc="Create or edit markdown posts." color="mauve" hoverColor="pink" />
        <QuickLink href="/admin/assets" icon="assets" title="Asset Library" desc="Manage images and uploads." color="teal" hoverColor="green" />
        <QuickLink href="/admin/settings" icon="settings" title="Settings" desc="Site title and themes." color="blue" hoverColor="sky" />
      </div>

      {/* Posts List */}
      <section>
        <h2 className="text-2xl font-bold text-mauve mb-6 flex items-center gap-3">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
          Manage Posts
        </h2>
        <div className="space-y-4">
          {loading && (
            <div className="animate-pulse flex space-x-4 p-8 glass">
              <div className="flex-1 space-y-4 py-1">
                <div className="h-4 bg-surface1 rounded w-3/4" />
                <div className="h-4 bg-surface1 rounded w-1/2" />
              </div>
            </div>
          )}
          {error && <div className="glass p-8 text-center text-red">{error}</div>}
          {!loading && posts.length === 0 && !error && (
            <div className="glass p-8 text-center text-subtext0">No posts yet.</div>
          )}
          {posts.map(post => (
            <div key={post.slug} className="glass p-6 flex justify-between items-center group hover:bg-surface0/50 transition-colors">
              <div>
                <h3 className="font-bold text-lavender text-lg">{post.slug}</h3>
                <p className="text-xs text-subtext0" style={{ color: 'var(--subtext0)' }}>/posts/{post.slug}</p>
              </div>
              <div className="flex gap-3">
                <a href={`/admin/editor?edit=${post.slug}`} className="p-2 text-blue hover:bg-blue/10 rounded transition-colors" title="Edit">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
                </a>
                <button onClick={() => handleDelete(post.slug)} className="p-2 text-red hover:bg-red/10 rounded transition-colors" title="Delete">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>
    </>
  );
}

const ICONS: Record<string, JSX.Element> = {
  write: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  assets: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>,
  settings: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>,
};

function QuickLink({ href, icon, title, desc, color, hoverColor }: { href: string; icon: string; title: string; desc: string; color: string; hoverColor: string }) {
  return (
    <a href={href} className="group">
      <div className="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex flex-col items-center text-center gap-4">
        <div className={`bg-${color}/20 p-4 rounded-full text-${color}`}>
          {ICONS[icon]}
        </div>
        <div>
          <h2 className={`text-xl font-bold text-lavender group-hover:text-${hoverColor} transition-colors`}>{title}</h2>
          <p className="text-xs text-subtext0 mt-1">{desc}</p>
        </div>
      </div>
    </a>
  );
}
