import React, { useState, useEffect } from 'react';
import { Project } from '../types';
import Spinner from './Spinner';

interface ProjectsDashboardProps {
  onSelectProject: (project: { id: string, name: string }) => void;
}

const ProjectsDashboard: React.FC<ProjectsDashboardProps> = ({ onSelectProject }) => {
  const [projects, setProjects] = useState<Project[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [projectName, setProjectName] = useState('');

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

  const fetchProjects = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await fetch('/api/projects');
      if (!response.ok) {
        throw new Error('Projeler yüklenemedi.');
      }
      const data = await response.json();
      setProjects(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Bilinmeyen bir hata oluştu.');
    } finally {
      setIsLoading(false);
    }
  };

  const openModal = (project: Project | null = null) => {
    setEditingProject(project);
    setProjectName(project ? project.name : '');
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setEditingProject(null);
    setProjectName('');
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!projectName.trim()) return;

    const url = editingProject ? `/api/projects/${editingProject.id}` : '/api/projects';
    const method = editingProject ? 'PUT' : 'POST';

    try {
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: projectName.trim() }),
      });
      if (!response.ok) {
        throw new Error('Proje kaydedilemedi.');
      }
      fetchProjects(); // Refresh the list
      closeModal();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Kaydetme sırasında hata.');
    }
  };

  const handleDelete = async (projectId: string) => {
    if (window.confirm('Bu projeyi ve içindeki tüm karakterleri/sahneleri silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.')) {
      try {
        const response = await fetch(`/api/projects/${projectId}`, { method: 'DELETE' });
        if (!response.ok) {
          throw new Error('Proje silinemedi.');
        }
        fetchProjects(); // Refresh the list
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Silme sırasında hata.');
      }
    }
  };

  return (
    <div className="min-h-screen bg-gray-900 text-gray-200 p-4 sm:p-6 lg:p-8">
      <div className="max-w-5xl mx-auto">
        <header className="text-center mb-10">
          <h1 className="text-4xl sm:text-5xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-indigo-600">
            Proje Yöneticisi
          </h1>
          <p className="mt-2 text-gray-400">Var olan bir projeyi seçin veya yeni bir tane oluşturun.</p>
        </header>

        {error && (
          <div className="bg-red-900 border border-red-600 text-red-200 px-4 py-3 rounded-lg relative mb-6" role="alert">
            <span className="block sm:inline">{error}</span>
            <button onClick={() => setError(null)} className="absolute top-0 bottom-0 right-0 px-4 py-3">&times;</button>
          </div>
        )}

        <div className="flex justify-end mb-6">
          <button onClick={() => openModal()} className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clipRule="evenodd" />
            </svg>
            Yeni Proje Oluştur
          </button>
        </div>

        {isLoading ? (
          <div className="flex justify-center items-center h-64"><Spinner size="h-12 w-12" /></div>
        ) : (
          <div className="space-y-4">
            {projects.length > 0 ? projects.map(project => (
              <div key={project.id} className="bg-gray-800 rounded-lg p-4 flex justify-between items-center transition-all hover:bg-gray-700/50 hover:ring-2 hover:ring-indigo-500">
                <div className="cursor-pointer flex-grow" onClick={() => onSelectProject({ id: project.id, name: project.name })}>
                  <h2 className="font-bold text-xl text-gray-100">{project.name}</h2>
                  <p className="text-xs text-gray-400">Son Güncelleme: {new Date(project.updatedAt).toLocaleString()}</p>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => openModal(project)} className="p-2 bg-gray-700 hover:bg-gray-600 rounded-md" title="Yeniden Adlandır">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.5L15.232 5.232z" />
                    </svg>
                  </button>
                  <button onClick={() => handleDelete(project.id)} className="p-2 bg-gray-700 hover:bg-red-600 rounded-md" title="Sil">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>
            )) : (
              <div className="text-center py-16 bg-gray-800 rounded-xl">
                <p className="text-gray-400 text-lg">Henüz hiç proje oluşturulmadı.</p>
                <p className="text-gray-500 mt-2">Başlamak için 'Yeni Proje Oluştur' butonuna tıklayın.</p>
              </div>
            )}
          </div>
        )}
      </div>

      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50">
          <div className="bg-gray-800 rounded-xl shadow-2xl p-6 max-w-md w-full">
            <h3 className="text-2xl font-bold mb-4">{editingProject ? 'Projeyi Yeniden Adlandır' : 'Yeni Proje Oluştur'}</h3>
            <form onSubmit={handleSave}>
              <input
                type="text"
                value={projectName}
                onChange={(e) => setProjectName(e.target.value)}
                placeholder="Proje Adı"
                className="w-full bg-gray-700 text-white rounded-md px-4 py-3 focus:ring-2 focus:ring-indigo-500 focus:outline-none transition"
                autoFocus
              />
              <div className="flex justify-end gap-4 mt-6">
                <button type="button" onClick={closeModal} className="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-6 rounded-md transition">İptal</button>
                <button type="submit" className="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-6 rounded-md transition">Kaydet</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProjectsDashboard;
