import { useState } from 'react';
import { Loader2, Rocket } from 'lucide-react';
import { toast } from 'sonner';
import { useClient } from 'hooks/useClient';
import { useUserApps } from 'state/useUserApps';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { resolveIcon, availableIconNames } from '../../utils/resolve-icon';

type PublishDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  projectSlug: string;
  projectName: string;
};

export const PublishDialog = ({ open, onOpenChange, projectSlug, projectName }: PublishDialogProps) => {
  const client = useClient();
  const { refetch } = useUserApps();

  const [name, setName] = useState(projectName);
  const [icon, setIcon] = useState('Globe');
  const [description, setDescription] = useState('');
  const [publishing, setPublishing] = useState(false);
  const [version, setVersion] = useState<string | null>(null);
  const [iconPickerOpen, setIconPickerOpen] = useState(false);

  // Fetch version from package.json when dialog opens
  const fetchVersion = async () => {
    try {
      const res = await client.get<{ content: string }>(`/file-browser/read?path=/Projects/${projectSlug}/package.json`);
      const pkg = JSON.parse(res.content);
      setVersion(pkg.version ?? '0.1.0');
    } catch {
      setVersion('0.1.0');
    }
  };

  const handleOpenChange = (nextOpen: boolean) => {
    if (nextOpen) {
      setName(projectName);
      setIcon('Globe');
      setDescription('');
      setPublishing(false);
      fetchVersion();
    }
    onOpenChange(nextOpen);
  };

  const handlePublish = async () => {
    setPublishing(true);
    try {
      await client.post('/apps/publish', {
        projectSlug,
        name,
        icon,
        description,
      });
      refetch();
      toast.success(`Published ${name} successfully`);
      onOpenChange(false);
    } catch (err: unknown) {
      const msg = err && typeof err === 'object' && 'message' in err ? String(err.message) : 'Publish failed';
      toast.error(msg);
    } finally {
      setPublishing(false);
    }
  };

  const SelectedIcon = resolveIcon(icon);

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Rocket className="h-4 w-4" />
            Publish App
          </DialogTitle>
          <DialogDescription>
            Build and publish <strong>{projectSlug}</strong> as a standalone app.
          </DialogDescription>
        </DialogHeader>

        <div className="flex flex-col gap-3">
          <label className="flex flex-col gap-1">
            <span className="text-xs text-muted-foreground">App Name</span>
            <input
              type="text"
              value={name}
              onChange={(ev) => setName(ev.target.value)}
              className="rounded-md border border-duck-dark/15 bg-transparent px-3 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-emerald-500/30"
            />
          </label>

          <label className="flex flex-col gap-1">
            <span className="text-xs text-muted-foreground">Icon</span>
            <div className="relative">
              <button
                type="button"
                onClick={() => setIconPickerOpen(!iconPickerOpen)}
                className="flex items-center gap-2 rounded-md border border-duck-dark/15 bg-transparent px-3 py-1.5 text-sm cursor-pointer hover:bg-duck-dark/5 w-full"
              >
                <SelectedIcon className="h-4 w-4" />
                <span>{icon}</span>
              </button>
              {iconPickerOpen && (
                <div className="absolute top-full left-0 mt-1 z-50 bg-background border border-duck-dark/15 rounded-md shadow-lg p-2 grid grid-cols-8 gap-1 max-h-48 overflow-y-auto w-full">
                  {availableIconNames.map((iconName) => {
                    const IconComp = resolveIcon(iconName);
                    return (
                      <button
                        key={iconName}
                        type="button"
                        onClick={() => {
                          setIcon(iconName);
                          setIconPickerOpen(false);
                        }}
                        className={`p-1.5 rounded cursor-pointer transition-colors ${
                          icon === iconName ? 'bg-emerald-500/20 text-emerald-400' : 'hover:bg-duck-dark/10'
                        }`}
                        title={iconName}
                      >
                        <IconComp className="h-4 w-4" />
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </label>

          <label className="flex flex-col gap-1">
            <span className="text-xs text-muted-foreground">Description</span>
            <textarea
              value={description}
              onChange={(ev) => setDescription(ev.target.value)}
              rows={2}
              className="rounded-md border border-duck-dark/15 bg-transparent px-3 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-emerald-500/30 resize-none"
            />
          </label>

          {version && (
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <span>Version:</span>
              <span className="font-mono">{version}</span>
            </div>
          )}

          <button
            type="button"
            disabled={publishing || !name.trim()}
            onClick={handlePublish}
            className="flex items-center justify-center gap-2 rounded-md bg-emerald-500 hover:bg-emerald-500/90 text-white py-2 px-4 text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            {publishing ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Publishing...
              </>
            ) : (
              <>
                <Rocket className="h-4 w-4" />
                Publish
              </>
            )}
          </button>
        </div>
      </DialogContent>
    </Dialog>
  );
};
