'use client'

import * as React from 'react'
import Link from 'next/link'
import { PlusCircle, Search, Filter, LayoutGrid, List } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { DashboardHeader } from '@/components/dashboard/dashboard-header'
import { PropertyTable } from '@/components/dashboard/property-table'
import { PropertyCard } from '@/components/property/property-card'
import { PropertyDetailModal } from '@/components/property/property-detail-modal'
import { mockProperties } from '@/lib/mock-data'
import { Property } from '@/lib/types'
import { cn } from '@/lib/utils'

export default function PropertiesPage() {
  const [viewMode, setViewMode] = React.useState<'table' | 'grid'>('table')
  const [searchQuery, setSearchQuery] = React.useState('')
  const [statusFilter, setStatusFilter] = React.useState('all')
  const [typeFilter, setTypeFilter] = React.useState('all')
  const [selectedProperty, setSelectedProperty] = React.useState<Property | null>(null)

  const filteredProperties = mockProperties.filter((property) => {
    const matchesSearch =
      property.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      property.neighborhood.toLowerCase().includes(searchQuery.toLowerCase()) ||
      property.city.toLowerCase().includes(searchQuery.toLowerCase())

    const matchesStatus = statusFilter === 'all' || property.status === statusFilter
    const matchesType = typeFilter === 'all' || property.propertyType === typeFilter

    return matchesSearch && matchesStatus && matchesType
  })

  return (
    <>
      <DashboardHeader
        title="Imóveis"
        description={`${filteredProperties.length} imóveis cadastrados`}
      >
        <Link href="/dashboard/imoveis/novo">
          <Button className="bg-primary text-primary-foreground hover:bg-primary/90">
            <PlusCircle className="size-4 mr-2" />
            Novo Imóvel
          </Button>
        </Link>
      </DashboardHeader>

      <main className="p-4 lg:p-8">
        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              type="search"
              placeholder="Buscar por título, bairro ou cidade..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 bg-card"
            />
          </div>

          <div className="flex gap-2">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32 bg-card">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="active">Ativos</SelectItem>
                <SelectItem value="inactive">Inativos</SelectItem>
                <SelectItem value="sold">Vendidos</SelectItem>
                <SelectItem value="rented">Alugados</SelectItem>
              </SelectContent>
            </Select>

            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger className="w-36 bg-card">
                <SelectValue placeholder="Tipo" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos os tipos</SelectItem>
                <SelectItem value="apartment">Apartamento</SelectItem>
                <SelectItem value="house">Casa</SelectItem>
                <SelectItem value="commercial">Comercial</SelectItem>
                <SelectItem value="land">Terreno</SelectItem>
                <SelectItem value="studio">Studio</SelectItem>
              </SelectContent>
            </Select>

            <div className="flex border border-border rounded-md overflow-hidden">
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'rounded-none',
                  viewMode === 'table' && 'bg-muted'
                )}
                onClick={() => setViewMode('table')}
                aria-label="Visualização em tabela"
              >
                <List className="size-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'rounded-none',
                  viewMode === 'grid' && 'bg-muted'
                )}
                onClick={() => setViewMode('grid')}
                aria-label="Visualização em grade"
              >
                <LayoutGrid className="size-4" />
              </Button>
            </div>
          </div>
        </div>

        {/* Content */}
        {viewMode === 'table' ? (
          <PropertyTable
            properties={filteredProperties}
            onView={setSelectedProperty}
            onEdit={(property) => console.log('Edit', property)}
            onDelete={(property) => console.log('Delete', property)}
          />
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredProperties.map((property) => (
              <PropertyCard
                key={property.id}
                property={property}
                onSelect={setSelectedProperty}
              />
            ))}
          </div>
        )}

        {filteredProperties.length === 0 && (
          <div className="text-center py-12">
            <div className="size-16 rounded-full bg-muted flex items-center justify-center mx-auto mb-4">
              <Filter className="size-8 text-muted-foreground" />
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">
              Nenhum imóvel encontrado
            </h3>
            <p className="text-muted-foreground text-sm mb-4">
              Tente ajustar os filtros ou adicione um novo imóvel.
            </p>
            <Link href="/dashboard/imoveis/novo">
              <Button className="bg-primary text-primary-foreground hover:bg-primary/90">
                <PlusCircle className="size-4 mr-2" />
                Cadastrar Imóvel
              </Button>
            </Link>
          </div>
        )}
      </main>

      <PropertyDetailModal
        property={selectedProperty}
        open={selectedProperty !== null}
        onOpenChange={(open) => !open && setSelectedProperty(null)}
      />
    </>
  )
}
