import { useState } from 'react';
import { Plus, Users } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import api from '@/lib/api';
import type { Person } from '@/types';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { GridSkeleton } from '@/components/ui/skeleton';
import { EmptyState } from '@/components/ui/empty-state';
import PersonCard from './PersonCard';
import PersonForm from './PersonForm';

export default function PeoplePage() {
  const [showForm, setShowForm] = useState(false);
  const [editingPerson, setEditingPerson] = useState<Person | null>(null);
  const [search, setSearch] = useState('');

  const { data: people = [], isLoading } = useQuery({
    queryKey: ['people'],
    queryFn: async () => {
      const { data } = await api.get<Person[]>('/people');
      return data;
    },
  });

  const filteredPeople = people.filter((person) =>
    person.name.toLowerCase().includes(search.toLowerCase())
  );

  const handleEdit = (person: Person) => {
    setEditingPerson(person);
    setShowForm(true);
  };

  const handleCloseForm = () => {
    setShowForm(false);
    setEditingPerson(null);
  };

  return (
    <div className="flex flex-col h-full">
      <div className="border-b bg-card px-6 py-4">
        <div className="flex items-center justify-between mb-4">
          <h1 className="text-3xl font-bold">People</h1>
          <Button onClick={() => setShowForm(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Add Person
          </Button>
        </div>

        <Input
          placeholder="Search people..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="max-w-md"
        />
      </div>

      <div className="flex-1 overflow-y-auto p-6">
        {isLoading ? (
          <GridSkeleton cards={6} />
        ) : filteredPeople.length === 0 ? (
          <EmptyState
            icon={Users}
            title="No contacts yet"
            description="Add people to your directory to keep track of contacts and relationships."
            actionLabel="Add Person"
            onAction={() => setShowForm(true)}
          />
        ) : (
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {filteredPeople.map((person) => (
              <PersonCard key={person.id} person={person} onEdit={handleEdit} />
            ))}
          </div>
        )}
      </div>

      {showForm && <PersonForm person={editingPerson} onClose={handleCloseForm} />}
    </div>
  );
}
