import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Card } from './ui/card';
import { Badge } from './ui/badge';
import { Checkbox } from './ui/checkbox';
import { Switch } from './ui/switch';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { GameController, Globe, DeviceMobile, FileCode, Info, Check } from '@phosphor-icons/react';
import { toast } from 'sonner';

interface NewProjectModalProps {
  open: boolean;
  onClose: () => void;
  onCreateProject: (config: ProjectConfig) => void;
}

export interface ProjectConfig {
  name: string;
  template: string;
  platforms: {
    roblox: boolean;
    web: boolean;
    mobile: boolean;
  };
  nexusEngine: boolean;
  passportAuth: boolean;
}

const templates = [
  {
    id: 'roblox-starter',
    name: 'Roblox Game Starter',
    description: 'Basic Roblox game template with player management and leaderboards',
    icon: '🎮',
    popular: true,
  },
  {
    id: 'multiplayer',
    name: 'Cross-Platform Multiplayer',
    description: 'Synchronized multiplayer game across Roblox, web, and mobile',
    icon: '🌐',
    popular: true,
  },
  {
    id: 'transmedia',
    name: 'Transmedia Story Project',
    description: 'Story-driven experience that spans multiple platforms',
    icon: '📚',
    popular: false,
  },
  {
    id: 'blank',
    name: 'Blank Project',
    description: 'Start from scratch with an empty project',
    icon: '📄',
    popular: false,
  },
];

export function NewProjectModal({ open, onClose, onCreateProject }: NewProjectModalProps) {
  const [step, setStep] = useState(1);
  const [projectName, setProjectName] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState('');
  const [platforms, setPlatforms] = useState({
    roblox: true,
    web: false,
    mobile: false,
  });
  const [nexusEngine, setNexusEngine] = useState(false);
  const [passportAuth, setPassportAuth] = useState(false);

  const handleReset = () => {
    setStep(1);
    setProjectName('');
    setSelectedTemplate('');
    setPlatforms({ roblox: true, web: false, mobile: false });
    setNexusEngine(false);
    setPassportAuth(false);
  };

  const handleCreate = () => {
    if (!projectName.trim()) {
      toast.error('Please enter a project name');
      return;
    }
    if (!selectedTemplate) {
      toast.error('Please select a template');
      return;
    }

    onCreateProject({
      name: projectName,
      template: selectedTemplate,
      platforms,
      nexusEngine,
      passportAuth,
    });

    handleReset();
    onClose();
    toast.success(`Project "${projectName}" created!`);
  };

  const handleClose = () => {
    handleReset();
    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle className="text-2xl">Create New Project</DialogTitle>
        </DialogHeader>

        <div className="flex items-center justify-center gap-2 mb-6">
          {[1, 2, 3].map((s) => (
            <div key={s} className="flex items-center">
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold ${
                  s <= step
                    ? 'bg-accent text-accent-foreground'
                    : 'bg-muted text-muted-foreground'
                }`}
              >
                {s < step ? <Check size={16} weight="bold" /> : s}
              </div>
              {s < 3 && (
                <div
                  className={`w-16 h-1 ${
                    s < step ? 'bg-accent' : 'bg-muted'
                  }`}
                />
              )}
            </div>
          ))}
        </div>

        {step === 1 && (
          <div>
            <h3 className="text-lg font-semibold mb-4">Choose a Template</h3>
            <div className="grid grid-cols-2 gap-4 max-h-[400px] overflow-y-auto">
              {templates.map((template) => (
                <Card
                  key={template.id}
                  className={`p-4 cursor-pointer transition-all hover:border-accent ${
                    selectedTemplate === template.id
                      ? 'border-2 border-accent bg-accent/5'
                      : ''
                  }`}
                  onClick={() => setSelectedTemplate(template.id)}
                >
                  <div className="flex items-start justify-between mb-2">
                    <div className="text-3xl">{template.icon}</div>
                    {template.popular && (
                      <Badge variant="secondary" className="text-xs">
                        Popular
                      </Badge>
                    )}
                  </div>
                  <h4 className="font-semibold mb-1">{template.name}</h4>
                  <p className="text-sm text-muted-foreground">
                    {template.description}
                  </p>
                </Card>
              ))}
            </div>
            <div className="flex justify-end gap-2 mt-6">
              <Button variant="outline" onClick={handleClose}>
                Cancel
              </Button>
              <Button
                onClick={() => setStep(2)}
                disabled={!selectedTemplate}
                className="bg-accent text-accent-foreground hover:bg-accent/90"
              >
                Next
              </Button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <h3 className="text-lg font-semibold mb-4">Project Configuration</h3>
            <div className="space-y-6">
              <div>
                <Label htmlFor="project-name">Project Name</Label>
                <Input
                  id="project-name"
                  value={projectName}
                  onChange={(e) => setProjectName(e.target.value)}
                  placeholder="My Awesome Game"
                  className="mt-2"
                />
              </div>

              <div>
                <Label className="mb-3 block">Target Platforms</Label>
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <Checkbox
                      id="platform-roblox"
                      checked={platforms.roblox}
                      onCheckedChange={(checked: boolean) =>
                        setPlatforms((p) => ({ ...p, roblox: checked === true }))
                      }
                    />
                    <Label htmlFor="platform-roblox" className="flex items-center gap-2 cursor-pointer">
                      <GameController className="text-accent" />
                      Roblox
                    </Label>
                  </div>
                  <div className="flex items-center gap-3">
                    <Checkbox
                      id="platform-web"
                      checked={platforms.web}
                      onCheckedChange={(checked: boolean) =>
                        setPlatforms((p) => ({ ...p, web: checked === true }))
                      }
                    />
                    <Label htmlFor="platform-web" className="flex items-center gap-2 cursor-pointer">
                      <Globe className="text-accent" />
                      Web Browser
                    </Label>
                  </div>
                  <div className="flex items-center gap-3">
                    <Checkbox
                      id="platform-mobile"
                      checked={platforms.mobile}
                      onCheckedChange={(checked: boolean) =>
                        setPlatforms((p) => ({ ...p, mobile: checked === true }))
                      }
                    />
                    <Label htmlFor="platform-mobile" className="flex items-center gap-2 cursor-pointer">
                      <DeviceMobile className="text-accent" />
                      Mobile (iOS/Android)
                    </Label>
                  </div>
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Label htmlFor="nexus-engine">Enable Nexus Engine</Label>
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger>
                          <Info size={16} className="text-muted-foreground" />
                        </TooltipTrigger>
                        <TooltipContent>
                          <p className="max-w-xs text-sm">
                            Nexus Engine synchronizes game state across all platforms in real-time
                          </p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </div>
                  <Switch
                    id="nexus-engine"
                    checked={nexusEngine}
                    onCheckedChange={setNexusEngine}
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Label htmlFor="passport-auth">Enable Passport Auth</Label>
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger>
                          <Info size={16} className="text-muted-foreground" />
                        </TooltipTrigger>
                        <TooltipContent>
                          <p className="max-w-xs text-sm">
                            AeThex Passport provides unified identity across all your games
                          </p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </div>
                  <Switch
                    id="passport-auth"
                    checked={passportAuth}
                    onCheckedChange={setPassportAuth}
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-between mt-6">
              <Button variant="outline" onClick={() => setStep(1)}>
                Back
              </Button>
              <div className="flex gap-2">
                <Button variant="outline" onClick={handleClose}>
                  Cancel
                </Button>
                <Button
                  onClick={() => setStep(3)}
                  className="bg-accent text-accent-foreground hover:bg-accent/90"
                >
                  Next
                </Button>
              </div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <h3 className="text-lg font-semibold mb-4">Review & Create</h3>
            <Card className="p-4 space-y-3">
              <div>
                <Label className="text-muted-foreground">Project Name</Label>
                <p className="font-semibold">{projectName}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">Template</Label>
                <p className="font-semibold">
                  {templates.find((t) => t.id === selectedTemplate)?.name}
                </p>
              </div>
              <div>
                <Label className="text-muted-foreground">Platforms</Label>
                <div className="flex gap-2 mt-1">
                  {platforms.roblox && <Badge>Roblox</Badge>}
                  {platforms.web && <Badge>Web</Badge>}
                  {platforms.mobile && <Badge>Mobile</Badge>}
                </div>
              </div>
              <div>
                <Label className="text-muted-foreground">Features</Label>
                <div className="flex gap-2 mt-1">
                  {nexusEngine && <Badge variant="secondary">Nexus Engine</Badge>}
                  {passportAuth && <Badge variant="secondary">Passport Auth</Badge>}
                  {!nexusEngine && !passportAuth && (
                    <span className="text-sm text-muted-foreground">None</span>
                  )}
                </div>
              </div>
            </Card>

            <div className="flex justify-between mt-6">
              <Button variant="outline" onClick={() => setStep(2)}>
                Back
              </Button>
              <div className="flex gap-2">
                <Button variant="outline" onClick={handleClose}>
                  Cancel
                </Button>
                <Button
                  onClick={handleCreate}
                  className="bg-accent text-accent-foreground hover:bg-accent/90"
                >
                  <FileCode className="mr-2" />
                  Create Project
                </Button>
              </div>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
