'use client'

import { MetricsBlock as MetricsBlockType, MetricItem } from '../types'
import { Button } from '../../ui/button'
import { Input } from '../../ui/input'
import { Label } from '../../ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../ui/select'
import { Plus, Trash2, TrendingUp, TrendingDown, Minus } from 'lucide-react'
import { cn } from '../../../lib/utils'

interface MetricsBlockProps {
  block: MetricsBlockType
  onChange: (block: MetricsBlockType) => void
  isEditing?: boolean
}

export function MetricsBlockEditor({ block, onChange, isEditing = true }: MetricsBlockProps) {
  const updateMetric = (metricId: string, updates: Partial<MetricItem>) => {
    onChange({
      ...block,
      metrics: block.metrics.map((m) =>
        m.id === metricId ? { ...m, ...updates } : m
      ),
    })
  }

  const addMetric = () => {
    const newMetric: MetricItem = {
      id: `metric-${Date.now()}`,
      label: 'New Metric',
      value: '0',
      change: '+0%',
      changeType: 'neutral',
    }
    onChange({ ...block, metrics: [...block.metrics, newMetric] })
  }

  const removeMetric = (metricId: string) => {
    onChange({ ...block, metrics: block.metrics.filter((m) => m.id !== metricId) })
  }

  const getChangeColor = (type?: 'positive' | 'negative' | 'neutral') => {
    switch (type) {
      case 'positive':
        return 'text-green-600'
      case 'negative':
        return 'text-red-600'
      default:
        return 'text-gray-500'
    }
  }

  const getChangeIcon = (type?: 'positive' | 'negative' | 'neutral') => {
    switch (type) {
      case 'positive':
        return <TrendingUp className="h-3 w-3 text-green-600" />
      case 'negative':
        return <TrendingDown className="h-3 w-3 text-red-600" />
      default:
        return <Minus className="h-3 w-3 text-gray-400" />
    }
  }

  if (!isEditing) {
    return (
      <div className="py-4">
        {block.title && (
          <h3 className="text-lg font-semibold mb-4 text-center">{block.title}</h3>
        )}
        <div
          className={cn(
            'grid gap-4',
            block.columns === 2 && 'grid-cols-2',
            block.columns === 3 && 'grid-cols-3',
            block.columns === 4 && 'grid-cols-4'
          )}
        >
          {block.metrics.map((metric) => (
            <div key={metric.id} className="text-center p-4 bg-gray-50 rounded-lg">
              <div className="text-2xl font-bold">{metric.value}</div>
              <div className="text-sm text-muted-foreground">{metric.label}</div>
              {metric.change && (
                <div
                  className={cn(
                    'flex items-center justify-center gap-1 text-sm mt-1',
                    getChangeColor(metric.changeType)
                  )}
                >
                  {getChangeIcon(metric.changeType)}
                  {metric.change}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4 p-4">
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label className="text-xs">Section Title</Label>
          <Input
            value={block.title || ''}
            onChange={(e) => onChange({ ...block, title: e.target.value })}
            placeholder="Key Metrics"
          />
        </div>
        <div className="space-y-2">
          <Label className="text-xs">Columns</Label>
          <Select
            value={block.columns.toString()}
            onValueChange={(v) =>
              onChange({ ...block, columns: parseInt(v) as 2 | 3 | 4 })
            }
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="2">2 columns</SelectItem>
              <SelectItem value="3">3 columns</SelectItem>
              <SelectItem value="4">4 columns</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <div className="space-y-2">
        {block.metrics.map((metric) => (
          <div
            key={metric.id}
            className="flex items-start gap-2 p-2 border rounded bg-background"
          >
            <div className="flex-1 grid grid-cols-4 gap-2">
              <Input
                value={metric.label}
                onChange={(e) => updateMetric(metric.id, { label: e.target.value })}
                placeholder="Label"
                className="text-xs"
              />
              <Input
                value={metric.value}
                onChange={(e) => updateMetric(metric.id, { value: e.target.value })}
                placeholder="Value"
                className="text-xs"
              />
              <Input
                value={metric.change || ''}
                onChange={(e) => updateMetric(metric.id, { change: e.target.value })}
                placeholder="+15%"
                className="text-xs"
              />
              <Select
                value={metric.changeType || 'neutral'}
                onValueChange={(v) =>
                  updateMetric(metric.id, {
                    changeType: v as 'positive' | 'negative' | 'neutral',
                  })
                }
              >
                <SelectTrigger className="text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="positive">Positive</SelectItem>
                  <SelectItem value="negative">Negative</SelectItem>
                  <SelectItem value="neutral">Neutral</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={() => removeMetric(metric.id)}
              disabled={block.metrics.length <= 1}
            >
              <Trash2 className="h-3 w-3 text-muted-foreground" />
            </Button>
          </div>
        ))}
        <Button variant="outline" size="sm" onClick={addMetric} className="w-full">
          <Plus className="mr-2 h-3 w-3" />
          Add Metric
        </Button>
      </div>
    </div>
  )
}
