'use client';

import { AnimatePresence, motion } from 'framer-motion';
import {
  BarChart3,
  CalendarDays,
  CheckSquare,
  Copy,
  Edit2,
  ExternalLink,
  FolderOpen,
  Link as LinkGlyph,
  QrCode,
  Settings,
  Square,
  Star,
  Trash2,
} from 'lucide-react';
import { FavoriteGradientStar } from './FavoriteGradientStar';
import { LINK_ACCENT_VARIANTS } from './constants';
import type { LinkItem } from './types';
import { buildStatus, formatDate, getLinkDescription } from './utils';

type LinkRowProps = {
  link: LinkItem;
  index: number;
  selected: boolean;
  settingsOpen: boolean;
  onToggleSelect: (linkId: string) => void;
  onToggleFavorite: (link: LinkItem) => void;
  onCopy: (value: string) => void;
  onOpenStats: (linkId: string) => void;
  onOpenQr: (link: LinkItem) => void;
  onToggleSettings: (linkId: string) => void;
  onCloseSettings: () => void;
  onEdit: (link: LinkItem) => void;
  onRequestDelete: (link: LinkItem) => void;
};

export function LinkRow({
  link,
  index,
  selected,
  settingsOpen,
  onToggleSelect,
  onToggleFavorite,
  onCopy,
  onOpenStats,
  onOpenQr,
  onToggleSettings,
  onCloseSettings,
  onEdit,
  onRequestDelete,
}: LinkRowProps) {
  const status = buildStatus(link);
  const accent = LINK_ACCENT_VARIANTS[index % LINK_ACCENT_VARIANTS.length];
  const linkDescription = getLinkDescription(link);

  return (
    <motion.article
      key={link.id}
      layout
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -8 }}
      transition={{ duration: 0.2, delay: index * 0.05 }}
      whileHover={{ y: -2 }}
      className={`group/link relative overflow-visible rounded-2xl border p-5 transition-all duration-300 ${
        settingsOpen ? 'z-50' : 'z-10'
      } ${
        selected
          ? 'border-violet-500/35 bg-violet-500/[0.05]'
          : 'border-white/10 bg-black/40 hover:border-white/20 hover:bg-white/[0.04]'
      }`}
    >
      <div className="pointer-events-none absolute right-0 top-0 h-full w-64 rounded-r-2xl bg-gradient-to-l from-white/[0.02] to-transparent" />

      <div className="relative z-10 flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div className="flex min-w-0 flex-1 items-start gap-4 overflow-hidden">
          <div className="mt-1 flex shrink-0 items-center gap-3 md:mt-0">
            <button
              type="button"
              onClick={(event) => {
                event.stopPropagation();
                onToggleSelect(link.id);
              }}
              className="text-gray-500 transition-colors hover:text-white"
            >
              {selected ? (
                <CheckSquare className="h-5 w-5 text-violet-400" />
              ) : (
                <Square className="h-5 w-5" />
              )}
            </button>

            <div className={`inline-flex h-10 w-10 items-center justify-center rounded-xl border shadow-sm ${accent.icon}`}>
              <LinkGlyph className="h-5 w-5" />
            </div>
          </div>

          <div className="min-w-0 flex-1 overflow-hidden">
            <div className="mb-1 flex flex-wrap items-center gap-2">
              <h3 className="min-w-0 max-w-full break-words text-base font-semibold text-white [overflow-wrap:anywhere] sm:max-w-[28rem] sm:truncate">
                {link.title || link.slug}
              </h3>
              <span className={`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-medium ${status.tone}`}>
                {status.label}
              </span>
              <button
                type="button"
                onClick={(event) => {
                  event.stopPropagation();
                  onToggleFavorite(link);
                }}
                className={`inline-flex h-6 w-6 items-center justify-center transition-all ${
                  link.isFavorite
                    ? 'text-white opacity-100 hover:scale-110'
                    : 'border-transparent text-gray-500 opacity-0 hover:border-white/10 hover:bg-white/5 hover:text-gray-300 group-hover/link:opacity-100'
                }`}
                title={link.isFavorite ? 'Убрать из избранного' : 'В избранное'}
              >
                {link.isFavorite ? (
                  <FavoriteGradientStar className="h-4 w-4" />
                ) : (
                  <Star className="h-4 w-4" />
                )}
              </button>
            </div>

            {linkDescription ? (
              <p className="mb-2 truncate text-xs text-gray-400">{linkDescription}</p>
            ) : null}

            <div className="flex max-w-full flex-wrap items-center gap-2 sm:gap-3">
              <div className="group/slug inline-flex min-w-0 items-center gap-1.5">
                <button
                  type="button"
                  onClick={(event) => {
                    event.stopPropagation();
                    onCopy(link.shortUrl);
                  }}
                  className={`truncate font-mono text-left text-sm transition-colors hover:text-white ${accent.shortUrl}`}
                  title="Скопировать short URL"
                >
                  {link.shortUrl}
                </button>
                <button
                  type="button"
                  onClick={(event) => {
                    event.stopPropagation();
                    onCopy(link.shortUrl);
                  }}
                  className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded border border-white/10 bg-white/5 text-gray-400 opacity-0 transition-all duration-200 hover:bg-white/10 hover:text-white group-hover/slug:opacity-100"
                  title="Копировать short URL"
                >
                  <Copy className="h-3 w-3" />
                </button>
              </div>
              <span className="hidden text-xs text-gray-600 sm:inline">•</span>
              <span className="max-w-[200px] truncate font-mono text-xs text-gray-500 sm:max-w-xs">{link.longUrl}</span>
            </div>

            <div className="mt-3 flex max-w-full flex-wrap items-center gap-3 text-xs text-gray-500">
              <span className="inline-flex items-center gap-1">
                <CalendarDays className="h-3 w-3" />
                {formatDate(link.createdAt)}
              </span>
              <span className="h-1 w-1 rounded-full bg-gray-700" />
              <span className="inline-flex items-center gap-1">
                <FolderOpen className="h-3 w-3" />
                {link.folder?.name || 'Без папки'}
              </span>
              {link.tags.length > 0 ? (
                <>
                  <span className="h-1 w-1 rounded-full bg-gray-700" />
                  <div className="flex min-w-0 flex-wrap items-center gap-1.5">
                    {link.tags.slice(0, 4).map((entry) => (
                      <span
                        key={`${link.id}-${entry.tag.id}`}
                        className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px]"
                        style={{
                          borderColor: `${entry.tag.color}44`,
                          color: entry.tag.color,
                          backgroundColor: `${entry.tag.color}1a`,
                        }}
                      >
                        <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: entry.tag.color }} />
                        {entry.tag.name}
                      </span>
                    ))}
                    {link.tags.length > 4 ? (
                      <span className="inline-flex items-center rounded-full border border-white/10 bg-white/[0.03] px-2 py-0.5 text-[10px] text-gray-400">
                        +{link.tags.length - 4}
                      </span>
                    ) : null}
                  </div>
                </>
              ) : null}
              {link.hasPassword ? (
                <>
                  <span className="h-1 w-1 rounded-full bg-gray-700" />
                  <span>Пароль</span>
                </>
              ) : null}
            </div>
          </div>
        </div>

        <div className="relative flex w-full shrink-0 flex-wrap items-center justify-between gap-2 border-t border-white/5 pt-4 md:w-auto md:flex-nowrap md:gap-0 md:border-none md:pt-0">
          <div className={`flex flex-col transition-opacity duration-200 md:items-end ${
            settingsOpen ? 'md:opacity-0' : 'md:group-hover/link:opacity-0'
          }`}>
            <span className="mb-1 text-[10px] uppercase tracking-wider text-gray-500 sm:text-xs">Клики</span>
            <span className="font-mono font-medium text-white">{link.clicks.toLocaleString('ru-RU')}</span>
          </div>

          <div className={`z-20 flex flex-wrap items-center justify-end gap-2 pb-1 transition-all md:absolute md:right-0 md:top-1/2 md:-translate-y-1/2 md:flex-nowrap md:pb-0 ${
            settingsOpen ? 'md:flex' : 'md:hidden md:group-hover/link:flex'
          }`}>
            <button
              type="button"
              onClick={(event) => {
                event.stopPropagation();
                onOpenStats(link.id);
              }}
              className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs font-medium text-white transition-colors hover:bg-white/10 sm:gap-2 sm:px-3 sm:text-sm"
              title="Статистика"
            >
              <BarChart3 className="h-4 w-4 text-violet-300" />
              <span className="hidden sm:inline">Статистика</span>
            </button>

            <button
              type="button"
              onClick={(event) => {
                event.stopPropagation();
                onOpenQr(link);
              }}
              className="group/qr inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/5 text-white transition-colors hover:bg-white/10 hover:text-violet-300"
              title="QR-код"
            >
              <QrCode className="h-4 w-4 transition-transform duration-200 group-hover/qr:scale-110" />
            </button>

            <div className="relative">
              <button
                type="button"
                onClick={(event) => {
                  event.stopPropagation();
                  onToggleSettings(link.id);
                }}
                className={`group/settings inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors ${
                  settingsOpen
                    ? 'border-white/20 bg-white/[0.15] text-white'
                    : 'border-white/10 bg-white/5 text-white hover:bg-white/10'
                }`}
                title="Действия"
              >
                <Settings className={`h-4 w-4 transition-transform duration-200 ${
                  settingsOpen ? 'rotate-45' : 'group-hover/settings:rotate-45'
                }`} />
              </button>

              <AnimatePresence>
                {settingsOpen ? (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.95, y: 10 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95, y: 10 }}
                    transition={{ duration: 0.15 }}
                    onClick={(event) => event.stopPropagation()}
                    className="absolute right-0 top-[120%] z-[100] mt-1 flex w-64 flex-col rounded-xl border border-white/10 bg-[#111] p-2 shadow-[0_10px_40px_rgba(0,0,0,0.8)]"
                  >
                    <button
                      type="button"
                      onClick={() => {
                        onCloseSettings();
                        onEdit(link);
                      }}
                      className="inline-flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
                    >
                      <Edit2 className="h-4 w-4 text-blue-400" />
                      Изменить
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        onCloseSettings();
                        onToggleFavorite(link);
                      }}
                      className="inline-flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
                    >
                      <Star className={`h-4 w-4 text-amber-300 ${link.isFavorite ? 'fill-current' : ''}`} />
                      {link.isFavorite ? 'Убрать из избранного' : 'В избранное'}
                    </button>
                    <a
                      href={link.longUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      onClick={onCloseSettings}
                      className="inline-flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
                    >
                      <ExternalLink className="h-4 w-4 text-violet-400" />
                      Открыть оригинал
                    </a>
                    <div className="mx-2 my-1 h-px bg-white/10" />
                    <button
                      type="button"
                      onClick={() => {
                        onCloseSettings();
                        onRequestDelete(link);
                      }}
                      className="inline-flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm text-red-400 transition-colors hover:bg-red-500/10 hover:text-red-300"
                    >
                      <Trash2 className="h-4 w-4" />
                      Удалить
                    </button>
                  </motion.div>
                ) : null}
              </AnimatePresence>
            </div>
          </div>
        </div>
      </div>
    </motion.article>
  );
}
