import { useState, useEffect } from 'react'
import { Info } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Slider } from '@/components/ui/slider'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useProcessStore } from '@/store/process-store'
import { formatPercent } from '@/lib/format'

const CURRENCIES = [
  { code: 'USD', label: 'USD — Dólar estadounidense' },
  { code: 'PYG', label: 'PYG — Guaraní paraguayo' },
  { code: 'BRL', label: 'BRL — Real brasileño' },
  { code: 'ARS', label: 'ARS — Peso argentino' },
  { code: 'EUR', label: 'EUR — Euro' },
  { code: 'COP', label: 'COP — Peso colombiano' },
  { code: 'MXN', label: 'MXN — Peso mexicano' },
  { code: 'CLP', label: 'CLP — Peso chileno' },
]

export function GlobalSettingsPanel() {
  const { currentProcess, updateProcess } = useProcessStore()
  const [localName, setLocalName] = useState('')
  const [localClient, setLocalClient] = useState('')
  const [localCurrency, setLocalCurrency] = useState('USD')
  const [localOverhead, setLocalOverhead] = useState(20)
  const [localFrequency, setLocalFrequency] = useState(1000)
  const [localHorizon, setLocalHorizon] = useState(3)
  const [localInvestment, setLocalInvestment] = useState(0)
  const [isDirty, setIsDirty] = useState(false)

  useEffect(() => {
    if (!currentProcess) return
    setLocalName(currentProcess.name)
    setLocalClient(currentProcess.clientName)
    setLocalCurrency(currentProcess.currency)
    setLocalOverhead(Math.round(currentProcess.overheadPercentage * 100))
    setLocalFrequency(currentProcess.annualFrequency)
    setLocalHorizon(currentProcess.analysisHorizonYears)
    setLocalInvestment(currentProcess.automationInvestment)
    setIsDirty(false)
  }, [currentProcess])

  function markDirty() { setIsDirty(true) }

  async function handleSave() {
    const clampedHorizon = Math.min(10, Math.max(1, localHorizon))
    await updateProcess({
      name: localName.trim() || 'Proceso sin nombre',
      clientName: localClient.trim(),
      currency: localCurrency,
      overheadPercentage: localOverhead / 100,
      annualFrequency: Math.max(1, localFrequency),
      analysisHorizonYears: clampedHorizon,
      automationInvestment: Math.max(0, localInvestment),
    })
    setLocalHorizon(clampedHorizon)
    setIsDirty(false)
  }

  if (!currentProcess) return null

  return (
    <ScrollArea className="h-full">
      <div className="p-4 space-y-5">
        {/* Nombre del proceso */}
        <div className="space-y-1.5">
          <Label htmlFor="proc-name" className="text-xs font-medium">Nombre del proceso</Label>
          <Input
            id="proc-name"
            value={localName}
            onChange={(e) => { setLocalName(e.target.value); markDirty() }}
            placeholder="ej. Proceso de ventas"
            className="h-8 text-sm"
          />
        </div>

        {/* Cliente */}
        <div className="space-y-1.5">
          <Label htmlFor="client-name" className="text-xs font-medium">Cliente</Label>
          <Input
            id="client-name"
            value={localClient}
            onChange={(e) => { setLocalClient(e.target.value); markDirty() }}
            placeholder="ej. Empresa ABC"
            className="h-8 text-sm"
          />
        </div>

        {/* Moneda */}
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">Moneda</Label>
          <Select value={localCurrency} onValueChange={(v) => { setLocalCurrency(v); markDirty() }}>
            <SelectTrigger className="h-8 text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {CURRENCIES.map((c) => (
                <SelectItem key={c.code} value={c.code} className="text-xs">{c.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Overhead */}
        <div className="space-y-2">
          <div className="flex items-center gap-1.5">
            <Label className="text-xs font-medium">Overhead (costos indirectos)</Label>
            <Tooltip>
              <TooltipTrigger asChild>
                <Info className="h-3 w-3 text-slate-400 cursor-help" />
              </TooltipTrigger>
              <TooltipContent side="right" className="max-w-52 text-xs">
                Porcentaje adicional sobre los costos directos que representa los costos indirectos: alquiler, administración, infraestructura general.
              </TooltipContent>
            </Tooltip>
          </div>
          <div className="flex items-center gap-3">
            <Slider
              value={[localOverhead]}
              min={0}
              max={100}
              step={1}
              onValueChange={([v]) => { setLocalOverhead(v); markDirty() }}
              className="flex-1"
            />
            <span className="text-sm font-mono font-semibold text-slate-700 w-12 text-right">
              {formatPercent(localOverhead, 0)}
            </span>
          </div>
          <p className="text-xs text-slate-400">
            Típicamente entre 15% y 40% para empresas de servicios
          </p>
        </div>

        {/* ── Sección: Análisis de Impacto ──────────────────────────────── */}
        <div>
          <Separator className="mb-4" />
          <div className="space-y-4">
            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Análisis de Impacto</p>

            {/* Frecuencia anual */}
            <div className="space-y-1.5">
              <div className="flex items-center gap-1.5">
                <Label htmlFor="annual-frequency" className="text-xs font-medium">
                  Frecuencia anual
                </Label>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Info className="h-3 w-3 text-slate-400 cursor-help" />
                  </TooltipTrigger>
                  <TooltipContent side="right" className="max-w-52 text-xs">
                    Cantidad de veces que se ejecuta el proceso completo por año. Se usa para anualizar los costos y calcular el ahorro.
                  </TooltipContent>
                </Tooltip>
              </div>
              <Input
                id="annual-frequency"
                type="number"
                min={1}
                max={10_000_000}
                step={1}
                value={localFrequency === 0 ? '' : localFrequency}
                onChange={(e) => { setLocalFrequency(Math.max(1, parseInt(e.target.value) || 1)); markDirty() }}
                className="font-mono h-8 text-sm"
                placeholder="1000"
              />
              <p className="text-[10px] text-slate-400">
                Ejemplos: 12 (mensual) · 52 (semanal) · 250 (diario laboral) · 8760 (cada hora)
              </p>
            </div>

            {/* Horizonte de análisis */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-1.5">
                  <Label className="text-xs font-medium">Horizonte de análisis</Label>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Info className="h-3 w-3 text-slate-400 cursor-help" />
                    </TooltipTrigger>
                    <TooltipContent side="right" className="max-w-52 text-xs">
                      Años hasta los que se proyecta el ahorro acumulado. Determina el eje X del gráfico de ROI.
                    </TooltipContent>
                  </Tooltip>
                </div>
                <span className="text-sm font-mono font-semibold text-slate-700">
                  {localHorizon} {localHorizon === 1 ? 'año' : 'años'}
                </span>
              </div>
              <Slider
                value={[localHorizon]}
                min={1}
                max={10}
                step={1}
                onValueChange={([v]) => { setLocalHorizon(v); markDirty() }}
              />
            </div>

            {/* Inversión en automatización */}
            <div className="space-y-1.5">
              <div className="flex items-center gap-1.5">
                <Label htmlFor="automation-investment" className="text-xs font-medium">
                  Inversión en automatización
                </Label>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Info className="h-3 w-3 text-slate-400 cursor-help" />
                  </TooltipTrigger>
                  <TooltipContent side="right" className="max-w-56 text-xs">
                    Costo único total del proyecto: desarrollo, licencias, implementación, capacitación. No incluir costos recurrentes.
                  </TooltipContent>
                </Tooltip>
              </div>
              <Input
                id="automation-investment"
                type="number"
                min={0}
                step={100}
                value={localInvestment === 0 ? '' : localInvestment}
                onChange={(e) => { setLocalInvestment(Math.max(0, parseFloat(e.target.value) || 0)); markDirty() }}
                className="font-mono h-8 text-sm"
                placeholder="0"
              />
            </div>
          </div>
        </div>

        {/* Guardar */}
        <Button
          size="sm"
          onClick={handleSave}
          disabled={!isDirty}
          className="w-full"
        >
          {isDirty ? 'Guardar configuración' : 'Sin cambios'}
        </Button>
      </div>
    </ScrollArea>
  )
}
