'use client'

import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Search, Loader2 } from 'lucide-react'

import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'

interface Resident {
  id: number
  name: string
  room: string
  table?: string
  station?: string
  highCaloric?: boolean
  aversions?: string
  notes?: string
  active: boolean
}

export default function ResidentsListPage() {
  const router = useRouter()
  const [residents, setResidents] = useState<Resident[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')

  useEffect(() => {
    const fetchResidents = async () => {
      try {
        const res = await fetch('/api/residents?where[active][equals]=true&limit=100&sort=name', {
          credentials: 'include',
        })
        if (res.ok) {
          const data = await res.json()
          setResidents(data.docs || [])
        } else if (res.status === 401) {
          router.push('/caregiver/login')
        }
      } catch (err) {
        console.error('Error fetching residents:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchResidents()
  }, [router])

  const filteredResidents = residents.filter(
    (r) =>
      r.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.room.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (r.station && r.station.toLowerCase().includes(searchQuery.toLowerCase())),
  )

  return (
    <div className="min-h-screen bg-muted/50">
      <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="container flex h-16 items-center">
          <Button variant="ghost" size="sm" asChild>
            <Link href="/caregiver/dashboard">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back
            </Link>
          </Button>
          <h1 className="ml-4 text-xl font-semibold">Residents</h1>
        </div>
      </header>

      <main className="container py-6">
        <div className="mb-6">
          <h2 className="text-2xl font-bold tracking-tight">Residents</h2>
          <p className="text-muted-foreground">View resident information and dietary requirements</p>
        </div>

        <div className="mb-6">
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              type="text"
              placeholder="Search by name, room, or station..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
        </div>

        {loading ? (
          <div className="flex items-center justify-center p-12">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          </div>
        ) : filteredResidents.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center p-8 text-center">
              <p className="text-muted-foreground">No residents found.</p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {filteredResidents.map((resident) => (
              <Card key={resident.id}>
                <CardContent className="px-3 py-2">
                  <div className="flex items-center justify-between gap-2">
                    <div className="font-medium">{resident.name}</div>
                    {resident.highCaloric && (
                      <Badge variant="secondary" className="bg-yellow-100 text-yellow-800 text-xs px-1.5 py-0">
                        High Cal
                      </Badge>
                    )}
                  </div>
                  <div className="flex flex-wrap gap-x-2 text-xs text-muted-foreground">
                    <span>Room {resident.room}</span>
                    {resident.table && <span>• Table {resident.table}</span>}
                    {resident.station && <span>• {resident.station}</span>}
                  </div>

                  {(resident.aversions || resident.notes) && (
                    <div className="mt-1 text-xs text-muted-foreground">
                      {resident.aversions && (
                        <div className="truncate">
                          <span className="font-medium">Aversions:</span> {resident.aversions}
                        </div>
                      )}
                      {resident.notes && (
                        <div className="truncate">
                          <span className="font-medium">Notes:</span> {resident.notes}
                        </div>
                      )}
                    </div>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </main>
    </div>
  )
}
