"use client";

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { 
  Plus, 
  Copy,
  Trash2,
  Edit,
  Eye,
  RefreshCw
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useFunnels, useCreateFunnel, useDuplicateFunnel, useDeleteFunnel } from '@/lib/admin/hooks';
import { StatusBadge, DateDisplay, SearchBar, FilterSelect } from '@/components/admin/ui';
import { SORT_OPTIONS, STATUS_FILTER_OPTIONS } from '@/lib/admin/utils';

export default function AdminCatalogPage() {
  const router = useRouter();
  
  // Фильтры и поиск
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [sortBy, setSortBy] = useState('updatedAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  
  // Используем hooks для работы с данными
  const { funnels, pagination, loading, error, loadFunnels, refresh } = useFunnels({
    search: searchQuery,
    status: statusFilter,
    sortBy,
    sortOrder,
  });
  
  const { createFunnel } = useCreateFunnel();
  const { duplicateFunnel } = useDuplicateFunnel();
  const { deleteFunnel } = useDeleteFunnel();


  // Создание новой воронки
  const handleCreateFunnel = async () => {
    try {
      const createdFunnel = await createFunnel({
        name: 'Новая воронка',
        description: 'Описание новой воронки',
        funnelData: {
          meta: {
            id: `funnel-${Date.now()}`,
            title: 'Новая воронка',
            description: 'Описание новой воронки',
            firstScreenId: 'screen-1'
          },
          defaultTexts: {
            nextButton: 'Continue'
          },
          screens: [
            {
              id: 'screen-1',
              template: 'info',
              title: {
                text: 'Добро пожаловать!',
                font: 'manrope',
                weight: 'bold'
              },
              subtitle: {
                text: 'Это ваша новая воронка. Начните редактирование.',
                color: 'muted'
              },
              icon: {
                type: 'emoji',
                value: '🎯',
                size: 'lg'
              }
            }
          ]
        }
      });
      
      router.push(`/admin/builder/${createdFunnel._id}`);
    } catch (err) {
      // Ошибка уже обработана в хуке
      console.error('Failed to create funnel:', err);
    }
  };

  // Дублирование воронки
  const handleDuplicateFunnel = async (funnelId: string, funnelName: string) => {
    try {
      await duplicateFunnel(funnelId, `${funnelName} (копия)`);
      refresh();
    } catch (err) {
      console.error('Failed to duplicate funnel:', err);
    }
  };

  // Удаление воронки
  const handleDeleteFunnel = async (funnelId: string, funnelName: string) => {
    if (!confirm(`Вы уверены, что хотите удалить воронку "${funnelName}"?`)) {
      return;
    }

    try {
      await deleteFunnel(funnelId);
      refresh();
    } catch (err) {
      console.error('Failed to delete funnel:', err);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-gray-900">Каталог воронок</h1>
              <p className="mt-2 text-gray-600">
                Управляйте своими воронками и создавайте новые
              </p>
            </div>
            <Button onClick={handleCreateFunnel} className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              Создать воронку
            </Button>
          </div>
        </div>

        {/* Фильтры и поиск */}
        <div className="mb-6 bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex flex-col sm:flex-row gap-4">
            
            {/* Поиск */}
            <div className="flex-1">
              <SearchBar
                value={searchQuery}
                onChange={setSearchQuery}
                placeholder="Поиск по названию, описанию..."
              />
            </div>

            {/* Фильтр статуса */}
            <FilterSelect
              value={statusFilter}
              onChange={setStatusFilter}
              options={STATUS_FILTER_OPTIONS}
            />

            {/* Сортировка */}
            <FilterSelect
              value={`${sortBy}-${sortOrder}`}
              onChange={(value) => {
                const [field, order] = value.split('-');
                setSortBy(field);
                setSortOrder(order as 'asc' | 'desc');
              }}
              options={SORT_OPTIONS}
            />

            <Button
              variant="outline"
              onClick={refresh}
              disabled={loading}
            >
              <RefreshCw className={cn("h-4 w-4", loading && "animate-spin")} />
            </Button>
          </div>
        </div>

        {/* Ошибка */}
        {error && (
          <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="text-red-800">{error}</div>
          </div>
        )}

        {/* Список воронок */}
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          
          {loading ? (
            <div className="p-8 text-center text-gray-500">
              <RefreshCw className="h-6 w-6 animate-spin mx-auto mb-2" />
              Загружается...
            </div>
          ) : funnels.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              <div className="mb-4">Воронки не найдены</div>
              <Button onClick={handleCreateFunnel} variant="outline">
                <Plus className="h-4 w-4 mr-2" />
                Создать первую воронку
              </Button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Название
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Статус
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Статистика
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Обновлена
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Действия
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {funnels.map((funnel) => (
                    <tr key={funnel._id} className="hover:bg-gray-50">
                      <td className="px-6 py-4">
                        <div className="flex flex-col">
                          <div className="text-sm font-medium text-gray-900">
                            {funnel.name}
                          </div>
                          <div className="text-sm text-gray-500">
                            ID: {funnel.funnelData?.meta?.id || 'N/A'}
                          </div>
                          {funnel.description && (
                            <div className="text-sm text-gray-500 mt-1">
                              {funnel.description}
                            </div>
                          )}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <StatusBadge status={funnel.status} />
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm text-gray-900">
                          {funnel.usage.totalViews} просмотров
                        </div>
                        <div className="text-sm text-gray-500">
                          {funnel.usage.totalCompletions} завершений
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-900">
                          <DateDisplay date={funnel.updatedAt} />
                        </div>
                        <div className="text-sm text-gray-500">
                          v{funnel.version}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right">
                        <div className="flex items-center justify-end gap-2">
                          
                          {/* Просмотр воронки */}
                          <Link href={`/${funnel.funnelData?.meta?.id || funnel._id}`}>
                            <Button variant="ghost" title="Просмотр" className="h-8 w-8 p-0">
                              <Eye className="h-4 w-4" />
                            </Button>
                          </Link>

                          {/* Редактирование */}
                          <Link href={`/admin/builder/${funnel._id}`}>
                            <Button variant="ghost" title="Редактировать" className="h-8 w-8 p-0">
                              <Edit className="h-4 w-4" />
                            </Button>
                          </Link>

                          {/* Дублировать */}
                          <Button 
                            variant="ghost" 
                            title="Дублировать"
                            onClick={() => handleDuplicateFunnel(funnel._id, funnel.name)}
                            className="h-8 w-8 p-0"
                          >
                            <Copy className="h-4 w-4" />
                          </Button>

                          {/* Удалить (только черновики) */}
                          {funnel.status === 'draft' && (
                            <Button 
                              variant="ghost" 
                              title="Удалить"
                              onClick={() => handleDeleteFunnel(funnel._id, funnel.name)}
                              className="h-8 w-8 p-0 text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Пагинация */}
        {pagination.total > 1 && (
          <div className="mt-6 flex items-center justify-between">
            <div className="text-sm text-gray-700">
              Показано {pagination.count} из {pagination.totalItems} воронок
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                disabled={pagination.current <= 1}
                onClick={() => loadFunnels(pagination.current - 1)}
              >
                Предыдущая
              </Button>
              <span className="px-3 py-1 bg-gray-100 rounded text-sm">
                {pagination.current} / {pagination.total}
              </span>
              <Button
                variant="outline"
                disabled={pagination.current >= pagination.total}
                onClick={() => loadFunnels(pagination.current + 1)}
              >
                Следующая
              </Button>
            </div>
          </div>
        )}

      </div>
    </div>
  );
}
