
import React, { useState, useEffect, useCallback } from 'react';
import type { Person, NewPerson } from './types';
import { getPeople, addPerson } from './services/apiService';
import PersonList from './components/PersonList';
import AddPersonForm from './components/AddPersonForm';
import Modal from './components/Modal';
import { PlusIcon, UsersIcon } from './components/Icons';

const App: React.FC = () => {
  const [people, setPeople] = useState<Person[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

  const fetchPeople = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);
      const data = await getPeople();
      setPeople(data);
    } catch (err) {
      setError('Failed to fetch people. Please try again later.');
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchPeople();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleAddPerson = async (newPerson: NewPerson) => {
    try {
      const addedPerson = await addPerson(newPerson);
      setPeople((prevPeople) => [...prevPeople, addedPerson]);
      setIsModalOpen(false);
    } catch (err) {
      setError('Failed to add person. Please try again.');
      console.error(err);
    }
  };

  const renderContent = () => {
    if (isLoading) {
      return <p className="text-center text-gray-500 dark:text-gray-400 mt-8">Loading profiles...</p>;
    }
    if (error) {
      return <p className="text-center text-red-500 dark:text-red-400 mt-8">{error}</p>;
    }
    if (people.length === 0) {
      return (
        <div className="text-center py-16 px-6 bg-white dark:bg-gray-800 rounded-lg shadow-md">
            <UsersIcon className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-lg font-medium text-gray-900 dark:text-white">No profiles yet</h3>
            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">Get started by adding a new profile.</p>
            <div className="mt-6">
                <button
                    onClick={() => setIsModalOpen(true)}
                    type="button"
                    className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                    <PlusIcon className="-ml-1 mr-2 h-5 w-5" />
                    Add Profile
                </button>
            </div>
        </div>
      );
    }
    return <PersonList people={people} />;
  };

  return (
    <div className="min-h-screen bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 font-sans">
      <div className="container mx-auto p-4 sm:p-6 lg:p-8">
        <header className="flex items-center justify-between mb-8 pb-4 border-b border-gray-200 dark:border-gray-700">
          <h1 className="text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 dark:text-white">
            Profile Linker
          </h1>
          {people.length > 0 && (
            <button
              onClick={() => setIsModalOpen(true)}
              className="inline-flex items-center justify-center px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
            >
              <PlusIcon className="w-5 h-5 mr-2 -ml-1" />
              <span>Add Profile</span>
            </button>
          )}
        </header>

        <main>
          {renderContent()}
        </main>
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="Add New Profile">
        <AddPersonForm onSubmit={handleAddPerson} onCancel={() => setIsModalOpen(false)} />
      </Modal>
    </div>
  );
};

export default App;
