'use client'

import * as React from 'react'
import {
  X,
  ChevronLeft,
  ChevronRight,
  Bed,
  Bath,
  Car,
  Maximize2,
  MapPin,
  Heart,
  Share2,
  Phone,
  MessageCircle,
  RefreshCw,
  CheckCircle2,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { Property } from '@/lib/types'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from '@/components/ui/dialog'
import { agency } from '@/lib/mock-data'

interface PropertyDetailModalProps {
  property: Property | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

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

export function PropertyDetailModal({ property, open, onOpenChange }: PropertyDetailModalProps) {
  const [currentImageIndex, setCurrentImageIndex] = React.useState(0)
  const [isFavorite, setIsFavorite] = React.useState(false)

  React.useEffect(() => {
    if (open) {
      setCurrentImageIndex(0)
    }
  }, [open])

  if (!property) return null

  const handlePreviousImage = () => {
    setCurrentImageIndex((prev) =>
      prev === 0 ? property.images.length - 1 : prev - 1
    )
  }

  const handleNextImage = () => {
    setCurrentImageIndex((prev) =>
      prev === property.images.length - 1 ? 0 : prev + 1
    )
  }

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent 
        className="max-w-5xl p-0 overflow-hidden max-h-[90vh] overflow-y-auto"
        showCloseButton={false}
      >
        <DialogTitle className="sr-only">{property.title}</DialogTitle>
        
        {/* Image Gallery */}
        <div className="relative aspect-[16/9] bg-muted">
          <img
            src={property.images[currentImageIndex]}
            alt={`${property.title} - Foto ${currentImageIndex + 1}`}
            className="w-full h-full object-cover"
          />

          {/* Close button */}
          <button
            onClick={() => onOpenChange(false)}
            className="absolute top-4 right-4 size-10 rounded-full bg-card/90 text-foreground flex items-center justify-center hover:bg-card transition-colors z-10"
            aria-label="Fechar"
          >
            <X className="size-5" />
          </button>

          {/* Navigation arrows */}
          {property.images.length > 1 && (
            <>
              <button
                onClick={handlePreviousImage}
                className="absolute left-4 top-1/2 -translate-y-1/2 size-10 rounded-full bg-card/90 text-foreground flex items-center justify-center hover:bg-card transition-colors"
                aria-label="Foto anterior"
              >
                <ChevronLeft className="size-6" />
              </button>
              <button
                onClick={handleNextImage}
                className="absolute right-4 top-1/2 -translate-y-1/2 size-10 rounded-full bg-card/90 text-foreground flex items-center justify-center hover:bg-card transition-colors"
                aria-label="Próxima foto"
              >
                <ChevronRight className="size-6" />
              </button>
            </>
          )}

          {/* Image counter */}
          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-foreground/80 text-card text-sm">
            {currentImageIndex + 1} / {property.images.length}
          </div>

          {/* Badges */}
          <div className="absolute top-4 left-4 flex flex-wrap gap-2">
            {property.isPremium && (
              <Badge className="bg-primary text-primary-foreground">
                Premium
              </Badge>
            )}
            {property.isNew && (
              <Badge className="bg-secondary text-secondary-foreground">
                Novo
              </Badge>
            )}
            {property.acceptsTrade && (
              <Badge variant="outline" className="bg-card/90 border-primary text-primary">
                <RefreshCw className="size-3 mr-1" />
                Aceita Permuta
              </Badge>
            )}
          </div>
        </div>

        {/* Thumbnail strip */}
        {property.images.length > 1 && (
          <div className="flex gap-2 p-4 overflow-x-auto bg-muted/30">
            {property.images.map((image, idx) => (
              <button
                key={idx}
                onClick={() => setCurrentImageIndex(idx)}
                className={cn(
                  'flex-shrink-0 size-16 rounded-lg overflow-hidden border-2 transition-all',
                  currentImageIndex === idx
                    ? 'border-primary'
                    : 'border-transparent opacity-70 hover:opacity-100'
                )}
              >
                <img
                  src={image}
                  alt={`Miniatura ${idx + 1}`}
                  className="w-full h-full object-cover"
                />
              </button>
            ))}
          </div>
        )}

        {/* Content */}
        <div className="p-6 lg:p-8">
          <div className="grid lg:grid-cols-3 gap-8">
            {/* Main content */}
            <div className="lg:col-span-2 space-y-6">
              {/* Header */}
              <div>
                <div className="flex items-start justify-between gap-4 mb-2">
                  <div>
                    <p className="text-sm text-muted-foreground mb-1">
                      {propertyTypeLabels[property.propertyType]}
                    </p>
                    <h2 className="text-2xl lg:text-3xl font-bold text-foreground text-balance">
                      {property.title}
                    </h2>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => setIsFavorite(!isFavorite)}
                      aria-label={isFavorite ? 'Remover dos favoritos' : 'Adicionar aos favoritos'}
                    >
                      <Heart className={cn('size-5', isFavorite && 'fill-primary text-primary')} />
                    </Button>
                    <Button variant="outline" size="icon" aria-label="Compartilhar">
                      <Share2 className="size-5" />
                    </Button>
                  </div>
                </div>
                <p className="flex items-center gap-1.5 text-muted-foreground">
                  <MapPin className="size-4" />
                  {property.address}, {property.neighborhood}, {property.city} - {property.state}
                </p>
              </div>

              {/* Quick specs */}
              <div className="flex flex-wrap gap-6 py-4 border-y border-border">
                <div className="flex items-center gap-2">
                  <Maximize2 className="size-5 text-primary" />
                  <div>
                    <p className="font-semibold text-foreground">{property.area}m²</p>
                    <p className="text-xs text-muted-foreground">Área total</p>
                  </div>
                </div>
                {property.bedrooms > 0 && (
                  <div className="flex items-center gap-2">
                    <Bed className="size-5 text-primary" />
                    <div>
                      <p className="font-semibold text-foreground">{property.bedrooms}</p>
                      <p className="text-xs text-muted-foreground">
                        {property.bedrooms === 1 ? 'Quarto' : 'Quartos'}
                        {property.suites ? ` (${property.suites} suíte${property.suites > 1 ? 's' : ''})` : ''}
                      </p>
                    </div>
                  </div>
                )}
                {property.bathrooms > 0 && (
                  <div className="flex items-center gap-2">
                    <Bath className="size-5 text-primary" />
                    <div>
                      <p className="font-semibold text-foreground">{property.bathrooms}</p>
                      <p className="text-xs text-muted-foreground">
                        {property.bathrooms === 1 ? 'Banheiro' : 'Banheiros'}
                      </p>
                    </div>
                  </div>
                )}
                {property.parkingSpaces > 0 && (
                  <div className="flex items-center gap-2">
                    <Car className="size-5 text-primary" />
                    <div>
                      <p className="font-semibold text-foreground">{property.parkingSpaces}</p>
                      <p className="text-xs text-muted-foreground">
                        {property.parkingSpaces === 1 ? 'Vaga' : 'Vagas'}
                      </p>
                    </div>
                  </div>
                )}
              </div>

              {/* Description */}
              <div>
                <h3 className="font-semibold text-foreground mb-3">Sobre o imóvel</h3>
                <p className="text-muted-foreground leading-relaxed">
                  {property.description}
                </p>
              </div>

              {/* Features */}
              <div>
                <h3 className="font-semibold text-foreground mb-3">Características</h3>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {property.features.map((feature) => (
                    <div key={feature} className="flex items-center gap-2 text-sm">
                      <CheckCircle2 className="size-4 text-secondary flex-shrink-0" />
                      <span className="text-foreground">{feature}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Sidebar - Pricing and Contact */}
            <div className="lg:col-span-1">
              <div className="sticky top-4 bg-muted/30 rounded-xl p-6 border border-border/50">
                {/* Price */}
                <div className="mb-6">
                  <p className="text-sm text-muted-foreground mb-1">
                    {property.transactionType === 'rent' ? 'Aluguel' : 'Venda'}
                  </p>
                  <p className="text-3xl font-bold text-primary">
                    {formatPrice(property.price)}
                  </p>
                  {property.rentPrice && (
                    <p className="text-sm text-muted-foreground mt-1">
                      ou {formatPrice(property.rentPrice)}/mês para aluguel
                    </p>
                  )}
                </div>

                {/* Monthly costs */}
                {(property.condoFee || property.iptu) && (
                  <div className="mb-6 p-4 bg-card rounded-lg">
                    <p className="text-sm font-medium text-foreground mb-2">Custos mensais</p>
                    <div className="space-y-1 text-sm">
                      {property.condoFee && (
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">Condomínio</span>
                          <span className="text-foreground">{formatPrice(property.condoFee)}</span>
                        </div>
                      )}
                      {property.iptu && (
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">IPTU</span>
                          <span className="text-foreground">{formatPrice(property.iptu)}</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                <Separator className="my-6" />

                {/* Contact buttons */}
                <div className="space-y-3">
                  <a
                    href={`https://wa.me/${agency.whatsapp}?text=Olá! Tenho interesse no imóvel: ${property.title}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-full"
                  >
                    <Button className="w-full bg-secondary text-secondary-foreground hover:bg-secondary/90 h-12">
                      <MessageCircle className="size-5 mr-2" />
                      WhatsApp
                    </Button>
                  </a>
                  <a href={`tel:${agency.phone.replace(/\D/g, '')}`}>
                    <Button variant="outline" className="w-full h-12">
                      <Phone className="size-5 mr-2" />
                      Ligar Agora
                    </Button>
                  </a>
                </div>

                {/* Agent info */}
                <div className="mt-6 flex items-center gap-3">
                  <div className="size-12 rounded-full bg-primary/10 flex items-center justify-center">
                    <span className="text-primary font-semibold">PD</span>
                  </div>
                  <div>
                    <p className="font-medium text-foreground text-sm">{agency.name}</p>
                    <p className="text-xs text-muted-foreground">{agency.creci}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
