import { Loader2, FolderKanban } from 'lucide-react';
import { usePreview } from './PreviewContext';

export const PreviewApp = () => {
  const { slug, cwdSlug, url, loading, error, iframeKey, projects, startServer, setSelectedSlug, clearError } =
    usePreview();

  if (!slug) {
    if (projects.length === 0) {
      return (
        <div className="flex h-full w-full items-center justify-center text-duck-dark/30 text-sm">
          No projects found
        </div>
      );
    }

    return (
      <div className="flex h-full w-full flex-col items-center justify-center gap-3">
        <FolderKanban className="h-6 w-6 text-duck-dark/30" />
        <span className="text-sm text-duck-dark/40">Select a project to preview</span>
        <div className="flex flex-col gap-1 w-48">
          {projects.map((p) => (
            <button
              key={p.id}
              onClick={() => setSelectedSlug(p.id)}
              className="rounded px-3 py-1.5 text-xs text-left hover:bg-duck-dark/10 transition-colors cursor-pointer"
            >
              {p.name}
            </button>
          ))}
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex h-full w-full flex-col items-center justify-center gap-2 text-duck-dark/50 text-sm">
        <Loader2 className="h-5 w-5 animate-spin" />
        <span>Starting dev server...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-full w-full flex-col items-center justify-center gap-2 text-sm">
        <span className="text-red-500 px-4 text-center">{error}</span>
        <div className="flex gap-2">
          <button
            onClick={() => startServer(slug)}
            className="rounded px-3 py-1 text-xs bg-duck-dark/10 hover:bg-duck-dark/20 cursor-pointer"
          >
            Retry
          </button>
          {!cwdSlug && (
            <button onClick={clearError} className="rounded px-3 py-1 text-xs bg-duck-dark/10 hover:bg-duck-dark/20 cursor-pointer">
              Back
            </button>
          )}
        </div>
      </div>
    );
  }

  if (!url) return null;

  return <iframe key={iframeKey} src={url} className="h-full w-full border-none" title="Preview" />;
};
