'use client'

import * as React from 'react'
import Link from 'next/link'
import {
  MoreHorizontal,
  Eye,
  Pencil,
  Trash2,
  Building2,
  CheckCircle2,
  XCircle,
  Clock,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { Property } from '@/lib/types'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

interface PropertyTableProps {
  properties: Property[]
  onEdit?: (property: Property) => void
  onDelete?: (property: Property) => void
  onView?: (property: Property) => void
}

function formatPrice(value: number): string {
  return new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL',
    maximumFractionDigits: 0,
  }).format(value)
}

const statusConfig = {
  active: {
    label: 'Ativo',
    icon: CheckCircle2,
    className: 'bg-secondary/10 text-secondary border-secondary/20',
  },
  inactive: {
    label: 'Inativo',
    icon: XCircle,
    className: 'bg-muted text-muted-foreground border-border',
  },
  sold: {
    label: 'Vendido',
    icon: CheckCircle2,
    className: 'bg-primary/10 text-primary border-primary/20',
  },
  rented: {
    label: 'Alugado',
    icon: Clock,
    className: 'bg-accent/20 text-accent-foreground border-accent/30',
  },
}

const propertyTypeLabels: Record<string, string> = {
  apartment: 'Apartamento',
  house: 'Casa',
  commercial: 'Comercial',
  land: 'Terreno',
  studio: 'Studio',
}

export function PropertyTable({
  properties,
  onEdit,
  onDelete,
  onView,
}: PropertyTableProps) {
  const [selectedIds, setSelectedIds] = React.useState<Set<string>>(new Set())

  const toggleAll = () => {
    if (selectedIds.size === properties.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(properties.map((p) => p.id)))
    }
  }

  const toggleOne = (id: string) => {
    const next = new Set(selectedIds)
    if (next.has(id)) {
      next.delete(id)
    } else {
      next.add(id)
    }
    setSelectedIds(next)
  }

  return (
    <div className="border border-border rounded-xl overflow-hidden">
      <Table>
        <TableHeader>
          <TableRow className="bg-muted/50 hover:bg-muted/50">
            <TableHead className="w-12">
              <Checkbox
                checked={selectedIds.size === properties.length && properties.length > 0}
                onCheckedChange={toggleAll}
                aria-label="Selecionar todos"
              />
            </TableHead>
            <TableHead>Imóvel</TableHead>
            <TableHead>Tipo</TableHead>
            <TableHead>Localização</TableHead>
            <TableHead className="text-right">Preço</TableHead>
            <TableHead>Status</TableHead>
            <TableHead className="w-12"></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {properties.map((property) => {
            const status = statusConfig[property.status]
            return (
              <TableRow
                key={property.id}
                className={cn(selectedIds.has(property.id) && 'bg-muted/30')}
              >
                <TableCell>
                  <Checkbox
                    checked={selectedIds.has(property.id)}
                    onCheckedChange={() => toggleOne(property.id)}
                    aria-label={`Selecionar ${property.title}`}
                  />
                </TableCell>
                <TableCell>
                  <div className="flex items-center gap-3">
                    <div className="size-12 rounded-lg overflow-hidden flex-shrink-0 bg-muted">
                      <img
                        src={property.images[0]}
                        alt={property.title}
                        className="w-full h-full object-cover"
                      />
                    </div>
                    <div className="min-w-0">
                      <p className="font-medium text-foreground truncate max-w-[200px]">
                        {property.title}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {property.area}m² • {property.bedrooms} quartos • {property.parkingSpaces} vagas
                      </p>
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  <div className="flex items-center gap-2">
                    <Building2 className="size-4 text-muted-foreground" />
                    <span className="text-sm">{propertyTypeLabels[property.propertyType]}</span>
                  </div>
                </TableCell>
                <TableCell>
                  <div className="text-sm">
                    <p className="text-foreground">{property.neighborhood}</p>
                    <p className="text-muted-foreground">{property.city} - {property.state}</p>
                  </div>
                </TableCell>
                <TableCell className="text-right">
                  <p className="font-semibold text-foreground">{formatPrice(property.price)}</p>
                  {property.rentPrice && (
                    <p className="text-xs text-muted-foreground">
                      Aluguel: {formatPrice(property.rentPrice)}/mês
                    </p>
                  )}
                </TableCell>
                <TableCell>
                  <Badge
                    variant="outline"
                    className={cn('gap-1', status.className)}
                  >
                    <status.icon className="size-3" />
                    {status.label}
                  </Badge>
                </TableCell>
                <TableCell>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="size-8">
                        <MoreHorizontal className="size-4" />
                        <span className="sr-only">Ações</span>
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem onClick={() => onView?.(property)}>
                        <Eye className="size-4 mr-2" />
                        Visualizar
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => onEdit?.(property)}>
                        <Pencil className="size-4 mr-2" />
                        Editar
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem
                        onClick={() => onDelete?.(property)}
                        className="text-destructive focus:text-destructive"
                      >
                        <Trash2 className="size-4 mr-2" />
                        Excluir
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableCell>
              </TableRow>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
