'use client'

import * as React from 'react'
import { useRouter } from 'next/navigation'
import {
  Upload,
  X,
  Plus,
  Save,
  ArrowLeft,
  ImagePlus,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { states, cities, neighborhoods, propertyTypes } from '@/lib/mock-data'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Separator } from '@/components/ui/separator'
import { FieldGroup, Field, FieldLabel } from '@/components/ui/field'

interface PropertyFormProps {
  mode?: 'create' | 'edit'
  initialData?: Record<string, unknown>
}

const transactionTypes = [
  { value: 'sale', label: 'Venda' },
  { value: 'rent', label: 'Aluguel' },
  { value: 'both', label: 'Venda e Aluguel' },
]

const statusOptions = [
  { value: 'active', label: 'Ativo' },
  { value: 'inactive', label: 'Inativo' },
]

export function PropertyForm({ mode = 'create', initialData }: PropertyFormProps) {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [selectedState, setSelectedState] = React.useState('')
  const [selectedCity, setSelectedCity] = React.useState('')
  const [features, setFeatures] = React.useState<string[]>([])
  const [newFeature, setNewFeature] = React.useState('')
  const [images, setImages] = React.useState<string[]>([])

  const availableCities = selectedState ? cities[selectedState] || [] : []
  const availableNeighborhoods = selectedCity ? neighborhoods[selectedCity] || [] : []

  const addFeature = () => {
    if (newFeature.trim() && !features.includes(newFeature.trim())) {
      setFeatures([...features, newFeature.trim()])
      setNewFeature('')
    }
  }

  const removeFeature = (feature: string) => {
    setFeatures(features.filter((f) => f !== feature))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    // Simulate form submission
    await new Promise((resolve) => setTimeout(resolve, 1500))
    setIsSubmitting(false)
    router.push('/dashboard/imoveis')
  }

  // Mock images for demo
  const mockImages = [
    'https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?w=400&h=300&fit=crop',
    'https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?w=400&h=300&fit=crop',
  ]

  return (
    <form onSubmit={handleSubmit} className="max-w-4xl">
      <div className="space-y-8">
        {/* Basic Information */}
        <section className="bg-card rounded-xl border border-border/50 p-6">
          <h2 className="text-lg font-semibold text-foreground mb-4">
            Informações Básicas
          </h2>
          <FieldGroup className="space-y-4">
            <Field>
              <FieldLabel htmlFor="title">Título do Anúncio</FieldLabel>
              <Input
                id="title"
                placeholder="Ex: Apartamento de Alto Padrão nos Jardins"
                required
              />
            </Field>

            <div className="grid sm:grid-cols-2 gap-4">
              <Field>
                <FieldLabel htmlFor="propertyType">Tipo de Imóvel</FieldLabel>
                <Select required>
                  <SelectTrigger id="propertyType">
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    {propertyTypes.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>

              <Field>
                <FieldLabel htmlFor="transactionType">Tipo de Transação</FieldLabel>
                <Select required>
                  <SelectTrigger id="transactionType">
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    {transactionTypes.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>
            </div>

            <Field>
              <FieldLabel htmlFor="description">Descrição</FieldLabel>
              <Textarea
                id="description"
                placeholder="Descreva o imóvel detalhadamente..."
                rows={4}
                required
              />
            </Field>
          </FieldGroup>
        </section>

        {/* Location */}
        <section className="bg-card rounded-xl border border-border/50 p-6">
          <h2 className="text-lg font-semibold text-foreground mb-4">
            Localização
          </h2>
          <FieldGroup className="space-y-4">
            <Field>
              <FieldLabel htmlFor="address">Endereço</FieldLabel>
              <Input
                id="address"
                placeholder="Rua, número e complemento"
                required
              />
            </Field>

            <div className="grid sm:grid-cols-3 gap-4">
              <Field>
                <FieldLabel htmlFor="state">Estado</FieldLabel>
                <Select
                  value={selectedState}
                  onValueChange={(v) => {
                    setSelectedState(v)
                    setSelectedCity('')
                  }}
                >
                  <SelectTrigger id="state">
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    {states.map((state) => (
                      <SelectItem key={state.value} value={state.value}>
                        {state.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>

              <Field>
                <FieldLabel htmlFor="city">Cidade</FieldLabel>
                <Select
                  value={selectedCity}
                  onValueChange={setSelectedCity}
                  disabled={!selectedState}
                >
                  <SelectTrigger id="city">
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableCities.map((city) => (
                      <SelectItem key={city.value} value={city.value}>
                        {city.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>

              <Field>
                <FieldLabel htmlFor="neighborhood">Bairro</FieldLabel>
                <Select disabled={!selectedCity}>
                  <SelectTrigger id="neighborhood">
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableNeighborhoods.map((nb) => (
                      <SelectItem key={nb.value} value={nb.value}>
                        {nb.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>
            </div>
          </FieldGroup>
        </section>

        {/* Details */}
        <section className="bg-card rounded-xl border border-border/50 p-6">
          <h2 className="text-lg font-semibold text-foreground mb-4">
            Detalhes do Imóvel
          </h2>
          <FieldGroup className="space-y-4">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <Field>
                <FieldLabel htmlFor="area">Área (m²)</FieldLabel>
                <Input
                  id="area"
                  type="number"
                  placeholder="0"
                  min="0"
                  required
                />
              </Field>

              <Field>
                <FieldLabel htmlFor="bedrooms">Quartos</FieldLabel>
                <Input
                  id="bedrooms"
                  type="number"
                  placeholder="0"
                  min="0"
                  required
                />
              </Field>

              <Field>
                <FieldLabel htmlFor="bathrooms">Banheiros</FieldLabel>
                <Input
                  id="bathrooms"
                  type="number"
                  placeholder="0"
                  min="0"
                  required
                />
              </Field>

              <Field>
                <FieldLabel htmlFor="suites">Suítes</FieldLabel>
                <Input
                  id="suites"
                  type="number"
                  placeholder="0"
                  min="0"
                />
              </Field>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Field>
                <FieldLabel htmlFor="parkingSpaces">Vagas de Garagem</FieldLabel>
                <Input
                  id="parkingSpaces"
                  type="number"
                  placeholder="0"
                  min="0"
                  required
                />
              </Field>

              <Field>
                <FieldLabel htmlFor="status">Status</FieldLabel>
                <Select defaultValue="active">
                  <SelectTrigger id="status">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {statusOptions.map((status) => (
                      <SelectItem key={status.value} value={status.value}>
                        {status.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>
            </div>
          </FieldGroup>
        </section>

        {/* Pricing */}
        <section className="bg-card rounded-xl border border-border/50 p-6">
          <h2 className="text-lg font-semibold text-foreground mb-4">
            Valores
          </h2>
          <FieldGroup className="space-y-4">
            <div className="grid sm:grid-cols-2 gap-4">
              <Field>
                <FieldLabel htmlFor="price">Preço de Venda (R$)</FieldLabel>
                <Input
                  id="price"
                  type="number"
                  placeholder="0"
                  min="0"
                />
              </Field>

              <Field>
                <FieldLabel htmlFor="rentPrice">Preço de Aluguel (R$/mês)</FieldLabel>
                <Input
                  id="rentPrice"
                  type="number"
                  placeholder="0"
                  min="0"
                />
              </Field>
            </div>

            <div className="grid sm:grid-cols-2 gap-4">
              <Field>
                <FieldLabel htmlFor="condoFee">Condomínio (R$/mês)</FieldLabel>
                <Input
                  id="condoFee"
                  type="number"
                  placeholder="0"
                  min="0"
                />
              </Field>

              <Field>
                <FieldLabel htmlFor="iptu">IPTU (R$/mês)</FieldLabel>
                <Input
                  id="iptu"
                  type="number"
                  placeholder="0"
                  min="0"
                />
              </Field>
            </div>

            <div className="flex items-center gap-3 pt-2">
              <Checkbox id="acceptsTrade" />
              <Label htmlFor="acceptsTrade" className="cursor-pointer">
                Aceita permuta
              </Label>
            </div>
          </FieldGroup>
        </section>

        {/* Features */}
        <section className="bg-card rounded-xl border border-border/50 p-6">
          <h2 className="text-lg font-semibold text-foreground mb-4">
            Características
          </h2>
          <div className="flex gap-2 mb-4">
            <Input
              placeholder="Adicionar característica (ex: Piscina, Academia)"
              value={newFeature}
              onChange={(e) => setNewFeature(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addFeature())}
            />
            <Button type="button" variant="outline" onClick={addFeature}>
              <Plus className="size-4" />
            </Button>
          </div>
          <div className="flex flex-wrap gap-2">
            {features.map((feature) => (
              <span
                key={feature}
                className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full bg-primary/10 text-primary text-sm"
              >
                {feature}
                <button
                  type="button"
                  onClick={() => removeFeature(feature)}
                  className="hover:bg-primary/20 rounded-full p-0.5"
                >
                  <X className="size-3" />
                </button>
              </span>
            ))}
            {features.length === 0 && (
              <p className="text-sm text-muted-foreground">
                Nenhuma característica adicionada
              </p>
            )}
          </div>
        </section>

        {/* Images */}
        <section className="bg-card rounded-xl border border-border/50 p-6">
          <h2 className="text-lg font-semibold text-foreground mb-4">
            Fotos do Imóvel
          </h2>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {mockImages.map((image, idx) => (
              <div key={idx} className="relative aspect-[4/3] rounded-lg overflow-hidden group">
                <img
                  src={image}
                  alt={`Foto ${idx + 1}`}
                  className="w-full h-full object-cover"
                />
                <button
                  type="button"
                  className="absolute top-2 right-2 size-6 rounded-full bg-card/90 text-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <X className="size-4" />
                </button>
              </div>
            ))}
            <button
              type="button"
              className="aspect-[4/3] rounded-lg border-2 border-dashed border-border hover:border-primary hover:bg-primary/5 transition-colors flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-primary"
            >
              <ImagePlus className="size-6" />
              <span className="text-xs font-medium">Adicionar foto</span>
            </button>
          </div>
          <p className="text-xs text-muted-foreground mt-3">
            Adicione até 20 fotos. A primeira foto será a capa do anúncio.
          </p>
        </section>

        {/* Form Actions */}
        <div className="flex items-center justify-between pt-4">
          <Button
            type="button"
            variant="ghost"
            onClick={() => router.back()}
          >
            <ArrowLeft className="size-4 mr-2" />
            Voltar
          </Button>
          <Button
            type="submit"
            disabled={isSubmitting}
            className="bg-primary text-primary-foreground hover:bg-primary/90"
          >
            {isSubmitting ? (
              'Salvando...'
            ) : (
              <>
                <Save className="size-4 mr-2" />
                {mode === 'create' ? 'Cadastrar Imóvel' : 'Salvar Alterações'}
              </>
            )}
          </Button>
        </div>
      </div>
    </form>
  )
}
