import { useState } from 'react';
import { X, Briefcase } from 'lucide-react';
import { useAppStore } from '../../stores/useAppStore';
import { useUIStore } from '../../stores/useUIStore';
import { useChatStore } from '../../stores/useChatStore';

export function NewProjectModal() {
  const { isNewProjectModalOpen, setNewProjectModalOpen, setEditingOutline } = useUIStore();
  const { addProject, setCurrentProjectId } = useAppStore();
  const resetChat = useChatStore(s => s.resetChat);
  const closeViewers = useUIStore(s => s.closeViewers);
  const [name, setName] = useState('');

  if (!isNewProjectModalOpen) return null;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    const newId = `p-${Date.now()}`;
    addProject({
      id: newId, name,
      files: [],
      activeTemplate: {
        name: '基础交付规范', version: 'v1.0',
        chapters: [{ id: 'def-1', title: '1.1 项目概况简述', status: 'idle', progress: 0, content: '' }],
      },
    });
    setName('');
    setNewProjectModalOpen(false);
    setCurrentProjectId(newId);
    resetChat();
    closeViewers();
    setEditingOutline(false);
  };

  return (
    <div className="fixed inset-0 bg-slate-950/90 backdrop-blur-2xl z-[150] flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-[3rem] w-full max-w-lg overflow-hidden shadow-2xl flex flex-col animate-zoom-in">
        <div className="px-10 py-8 border-b border-slate-800 flex items-center justify-between bg-slate-900/50">
          <div className="flex items-center gap-4 text-blue-500 font-black uppercase text-sm">
            <Briefcase size={24} /> 工程初始化
          </div>
          <button onClick={() => setNewProjectModalOpen(false)}><X size={24} /></button>
        </div>
        <form onSubmit={handleSubmit} className="p-10 space-y-8 text-left">
          <div className="space-y-3">
            <label className="text-[10px] text-slate-500 font-black uppercase tracking-widest ml-1">项目全称</label>
            <input
              autoFocus required value={name} onChange={(e) => setName(e.target.value)}
              placeholder="输入名称..."
              className="w-full bg-slate-950 border border-slate-800 focus:border-blue-500 rounded-2xl px-6 py-4 text-sm text-slate-200 outline-none"
            />
          </div>
          <div className="flex gap-4">
            <button type="button" onClick={() => setNewProjectModalOpen(false)} className="flex-1 py-4 bg-slate-800 text-white rounded-2xl font-black text-[10px] uppercase tracking-widest">取消</button>
            <button type="submit" className="flex-1 py-4 bg-blue-600 text-white rounded-2xl font-black text-[10px] uppercase shadow-xl">立即创建</button>
          </div>
        </form>
      </div>
    </div>
  );
}
