import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from './ui/dropdown-menu';
import {
  Download,
  Power,
  PowerOff,
  MoreVertical,
  Trash2,
  RefreshCw,
  Loader2,
  ArrowRight,
  Cable,
} from 'lucide-react';
import { ServiceIcon } from './ServiceIcon';
import type { PackageWithStatus } from '../types/package';
import { __ } from '@/lib/i18n';

export interface PackageCardProps {
  package: PackageWithStatus;
  showInstall?: boolean;
  showUninstall?: boolean;
  onActivate?: (slug: string) => void;
  onDeactivate?: (slug: string) => void;
  onInstall?: (slug: string) => void;
  onUninstall?: (slug: string) => void;
  onUpdate?: (slug: string) => void;
  onConnect?: (slug: string) => void;
  connectionStatus?: 'connected' | 'not_connected';
  actionInProgress?: string | null;
  actionTypeInProgress?: 'update' | 'activate' | 'deactivate' | 'install' | 'uninstall' | null;
  installDisabled?: boolean;
  installDisabledReason?: string;
}

export function PackageCard({
  package: pkg,
  showInstall = false,
  showUninstall = false,
  onActivate,
  onDeactivate,
  onInstall,
  onUninstall,
  onUpdate,
  onConnect,
  connectionStatus,
  actionInProgress,
  actionTypeInProgress = null,
  installDisabled = false,
  installDisabledReason,
}: PackageCardProps) {
  const isProcessing = actionInProgress === pkg.slug;
  const isInstalled = pkg.status === 'installed' || pkg.status === 'update_available';
  const isActive = pkg.is_active === true;

  return (
    <Card
      data-testid="package-card"
      className="group overflow-hidden transition-all duration-200 hover:shadow-md hover:border-slate-300 hover:-translate-y-px"
    >
      <CardContent className="p-5">
        {/* Header: Icon + Name + Status Badges */}
        <div className="flex items-start gap-3.5">
          <div className="w-12 h-12 rounded-xl bg-slate-50 border border-slate-100/80 flex items-center justify-center flex-shrink-0 transition-colors group-hover:border-slate-200">
            <ServiceIcon service={pkg.slug} size={28} className="flex-shrink-0" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h3 className="font-semibold text-[15px] text-slate-900 leading-tight">
                {pkg.name}
              </h3>
              {isInstalled && (
                <Badge
                  variant={isActive ? 'success' : 'secondary'}
                  className="text-[10px] px-1.5 py-0"
                >
                  {isActive ? __('Active') : __('Inactive')}
                </Badge>
              )}
            </div>
          </div>
        </div>

        {/* Description */}
        <p className="text-sm text-slate-500 mt-3 leading-relaxed line-clamp-2">
          {pkg.description}
        </p>

        {/* Version info */}
        {pkg.status === 'update_available' && pkg.installed_version && (
          <div className="flex items-center gap-2 mt-3 px-2.5 py-1.5 rounded-md bg-warning-muted/50 border border-warning/20">
            <span className="text-[11px] font-medium text-slate-500">
              {__('v%s').replace('%s', pkg.installed_version)}
            </span>
            <ArrowRight className="h-3 w-3 text-warning-text flex-shrink-0" />
            <span className="text-[11px] font-semibold text-warning-text">
              {__('v%s').replace('%s', pkg.version)}
            </span>
          </div>
        )}

        {/* Actions Footer */}
        <div className="flex items-center gap-2 mt-4 pt-3 border-t border-slate-100">
          {/* Category + Version */}
          <div className="flex items-center gap-1.5">
            <Badge variant="outline" className="text-[10px] px-1.5 py-0">
              {pkg.category}
            </Badge>
            {isInstalled && pkg.status !== 'update_available' && pkg.installed_version && (
              <span className="text-[10px] text-slate-400 font-medium tabular-nums">
                {'v' + pkg.installed_version}
              </span>
            )}
            {pkg.status === 'not_installed' && pkg.version && (
              <span className="text-[10px] text-slate-400 font-medium tabular-nums">
                {'v' + pkg.version}
              </span>
            )}
          </div>

          <div className="ml-auto flex items-center gap-1">
            {/* Install button (not_installed + showInstall) */}
            {pkg.status === 'not_installed' && showInstall && (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <span>
                      <Button
                        variant="accent"
                        size="sm"
                        onClick={() => onInstall?.(pkg.slug)}
                        disabled={isProcessing || installDisabled}
                      >
                        {isProcessing && actionTypeInProgress === 'install' ? (
                          <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
                        ) : (
                          <Download className="h-4 w-4 mr-1.5" />
                        )}
                        {__('Install')}
                      </Button>
                    </span>
                  </TooltipTrigger>
                  {installDisabled && installDisabledReason && (
                    <TooltipContent>{installDisabledReason}</TooltipContent>
                  )}
                </Tooltip>
              </TooltipProvider>
            )}

            {/* Update button (update_available) */}
            {pkg.status === 'update_available' && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => onUpdate?.(pkg.slug)}
                disabled={isProcessing}
                className="border-warning text-warning-text hover:bg-warning-muted"
              >
                {isProcessing && actionTypeInProgress === 'update' ? (
                  <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
                ) : (
                  <RefreshCw className="h-4 w-4 mr-1.5" />
                )}
                {__('Update')}
              </Button>
            )}

            {/* Activate button (installed + inactive) */}
            {isInstalled && !isActive && (
              <Button
                variant="default"
                size="sm"
                onClick={() => onActivate?.(pkg.slug)}
                disabled={isProcessing}
              >
                {isProcessing && actionTypeInProgress === 'activate' ? (
                  <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
                ) : (
                  <Power className="h-4 w-4 mr-1.5" />
                )}
                {__('Activate')}
              </Button>
            )}

            {/* Connect/Manage button (installed + active + has credentials) */}
            {isInstalled && isActive && onConnect && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => onConnect(pkg.slug)}
                disabled={isProcessing}
              >
                <Cable className="h-4 w-4 mr-1.5" />
                {connectionStatus === 'connected' ? __('Manage') : __('Connect')}
              </Button>
            )}

            {/* Deactivate button (installed + active) */}
            {isInstalled && isActive && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => onDeactivate?.(pkg.slug)}
                disabled={isProcessing}
              >
                {isProcessing && actionTypeInProgress === 'deactivate' ? (
                  <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
                ) : (
                  <PowerOff className="h-4 w-4 mr-1.5" />
                )}
                {__('Deactivate')}
              </Button>
            )}

            {/* Three-dot menu with Uninstall (installed + inactive + showUninstall) */}
            {showUninstall && isInstalled && !isActive && (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0"
                    disabled={isProcessing}
                  >
                    <MoreVertical className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem
                    onClick={() => onUninstall?.(pkg.slug)}
                    className="text-red-600 focus:text-red-600"
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    {__('Uninstall')}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
