'use client';

import { useState } from 'react';
import { FolderPlus, Pin, Trash2 } from 'lucide-react';
import type { Project } from '../../lib/types';
import { addProject, deleteProject, updateProject } from '../../lib/db';

interface ProjectSidebarProps {
  projects: Project[];
  activeProjectId?: string;
  onSelect: (projectId: string | undefined) => void;
  onProjectsChanged: () => void;
}

export function ProjectSidebar({
  projects,
  activeProjectId,
  onSelect,
  onProjectsChanged,
}: ProjectSidebarProps) {
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');

  const handleCreate = async () => {
    if (!newName.trim()) return;
    const project: Project = {
      id: crypto.randomUUID(),
      name: newName.trim(),
      icon: '📁',
      conversationIds: [],
      pinned: false,
      createdAt: Date.now(),
    };
    await addProject(project);
    setNewName('');
    setCreating(false);
    onProjectsChanged();
    onSelect(project.id);
  };

  const handlePin = async (id: string, pinned: boolean) => {
    await updateProject(id, { pinned: !pinned });
    onProjectsChanged();
  };

  const handleDelete = async (id: string) => {
    await deleteProject(id);
    if (activeProjectId === id) onSelect(undefined);
    onProjectsChanged();
  };

  return (
    <div className="border-t border-white/10 px-3 py-2">
      <div className="mb-1 flex items-center justify-between">
        <span className="text-[10px] font-medium uppercase tracking-wider text-[var(--text-tertiary)]">
          Projects
        </span>
        <button
          type="button"
          onClick={() => setCreating(true)}
          className="text-[var(--text-tertiary)] hover:text-[var(--text-primary)]"
          title="New project"
        >
          <FolderPlus size={13} />
        </button>
      </div>

      {creating && (
        <div className="mb-1 flex gap-1">
          <input
            value={newName}
            onChange={e => setNewName(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter') void handleCreate();
              if (e.key === 'Escape') setCreating(false);
            }}
            autoFocus
            className="min-w-0 flex-1 rounded border border-white/10 bg-[var(--surface-card)] px-2 py-0.5 text-xs text-[var(--text-primary)] outline-none"
            placeholder="Project name"
          />
        </div>
      )}

      <button
        type="button"
        onClick={() => onSelect(undefined)}
        className={`mb-0.5 block w-full rounded px-2 py-1 text-left text-xs ${!activeProjectId ? 'bg-white/5 text-[var(--accent-primary)]' : 'text-[var(--text-secondary)] hover:bg-white/5'}`}
      >
        All Conversations
      </button>

      {projects.map(p => (
        <div
          key={p.id}
          className={`group mb-0.5 flex items-center gap-1 rounded px-2 py-1 text-xs ${activeProjectId === p.id ? 'bg-white/5 text-[var(--accent-primary)]' : 'text-[var(--text-secondary)] hover:bg-white/5'}`}
        >
          <button
            type="button"
            onClick={() => onSelect(p.id)}
            className="flex min-w-0 flex-1 items-center gap-1 text-left"
          >
            <span>{p.icon}</span>
            <span className="truncate">{p.name}</span>
          </button>
          <div className="flex gap-0.5 opacity-0 group-hover:opacity-100">
            <button
              type="button"
              onClick={() => void handlePin(p.id, p.pinned)}
              className={
                p.pinned
                  ? 'text-[var(--accent-secondary)]'
                  : 'text-[var(--text-tertiary)] hover:text-[var(--text-primary)]'
              }
              title={p.pinned ? 'Unpin' : 'Pin'}
            >
              <Pin size={10} />
            </button>
            <button
              type="button"
              onClick={() => void handleDelete(p.id)}
              className="text-[var(--text-tertiary)] hover:text-[var(--danger)]"
              title="Delete"
            >
              <Trash2 size={10} />
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
