'use client';

import { useState, useCallback } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { RefreshCw, Upload } from 'lucide-react';
import { AppPlatform, AppVersion } from '@/domain/entities/app-version';
import {
  listVersions,
  deleteVersion,
  toggleVersion,
} from '@/infrastructure/repositories/api-app-version.repository';
import { VersionCard } from '@/presentation/components/app-versions/version-card';
import { UploadModal } from '@/presentation/components/app-versions/upload-modal';
import { EditModal } from '@/presentation/components/app-versions/edit-modal';

type PlatformFilter = AppPlatform | 'all';

const PLATFORM_BUTTONS: { value: PlatformFilter; label: string }[] = [
  { value: 'all', label: '全部' },
  { value: 'android', label: 'Android' },
  { value: 'ios', label: 'iOS' },
];

export default function AppVersionsPage() {
  const queryClient = useQueryClient();
  const [platformFilter, setPlatformFilter] = useState<PlatformFilter>('all');
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [editingVersionId, setEditingVersionId] = useState<string | null>(null);

  const { data: versions = [], isLoading, error, refetch } = useQuery<AppVersion[]>({
    queryKey: ['app-versions', platformFilter],
    queryFn: () =>
      listVersions({
        platform: platformFilter === 'all' ? undefined : platformFilter,
        includeDisabled: true,
      }),
  });

  const handleRefresh = useCallback(() => {
    refetch();
  }, [refetch]);

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这个版本吗？此操作不可恢复。')) return;
    try {
      await deleteVersion(id);
      toast.success('版本已删除');
      queryClient.invalidateQueries({ queryKey: ['app-versions'] });
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '删除失败');
    }
  };

  const handleToggle = async (id: string, isEnabled: boolean) => {
    try {
      await toggleVersion(id, isEnabled);
      toast.success(isEnabled ? '版本已启用' : '版本已禁用');
      queryClient.invalidateQueries({ queryKey: ['app-versions'] });
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '操作失败');
    }
  };

  const handleUploadSuccess = () => {
    setShowUploadModal(false);
    toast.success('版本上传成功');
    queryClient.invalidateQueries({ queryKey: ['app-versions'] });
  };

  const handleEditSuccess = () => {
    setEditingVersionId(null);
    toast.success('版本更新成功');
    queryClient.invalidateQueries({ queryKey: ['app-versions'] });
  };

  return (
    <div className="space-y-5">
      {/* Page header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-foreground">App 版本管理</h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            管理 IT0 App 的 APK / IPA 版本发布与升级策略
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={handleRefresh}
            disabled={isLoading}
            className="flex items-center gap-1.5 px-3 py-2 rounded-md text-sm bg-accent text-foreground hover:bg-accent/80 transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
            刷新
          </button>
          <button
            onClick={() => setShowUploadModal(true)}
            className="flex items-center gap-1.5 px-3 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
          >
            <Upload className="w-4 h-4" />
            上传新版本
          </button>
        </div>
      </div>

      {/* Platform filter */}
      <div className="flex items-center gap-2">
        <span className="text-sm text-muted-foreground shrink-0">平台筛选:</span>
        <div className="flex gap-1.5">
          {PLATFORM_BUTTONS.map(({ value, label }) => (
            <button
              key={value}
              onClick={() => setPlatformFilter(value)}
              className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
                platformFilter === value
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-accent text-muted-foreground hover:text-foreground hover:bg-accent/80'
              }`}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Error state */}
      {error && (
        <div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4 text-red-400 text-sm">
          加载失败：{error instanceof Error ? error.message : String(error)}
        </div>
      )}

      {/* Loading skeleton */}
      {isLoading && (
        <div className="space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="bg-card rounded-lg border p-4 animate-pulse">
              <div className="flex gap-3 mb-3">
                <div className="h-5 w-16 rounded bg-accent" />
                <div className="h-5 w-24 rounded bg-accent" />
                <div className="h-5 w-20 rounded bg-accent" />
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div className="h-4 rounded bg-accent" />
                <div className="h-4 rounded bg-accent" />
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Version list */}
      {!isLoading && !error && (
        <div className="space-y-3">
          {versions.length === 0 ? (
            <div className="bg-card rounded-lg border p-12 text-center">
              <p className="text-muted-foreground text-sm mb-4">暂无版本数据</p>
              <button
                onClick={() => setShowUploadModal(true)}
                className="px-4 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
              >
                上传第一个版本
              </button>
            </div>
          ) : (
            versions.map((version) => (
              <VersionCard
                key={version.id}
                version={version}
                onEdit={() => setEditingVersionId(version.id)}
                onDelete={() => handleDelete(version.id)}
                onToggle={(enabled) => handleToggle(version.id, enabled)}
              />
            ))
          )}
        </div>
      )}

      {/* Modals */}
      {showUploadModal && (
        <UploadModal
          onClose={() => setShowUploadModal(false)}
          onSuccess={handleUploadSuccess}
        />
      )}
      {editingVersionId && (
        <EditModal
          versionId={editingVersionId}
          onClose={() => setEditingVersionId(null)}
          onSuccess={handleEditSuccess}
        />
      )}
    </div>
  );
}
