import { useState } from 'react';
import { Trash2, Loader2, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';
import { useClient } from 'hooks/useClient';
import { useUserApps, type AppManifest } from 'state/useUserApps';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

export const AppsList = () => {
  const client = useClient();
  const { apps, isLoading, refetch } = useUserApps();
  const [deleting, setDeleting] = useState<AppManifest | null>(null);
  const [deletingInProgress, setDeletingInProgress] = useState(false);

  const confirmDelete = async () => {
    if (!deleting) return;
    setDeletingInProgress(true);
    try {
      await client.delete(`/apps/${deleting.slug}`);
      toast.success(`Deleted ${deleting.name}`);
      refetch();
    } catch {
      toast.error('Failed to delete app');
    } finally {
      setDeletingInProgress(false);
      setDeleting(null);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-5 w-5 animate-spin text-duck-dark/30 dark:text-foreground/30" />
      </div>
    );
  }

  if (apps.length === 0) {
    return (
      <div className="text-sm text-duck-dark/40 dark:text-foreground/40 py-8 text-center">
        No published apps yet. Publish a project from the Projects page.
      </div>
    );
  }

  return (
    <>
      <div className="flex flex-col gap-2">
        {apps.map((app) => (
          <div
            key={app.slug}
            className="flex items-center gap-4 rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-4"
          >
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium text-duck-dark dark:text-foreground">{app.name}</span>
                <span className="text-[10px] font-mono text-duck-dark/30 dark:text-foreground/30">v{app.version}</span>
              </div>
              {app.description && (
                <p className="text-xs text-duck-dark/50 dark:text-foreground/50 mt-0.5 truncate">{app.description}</p>
              )}
              <div className="flex items-center gap-3 mt-1.5 text-[11px] text-duck-dark/30 dark:text-foreground/30">
                <span>Source: <span className="font-mono">{app.sourceProject}</span></span>
                <span>Commit: <span className="font-mono">{app.commitHash}</span></span>
                <span>Published: {new Date(app.publishedAt).toLocaleDateString()}</span>
              </div>
            </div>
            <a
              href={`/api/app-serve/${app.slug}/`}
              target="_blank"
              rel="noopener noreferrer"
              className="shrink-0 p-2 rounded-md text-duck-dark/30 dark:text-foreground/30 hover:text-duck-teal hover:bg-duck-teal/10 transition-colors cursor-pointer"
              title="Open in new tab"
            >
              <ExternalLink className="h-4 w-4" />
            </a>
            <button
              type="button"
              onClick={() => setDeleting(app)}
              className="shrink-0 p-2 rounded-md text-duck-dark/30 dark:text-foreground/30 hover:text-red-500 hover:bg-red-500/10 transition-colors cursor-pointer"
              title="Delete app"
            >
              <Trash2 className="h-4 w-4" />
            </button>
          </div>
        ))}
      </div>

      <AlertDialog open={deleting !== null} onOpenChange={(open) => { if (!open) setDeleting(null); }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete published app</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete <strong>{deleting?.name}</strong>? This removes the published build. The source project is not affected.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deletingInProgress}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} disabled={deletingInProgress} className="bg-red-600 hover:bg-red-700">
              {deletingInProgress ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Delete'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};
