'use client'
import Link from 'next/link'
import { motion } from 'framer-motion'
import {
  ArrowLeft, Edit2, Building2, User, Shield, FileText,
  CheckCircle2, Clock, AlertCircle, Send, History, Printer, StickyNote,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { cn, formatDate, formatCurrency } from '@/lib/utils'
import { STATUS_COLORS, GUARANTEE_LABELS, type OperationStatus } from '@/types'
import { ChecklistSection } from '../checklist/ChecklistSection'
import { ActivityLog } from '../activity/ActivityLog'
import { DocumentsSection } from '../documents/DocumentsSection'
import { NotesSection } from './NotesSection'
import { WhatsAppLink } from '../ui/WhatsAppLink'
import { OperationTypeBadge } from '../ui/OperationTypeBadge'
import { StatusChanger } from './StatusChanger'
import { ParticipantsPanel } from './ParticipantsPanel'
import { useOperationsStore } from '@/store/operationsStore'

// Fallback data for fields not yet in the store (owner_dni, tenant_dni, etc.)
const EXTRA_DATA: Record<string, {
  owner_dni?: string; tenant_dni?: string;
  guarantee_company?: string; guarantee_observations?: string;
  sent_to_owner_date?: string; sent_to_tenant_date?: string;
}> = {
  '1': {
    owner_dni: '12.345.678', tenant_dni: '30.123.456',
    guarantee_company: 'Garantizar S.A.', guarantee_observations: 'Póliza N° 12345-6',
    sent_to_owner_date: '2026-05-15',
  },
}

const PROGRESS_MAP: 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,
}

function InfoRow({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div>
      <p className="text-xs text-muted-foreground">{label}</p>
      <div className="text-sm font-medium text-foreground mt-0.5">{value || '—'}</div>
    </div>
  )
}

export function OperationDetail({ id }: { id: string }) {
  const op = useOperationsStore(s => s.getById(id))
  const updateStatus = useOperationsStore(s => s.updateStatus)

  const MOCK_OP = op ?? {
    id, internal_code: '—', status: 'consulta_recibida' as OperationStatus,
    operation_type: 'nuevo' as const, property_address: '—', property_locality: '—',
    property_type: '—', owner_name: '—', owner_email: '', owner_phone: '',
    tenant_name: '—', tenant_email: '', tenant_phone: '',
    guarantee_type: 'propietaria' as const, initial_value: 0,
    adjustment_type: 'ICL' as const, adjustment_frequency: 'trimestral' as const,
    entry_date: '', start_date: '', end_date: '',
    sent_to_owner: false, sent_to_tenant: false,
    created_at: '', updated_at: '',
  }

  const extra = EXTRA_DATA[id] ?? {}
  const progress = PROGRESS_MAP[MOCK_OP.status]
  const guaranteeLabel = GUARANTEE_LABELS[MOCK_OP.guarantee_type as keyof typeof GUARANTEE_LABELS] ?? MOCK_OP.guarantee_type

  const handleStatusChange = (status: OperationStatus) => {
    updateStatus(id, status)
  }

  return (
    <div className="max-w-6xl mx-auto space-y-5">
      {/* Header */}
      <div className="flex flex-wrap items-start gap-3">
        <Link href="/operaciones">
          <Button variant="ghost" size="icon"><ArrowLeft size={18} /></Button>
        </Link>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <h2 className="text-lg font-semibold">{MOCK_OP.property_address}</h2>
            <OperationTypeBadge type={MOCK_OP.operation_type} />
            <span className="font-mono text-xs text-muted-foreground">{MOCK_OP.internal_code}</span>
          </div>
          <p className="text-sm text-muted-foreground mt-0.5">
            {MOCK_OP.property_locality} · Prop: {MOCK_OP.owner_name} · Inq: {MOCK_OP.tenant_name}
          </p>
        </div>
        <Link href={`/operaciones/${id}/imprimir`} target="_blank">
          <Button variant="outline" size="sm" className="gap-2">
            <Printer size={14} />Exportar
          </Button>
        </Link>
        <Link href={`/operaciones/${id}/editar`}>
          <Button variant="outline" size="sm" className="gap-2">
            <Edit2 size={14} />Editar
          </Button>
        </Link>
      </div>

      {/* Status Changer — barra de cambio de estado */}
      <div className="bg-card border border-border rounded-xl px-5 py-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-xs text-muted-foreground mb-1">Etapa actual</p>
          <StatusChanger currentStatus={MOCK_OP.status} onStatusChange={handleStatusChange} />
        </div>
        <div className="text-right">
          <p className="text-xs text-muted-foreground">Última actualización</p>
          <p className="text-sm font-medium">{formatDate(MOCK_OP.updated_at)}</p>
        </div>
      </div>

      {/* Progress Banner */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="bg-card border border-border rounded-xl p-5"
      >
        <div className="flex items-center justify-between mb-3">
          <div>
            <p className="text-sm font-semibold text-foreground">Progreso Total</p>
            <p className="text-xs text-muted-foreground">Basado en checklist completado</p>
          </div>
          <span className="text-2xl font-bold text-primary">{progress}%</span>
        </div>
        <Progress value={progress} className="h-3 mb-4" />
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {[
            { label: 'Documentación', value: 72, color: 'text-blue-500' },
            { label: 'Comercial', value: 85, color: 'text-purple-500' },
            { label: 'Contrato', value: 60, color: 'text-indigo-500' },
            { label: 'Firma', value: 20, color: 'text-green-500' },
          ].map(item => (
            <div key={item.label} className="bg-muted/40 rounded-lg p-3">
              <p className="text-xs text-muted-foreground mb-1">{item.label}</p>
              <div className="flex items-center gap-2">
                <Progress value={item.value} className="h-1.5 flex-1" />
                <span className={cn('text-xs font-semibold', item.color)}>{item.value}%</span>
              </div>
            </div>
          ))}
        </div>
      </motion.div>

      {/* Tabs */}
      <Tabs defaultValue="datos">
        <TabsList className="w-full justify-start border-b rounded-none bg-transparent h-auto p-0 gap-1">
          {[
            { value: 'datos', label: 'Datos', icon: Building2 },
            { value: 'checklist', label: 'Checklist', icon: CheckCircle2 },
            { value: 'documentos', label: 'Documentos', icon: FileText },
            { value: 'notas', label: 'Notas', icon: StickyNote },
            { value: 'actividad', label: 'Actividad', icon: History },
          ].map(({ value, label, icon: Icon }) => (
            <TabsTrigger
              key={value}
              value={value}
              className="flex items-center gap-2 rounded-t-lg rounded-b-none data-[state=active]:border-b-2 data-[state=active]:border-primary data-[state=active]:shadow-none pb-3"
            >
              <Icon size={14} />
              {label}
            </TabsTrigger>
          ))}
        </TabsList>

        <TabsContent value="datos" className="mt-4 space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">

            {/* Propiedad */}
            <div className="bg-card border border-border rounded-xl p-5">
              <h4 className="text-sm font-semibold text-primary flex items-center gap-2 mb-4">
                <Building2 size={15} /> Propiedad
              </h4>
              <div className="grid grid-cols-2 gap-3">
                <InfoRow label="Dirección" value={MOCK_OP.property_address} />
                <InfoRow label="Localidad" value={MOCK_OP.property_locality} />
                <InfoRow label="Tipo" value={MOCK_OP.property_type} />
              </div>
            </div>

            {/* Datos Contractuales */}
            <div className="bg-card border border-border rounded-xl p-5">
              <h4 className="text-sm font-semibold text-primary flex items-center gap-2 mb-4">
                <FileText size={15} /> Datos Contractuales
              </h4>
              <div className="grid grid-cols-2 gap-3">
                <InfoRow label="Fecha Ingreso" value={formatDate(MOCK_OP.entry_date)} />
                <InfoRow label="Fecha Inicio" value={formatDate(MOCK_OP.start_date)} />
                <InfoRow label="Fecha Fin" value={formatDate(MOCK_OP.end_date)} />
                <InfoRow label="Valor Inicial" value={formatCurrency(MOCK_OP.initial_value)} />
                <InfoRow label="Ajuste" value={MOCK_OP.adjustment_type} />
                <InfoRow label="Frecuencia" value={MOCK_OP.adjustment_frequency} />
              </div>
            </div>

            {/* Propietario */}
            <div className="bg-card border border-border rounded-xl p-5">
              <h4 className="text-sm font-semibold text-primary flex items-center gap-2 mb-4">
                <User size={15} /> Propietario
              </h4>
              <div className="grid grid-cols-2 gap-3">
                <InfoRow label="Nombre" value={MOCK_OP.owner_name} />
                <InfoRow label="DNI" value={extra.owner_dni} />
                <InfoRow label="Teléfono" value={<WhatsAppLink phone={MOCK_OP.owner_phone} name={MOCK_OP.owner_name} />} />
                <InfoRow label="Email" value={MOCK_OP.owner_email} />
              </div>
            </div>

            {/* Inquilino */}
            <div className="bg-card border border-border rounded-xl p-5">
              <h4 className="text-sm font-semibold text-primary flex items-center gap-2 mb-4">
                <User size={15} /> Inquilino
              </h4>
              <div className="grid grid-cols-2 gap-3">
                <InfoRow label="Nombre" value={MOCK_OP.tenant_name} />
                <InfoRow label="DNI" value={extra.tenant_dni} />
                <InfoRow label="Teléfono" value={<WhatsAppLink phone={MOCK_OP.tenant_phone} name={MOCK_OP.tenant_name} />} />
                <InfoRow label="Email" value={MOCK_OP.tenant_email} />
              </div>
            </div>

            {/* Garantía */}
            <div className="bg-card border border-border rounded-xl p-5">
              <h4 className="text-sm font-semibold text-primary flex items-center gap-2 mb-4">
                <Shield size={15} /> Garantía
              </h4>
              <div className="grid grid-cols-2 gap-3">
                <InfoRow label="Tipo" value={guaranteeLabel} />
                {extra.guarantee_company && (
                  <InfoRow label="Empresa Aseguradora" value={extra.guarantee_company} />
                )}
                <InfoRow label="Observaciones" value={extra.guarantee_observations} />
              </div>
            </div>

            {/* Participantes */}
            <ParticipantsPanel
              initialParticipants={[
                { id: 'martin', name: 'Martín', role: 'Gestor' },
                { id: 'horacio', name: 'Horacio Acosta', role: 'Titular' },
              ]}
            />

            {/* Envío de Contrato */}
            <div className="bg-card border border-border rounded-xl p-5 md:col-span-2">
              <h4 className="text-sm font-semibold text-primary flex items-center gap-2 mb-3">
                <Send size={15} /> Envío de Contrato
              </h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex items-center justify-between p-3 rounded-lg bg-muted/30">
                  <span className="text-sm text-foreground">Al Propietario</span>
                  {MOCK_OP.sent_to_owner ? (
                    <div className="flex items-center gap-2">
                      <CheckCircle2 size={14} className="text-green-500" />
                      <span className="text-xs text-green-600 font-medium">{formatDate(extra.sent_to_owner_date)}</span>
                    </div>
                  ) : (
                    <div className="flex items-center gap-1 text-yellow-500">
                      <Clock size={14} />
                      <span className="text-xs font-medium">Pendiente</span>
                    </div>
                  )}
                </div>
                <div className="flex items-center justify-between p-3 rounded-lg bg-muted/30">
                  <span className="text-sm text-foreground">Al Inquilino</span>
                  {MOCK_OP.sent_to_tenant ? (
                    <div className="flex items-center gap-2">
                      <CheckCircle2 size={14} className="text-green-500" />
                      <span className="text-xs text-green-600 font-medium">{formatDate(extra.sent_to_tenant_date)}</span>
                    </div>
                  ) : (
                    <div className="flex items-center gap-1 text-yellow-500">
                      <AlertCircle size={14} />
                      <span className="text-xs font-medium">Pendiente</span>
                    </div>
                  )}
                </div>
              </div>
            </div>

          </div>
        </TabsContent>

        <TabsContent value="checklist" className="mt-4">
          <ChecklistSection operationId={id} />
        </TabsContent>

        <TabsContent value="documentos" className="mt-4">
          <DocumentsSection operationId={id} />
        </TabsContent>

        <TabsContent value="notas" className="mt-4">
          <NotesSection operationId={id} />
        </TabsContent>

        <TabsContent value="actividad" className="mt-4">
          <ActivityLog operationId={id} />
        </TabsContent>
      </Tabs>
    </div>
  )
}
