'use client'
import { useState } from 'react'
import Link from 'next/link'
import { motion } from 'framer-motion'
import { Search, Plus, Filter, SlidersHorizontal, Eye, Edit2, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { cn, formatDate, formatCurrency } from '@/lib/utils'
import { STATUS_LABELS, STATUS_COLORS, type Operation, type OperationStatus } from '@/types'
import { OperationTypeBadge } from '../ui/OperationTypeBadge'
import { WhatsAppLink } from '../ui/WhatsAppLink'
import { useOperationsStore } from '@/store/operationsStore'

const PROGRESS_BY_STATUS: Record<OperationStatus, number> = {
  consulta_recibida: 5,
  reserva_realizada: 15,
  documentacion_pendiente: 25,
  documentacion_completa: 45,
  contrato_en_confeccion: 60,
  enviado_propietario: 70,
  enviado_inquilino: 80,
  correcciones: 75,
  listo_para_firma: 90,
  firmado: 100,
  archivado: 100,
}

const TEAM_MEMBERS = [
  { id: 'horacio', name: 'Horacio Acosta' },
  { id: 'martin', name: 'Martín' },
  { id: 'admin', name: 'Administración' },
  { id: 'sofia', name: 'Sofía' },
  { id: 'lucas', name: 'Lucas' },
]

export function OperationsList() {
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [responsableFilter, setResponsableFilter] = useState<string>('all')
  const operations = useOperationsStore(s => s.operations)

  const filtered = operations.filter(op => {
    const matchSearch = !search || [op.property_address, op.owner_name, op.tenant_name, op.internal_code]
      .some(v => v?.toLowerCase().includes(search.toLowerCase()))
    const matchStatus = statusFilter === 'all' || op.status === statusFilter
    const matchResponsable = responsableFilter === 'all' || op.assigned_to === responsableFilter
    return matchSearch && matchStatus && matchResponsable
  })

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">Operaciones</h2>
          <p className="text-sm text-muted-foreground">{filtered.length} operaciones encontradas</p>
        </div>
        <Link href="/operaciones/nueva">
          <Button className="gap-2">
            <Plus size={16} />
            Nueva Operación
          </Button>
        </Link>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Buscar por dirección, propietario, inquilino..."
            className="pl-9"
            value={search}
            onChange={e => setSearch(e.target.value)}
            onKeyDown={e => e.key === 'Escape' && setSearch('')}
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full sm:w-52">
            <Filter size={14} className="mr-2" />
            <SelectValue placeholder="Estado" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Todos los estados</SelectItem>
            {Object.entries(STATUS_LABELS).map(([k, v]) => (
              <SelectItem key={k} value={k}>{v}</SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={responsableFilter} onValueChange={setResponsableFilter}>
          <SelectTrigger className="w-full sm:w-44">
            <SlidersHorizontal size={14} className="mr-2" />
            <SelectValue placeholder="Responsable" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Todos</SelectItem>
            {TEAM_MEMBERS.map(m => (
              <SelectItem key={m.id} value={m.id}>{m.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Table */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="px-3 py-3" />
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Código</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Tipo</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Propiedad</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Propietario</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Inquilino</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Estado</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Valor</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Progreso</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Responsable</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Inicio</th>
              </tr>
            </thead>
            <tbody>
              {(() => {
                const active   = filtered.filter(op => op.status !== 'archivado')
                const archived = filtered.filter(op => op.status === 'archivado')
                const rows = []

                active.forEach((op, i) => rows.push(
                  <motion.tr
                    key={op.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: i * 0.03 }}
                    className="border-b border-border last:border-0 hover:bg-accent/50 transition-colors"
                  >
                    {renderCells(op)}
                  </motion.tr>
                ))

                if (archived.length > 0) {
                  rows.push(
                    <tr key="archived-divider">
                      <td colSpan={11} className="px-4 py-2">
                        <div className="flex items-center gap-3">
                          <div className="flex-1 h-px bg-border" />
                          <span className="text-xs text-muted-foreground/60 font-medium whitespace-nowrap">
                            {archived.length} archivado{archived.length !== 1 ? 's' : ''}
                          </span>
                          <div className="flex-1 h-px bg-border" />
                        </div>
                      </td>
                    </tr>
                  )
                  archived.forEach((op, i) => rows.push(
                    <motion.tr
                      key={op.id}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ delay: i * 0.03 }}
                      className="border-b border-border last:border-0 hover:bg-accent/50 transition-colors opacity-50"
                    >
                      {renderCells(op)}
                    </motion.tr>
                  ))
                }

                return rows
              })()}
            </tbody>
          </table>
        </div>
        {filtered.length === 0 && (
          <div className="py-16 text-center text-muted-foreground">
            <FileText className="mx-auto mb-3 opacity-30" size={40} />
            <p>No se encontraron operaciones</p>
          </div>
        )}
      </div>
    </div>
  )
}

function renderCells(op: Operation) {
  return (
    <>
      <td className="px-3 py-3">
        <div className="flex items-center gap-1.5">
          <Link href={`/operaciones/${op.id}`}>
            <Button size="sm" variant="default" className="h-7 gap-1.5 px-2.5 text-xs">
              <Eye size={13} /> Ver
            </Button>
          </Link>
          <Link href={`/operaciones/${op.id}/editar`}>
            <Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-foreground">
              <Edit2 size={13} />
            </Button>
          </Link>
        </div>
      </td>
      <td className="px-4 py-3">
        <span className="font-mono text-xs text-muted-foreground">{op.internal_code}</span>
      </td>
      <td className="px-4 py-3">
        <OperationTypeBadge type={op.operation_type} />
      </td>
      <td className="px-4 py-3">
        <p className="font-medium text-foreground truncate max-w-[180px]">{op.property_address}</p>
        <p className="text-xs text-muted-foreground">{op.property_locality}</p>
      </td>
      <td className="px-4 py-3">
        <span className="text-foreground">{op.owner_name}</span>
      </td>
      <td className="px-4 py-3">
        <span className="text-foreground">{op.tenant_name}</span>
      </td>
      <td className="px-4 py-3">
        <Badge className={cn('text-xs', STATUS_COLORS[op.status])}>
          {STATUS_LABELS[op.status]}
        </Badge>
      </td>
      <td className="px-4 py-3 text-foreground">
        {formatCurrency(op.initial_value)}
      </td>
      <td className="px-4 py-3 w-28">
        <div className="flex items-center gap-2">
          <Progress value={PROGRESS_BY_STATUS[op.status]} className="h-1.5 flex-1" />
          <span className="text-xs text-muted-foreground w-8">{PROGRESS_BY_STATUS[op.status]}%</span>
        </div>
      </td>
      <td className="px-4 py-3">
        {op.assigned_to ? (
          <span className="text-xs font-medium text-foreground">
            {TEAM_MEMBERS.find(m => m.id === op.assigned_to)?.name ?? op.assigned_to}
          </span>
        ) : (
          <span className="text-xs text-muted-foreground">—</span>
        )}
      </td>
      <td className="px-4 py-3 text-muted-foreground text-xs">
        {formatDate(op.start_date)}
      </td>
    </>
  )
}

function FileText({ className, size }: { className?: string; size?: number }) {
  return (
    <svg className={className} width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
      <polyline points="10 9 9 9 8 9" />
    </svg>
  )
}
