import { Template, TemplateAttributeDetail } from '@/type/template'
import clsx from 'clsx'
import { Check, Copy, MoreVertical, Pencil, Trash2 } from 'lucide-react'
import React from 'react'
import { useNavigate } from 'react-router-dom'
import { Button } from 'shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from 'shared/ui/card'
import { Popover, PopoverContent, PopoverTrigger } from 'shared/ui/popover'

interface TemplateCardProps {
  template: Template & { attributes?: TemplateAttributeDetail[] }
  selectionMode?: boolean
  isSelected: boolean
  onToggleSelect?: (id: string) => void
  onDelete?: (id: string) => void
  onCopy?: (id: string) => void
  onEdit?: (id: string) => void
  activeFilters?: { [attributeId: string]: string } // Добавляем пропс для активных фильтров
}

const TemplateCard: React.FC<TemplateCardProps> = ({
  template,
  selectionMode = false,
  isSelected,
  onToggleSelect,
  onDelete,
  onCopy,
  onEdit,
  activeFilters = {},
}) => {
  const navigate = useNavigate()

  const isConfigured = true // TODO: remove

  const handleEdit = (e: React.MouseEvent) => {
    e.stopPropagation()
    onEdit?.(template.id)
  }

  const handleCopy = (e: React.MouseEvent) => {
    e.stopPropagation()
    onCopy?.(template.id)
  }

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation()
    onDelete?.(template.id)
  }

  return (
    // console.log(template.excelFile),
    <Card
      aria-label={`Шаблон ${template.name}`}
      onClick={
        selectionMode && onToggleSelect
          ? () => onToggleSelect(template.id)
          : !selectionMode && isConfigured
            ? () => navigate(`/templates/${template.id}/protocols`)
            : undefined
      }
      className={clsx(
        'group relative flex min-h-[160px] flex-col transition-all duration-300 ease-out',
        (selectionMode || (!selectionMode && isConfigured)) && 'cursor-pointer',
        selectionMode &&
          isSelected &&
          'border-primary ring-2 ring-primary ring-offset-2',
        !selectionMode &&
          isConfigured &&
          'hover:border-primary/40 hover:shadow-md',
        !selectionMode && !isConfigured && 'cursor-not-allowed opacity-60'
      )}
    >
      {selectionMode && (
        <button
          type="button"
          onClick={e => {
            e.stopPropagation()
            onToggleSelect?.(template.id)
          }}
          className={clsx(
            'absolute right-2 top-2 h-5 w-5 rounded border border-primary',
            isSelected
              ? 'bg-primary text-primary-foreground'
              : 'border-input bg-background hover:bg-accent hover:text-accent-foreground'
          )}
        >
          {isSelected && <Check className="h-3 w-3" />}
        </button>
      )}
      {!selectionMode && (
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="ghost"
              size="sm"
              className="absolute right-1 top-1 h-7 w-7 p-0 opacity-0 transition-all duration-200 ease-out group-hover:opacity-100 hover:scale-110 hover:bg-accent/80"
              onClick={e => e.stopPropagation()}
            >
              <MoreVertical className="h-3 w-3" />
            </Button>
          </PopoverTrigger>
          <PopoverContent align="end" className="w-48 p-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleEdit}
              className="w-full justify-start"
            >
              <Pencil className="mr-2 h-4 w-4" />
              Редактировать
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleCopy}
              className="w-full justify-start"
            >
              <Copy className="mr-2 h-4 w-4" />
              Копировать
            </Button>
            <div className="mx-1 my-1 h-px bg-border" />
            <Button
              variant="ghost"
              size="sm"
              onClick={handleDelete}
              className="w-full justify-start text-destructive hover:bg-destructive hover:text-destructive-foreground"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Удалить
            </Button>
          </PopoverContent>
        </Popover>
      )}

      <CardHeader className="flex-shrink-0 pb-3">
        <CardTitle className="line-clamp-3 text-base font-semibold leading-snug">
          {template.name}
        </CardTitle>
      </CardHeader>
      <CardContent className="flex flex-1 flex-col pb-4 pt-0">
        <div className="flex-1"></div>

        <div className="space-y-2">
          {/* Показываем госреестр (если не в фильтрах) */}
          {template.attributes &&
            template.attributes
              .filter(
                attr =>
                  attr.value &&
                  attr.value.trim() &&
                  (attr.attribute_name.toLowerCase().includes('госреестр') ||
                    attr.attribute_name.toLowerCase().includes('реестр')) &&
                  !activeFilters[attr.attribute_id]
              )
              .slice(0, 1)
              .map(attr => (
                <div
                  key={attr.attribute_id}
                  className="rounded-md border bg-muted/30 px-3 py-2"
                >
                  <div className="flex items-center justify-between gap-2">
                    <span className="flex-shrink-0 text-xs font-bold text-muted-foreground/70">
                      ГРСИ
                    </span>
                    <div className="break-all text-right text-sm font-medium leading-tight text-foreground">
                      {attr.value}
                    </div>
                  </div>
                </div>
              ))}

          {/* Показываем все отфильтрованные атрибуты */}
          {template.attributes &&
            template.attributes
              .filter(
                attr =>
                  attr.value &&
                  attr.value.trim() &&
                  activeFilters[attr.attribute_id]
              )
              .map(attr => {
                const isRegistry =
                  attr.attribute_name.toLowerCase().includes('госреестр') ||
                  attr.attribute_name.toLowerCase().includes('реестр')

                if (isRegistry) {
                  // Госреестр в фильтрах показываем в специальном стиле
                  return (
                    <div
                      key={attr.attribute_id}
                      className="rounded-md border border-primary/50 bg-primary/10 px-3 py-2"
                    >
                      <div className="flex items-center justify-between gap-2">
                        <span className="flex-shrink-0 text-xs font-bold text-primary">
                          ГРСИ
                        </span>
                        <div className="break-all text-right text-sm font-medium leading-tight text-foreground">
                          {attr.value}
                        </div>
                      </div>
                    </div>
                  )
                } else {
                  // Обычные атрибуты
                  const displayName =
                    attr.attribute_name.toLowerCase().includes('тип') &&
                    attr.attribute_name.toLowerCase().includes('прибор')
                      ? 'ТИП'
                      : attr.attribute_name

                  return (
                    <div
                      key={attr.attribute_id}
                      className="rounded-md border border-primary/50 bg-primary/10 px-3 py-2"
                    >
                      <div className="flex items-center justify-between gap-2">
                        <span className="flex-shrink-0 text-xs font-bold text-primary">
                          {displayName}
                        </span>
                        <div className="break-all text-right text-sm font-medium leading-tight text-foreground">
                          {attr.value}
                        </div>
                      </div>
                    </div>
                  )
                }
              })}
        </div>

        {/* Статус шаблона */}
        {!isConfigured && (
          <div className="mt-auto">
            <div className="rounded-md bg-orange-50 px-3 py-2 text-center">
              <div className="text-xs font-medium text-orange-600">
                Требует настройки
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

export default TemplateCard
