'use client';

import { useState } from 'react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import {
  ArrowLeft,
  ArrowRight,
  Check,
  FileCode,
  Folder,
  Layers,
  Building2,
  Zap,
  HelpCircle,
  Shield,
  Milestone,
  Bot,
  MessageSquare,
  User,
  Sparkles,
  GitBranch,
  AlertCircle,
  CheckCircle2,
} from 'lucide-react';
import { cn } from '@/lib/utils';

// Wizard state type definition
interface WizardState {
  step: number;
  projectName: string;
  description: string;
  repoUrl: string;
  complexity: 'script' | 'simple' | 'medium' | 'complex' | null;
  clientMode: 'technical' | 'auto' | null;
  autonomyLevel: 'full_control' | 'milestone' | 'autonomous' | null;
}

// Complexity options with descriptions
const complexityOptions = [
  {
    id: 'script' as const,
    label: 'Script',
    icon: FileCode,
    description: 'Single-file utilities, automation scripts, CLI tools',
    scope: 'Minutes to 1-2 hours, single file or small module',
    examples: 'Data migration script, API integration helper, Build tool plugin',
    skipConfig: true, // Scripts skip client mode, autonomy, sprints - just chat with agent
  },
  {
    id: 'simple' as const,
    label: 'Simple',
    icon: Folder,
    description: 'Small applications with clear requirements',
    scope: '2-3 days, handful of files/components',
    examples: 'Landing page, REST API endpoint, Browser extension',
    skipConfig: false,
  },
  {
    id: 'medium' as const,
    label: 'Medium',
    icon: Layers,
    description: 'Full applications with multiple features',
    scope: '2-3 weeks, multiple modules/services',
    examples: 'Admin dashboard, E-commerce store, Mobile app',
    skipConfig: false,
  },
  {
    id: 'complex' as const,
    label: 'Complex',
    icon: Building2,
    description: 'Enterprise systems with many moving parts',
    scope: '2-3 months, distributed architecture',
    examples: 'SaaS platform, Microservices ecosystem, Data pipeline',
    skipConfig: false,
  },
];

// Client mode options
const clientModeOptions = [
  {
    id: 'technical' as const,
    label: 'Technical Mode',
    icon: Zap,
    description: "I'll provide detailed technical specifications",
    details: [
      'Upload existing specs or PRDs',
      'Define API contracts and schemas',
      'Specify architecture patterns',
      'Direct sprint planning input',
    ],
  },
  {
    id: 'auto' as const,
    label: 'Auto Mode',
    icon: HelpCircle,
    description: 'Help me figure out what I need',
    details: [
      'Guided requirements discovery',
      'AI suggests best practices',
      'Interactive brainstorming sessions',
      'Progressive refinement of scope',
    ],
  },
];

// Autonomy level options with approval matrix
const autonomyOptions = [
  {
    id: 'full_control' as const,
    label: 'Full Control',
    icon: Shield,
    description: 'Review every action before it happens',
    approvals: {
      codeChanges: true,
      issueUpdates: true,
      architectureDecisions: true,
      sprintPlanning: true,
      deployments: true,
    },
    recommended: 'New users or critical projects',
  },
  {
    id: 'milestone' as const,
    label: 'Milestone',
    icon: Milestone,
    description: 'Review at sprint boundaries',
    approvals: {
      codeChanges: false,
      issueUpdates: false,
      architectureDecisions: true,
      sprintPlanning: true,
      deployments: true,
    },
    recommended: 'Balanced control (recommended)',
  },
  {
    id: 'autonomous' as const,
    label: 'Autonomous',
    icon: Bot,
    description: 'Only major decisions require approval',
    approvals: {
      codeChanges: false,
      issueUpdates: false,
      architectureDecisions: true,
      sprintPlanning: false,
      deployments: true,
    },
    recommended: 'Experienced users or low-risk projects',
  },
];

// Step indicator component - dynamic based on complexity
function StepIndicator({
  currentStep,
  isScriptMode
}: {
  currentStep: number;
  isScriptMode: boolean;
}) {
  // Scripts have a simplified 4-step flow
  const scriptSteps = ['Basic Info', 'Complexity', 'Agent Chat', 'Review'];
  const fullSteps = ['Basic Info', 'Complexity', 'Client Mode', 'Autonomy', 'Agent Chat', 'Review'];

  const steps = isScriptMode ? scriptSteps : fullSteps;
  const totalSteps = steps.length;

  // Map display step to actual step for scripts
  const displayStep = isScriptMode && currentStep > 2
    ? (currentStep === 5 ? 3 : currentStep === 6 ? 4 : currentStep)
    : currentStep;

  return (
    <div className="w-full">
      <div className="mb-2 flex items-center justify-between text-sm text-muted-foreground">
        <span>Step {displayStep} of {totalSteps}</span>
        <span>{steps[displayStep - 1]}</span>
      </div>
      <div className="flex gap-1">
        {Array.from({ length: totalSteps }, (_, i) => (
          <div
            key={i}
            className={cn(
              'h-2 flex-1 rounded-full transition-colors',
              i + 1 < displayStep
                ? 'bg-primary'
                : i + 1 === displayStep
                  ? 'bg-primary/70'
                  : 'bg-muted'
            )}
          />
        ))}
      </div>
    </div>
  );
}

// Selectable card component for options
function SelectableCard({
  selected,
  onClick,
  children,
  className,
}: {
  selected: boolean;
  onClick: () => void;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'w-full rounded-lg border-2 p-4 text-left transition-all',
        'hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
        selected ? 'border-primary bg-primary/5' : 'border-border',
        className
      )}
    >
      {children}
    </button>
  );
}

// Step 1: Basic Info
function BasicInfoStep({
  state,
  updateState,
}: {
  state: WizardState;
  updateState: (updates: Partial<WizardState>) => void;
}) {
  const [errors, setErrors] = useState<{ projectName?: string }>({});

  const validateProjectName = (name: string) => {
    if (!name.trim()) {
      setErrors({ projectName: 'Project name is required' });
      return false;
    }
    if (name.length < 3) {
      setErrors({ projectName: 'Project name must be at least 3 characters' });
      return false;
    }
    setErrors({});
    return true;
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">Create New Project</h2>
        <p className="mt-1 text-muted-foreground">
          Let&apos;s start with the basics. Give your project a name and description.
        </p>
      </div>

      <div className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="project-name">
            Project Name <span className="text-destructive">*</span>
          </Label>
          <Input
            id="project-name"
            placeholder="e.g., E-Commerce Platform Redesign"
            value={state.projectName}
            onChange={(e) => {
              updateState({ projectName: e.target.value });
              if (errors.projectName) validateProjectName(e.target.value);
            }}
            onBlur={(e) => validateProjectName(e.target.value)}
            aria-invalid={!!errors.projectName}
            aria-describedby={errors.projectName ? 'project-name-error' : undefined}
          />
          {errors.projectName && (
            <p id="project-name-error" className="text-sm text-destructive">
              {errors.projectName}
            </p>
          )}
        </div>

        <div className="space-y-2">
          <Label htmlFor="description">Description (Optional)</Label>
          <Textarea
            id="description"
            placeholder="Briefly describe what this project is about..."
            value={state.description}
            onChange={(e) => updateState({ description: e.target.value })}
            rows={3}
          />
          <p className="text-xs text-muted-foreground">
            A clear description helps the AI agents understand your project better.
          </p>
        </div>

        <div className="space-y-2">
          <Label htmlFor="repo-url">Repository URL (Optional)</Label>
          <div className="flex gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-md border bg-muted">
              <GitBranch className="h-4 w-4 text-muted-foreground" />
            </div>
            <Input
              id="repo-url"
              placeholder="https://github.com/your-org/your-repo"
              value={state.repoUrl}
              onChange={(e) => updateState({ repoUrl: e.target.value })}
              className="flex-1"
            />
          </div>
          <p className="text-xs text-muted-foreground">
            Connect an existing repository or leave blank to create a new one.
          </p>
        </div>
      </div>
    </div>
  );
}

// Step 2: Complexity Assessment
function ComplexityStep({
  state,
  updateState,
}: {
  state: WizardState;
  updateState: (updates: Partial<WizardState>) => void;
}) {
  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">Project Complexity</h2>
        <p className="mt-1 text-muted-foreground">
          How complex is your project? This helps us assign the right resources.
        </p>
        {state.complexity === 'script' && (
          <p className="mt-2 text-sm text-primary">
            Scripts use a simplified flow - you&apos;ll skip to agent chat directly.
          </p>
        )}
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {complexityOptions.map((option) => {
          const Icon = option.icon;
          const isSelected = state.complexity === option.id;

          return (
            <SelectableCard
              key={option.id}
              selected={isSelected}
              onClick={() => updateState({ complexity: option.id })}
            >
              <div className="space-y-3">
                <div className="flex items-start justify-between">
                  <div
                    className={cn(
                      'flex h-10 w-10 items-center justify-center rounded-lg',
                      isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted'
                    )}
                  >
                    <Icon className="h-5 w-5" />
                  </div>
                  {isSelected && (
                    <div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-primary-foreground">
                      <Check className="h-4 w-4" />
                    </div>
                  )}
                </div>
                <div>
                  <h3 className="font-semibold">{option.label}</h3>
                  <p className="mt-1 text-sm text-muted-foreground">{option.description}</p>
                </div>
                <Separator />
                <div className="space-y-1 text-sm">
                  <p className="text-muted-foreground">
                    <span className="font-medium text-foreground">Scope:</span> {option.scope}
                  </p>
                  <p className="text-muted-foreground">
                    <span className="font-medium text-foreground">Examples:</span> {option.examples}
                  </p>
                </div>
              </div>
            </SelectableCard>
          );
        })}
      </div>
    </div>
  );
}

// Step 3: Client Mode Selection
function ClientModeStep({
  state,
  updateState,
}: {
  state: WizardState;
  updateState: (updates: Partial<WizardState>) => void;
}) {
  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">How Would You Like to Work?</h2>
        <p className="mt-1 text-muted-foreground">
          Choose how you want to interact with Syndarix agents.
        </p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {clientModeOptions.map((option) => {
          const Icon = option.icon;
          const isSelected = state.clientMode === option.id;

          return (
            <SelectableCard
              key={option.id}
              selected={isSelected}
              onClick={() => updateState({ clientMode: option.id })}
              className="h-full"
            >
              <div className="flex h-full flex-col space-y-4">
                <div className="flex items-start justify-between">
                  <div
                    className={cn(
                      'flex h-12 w-12 items-center justify-center rounded-lg',
                      isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted'
                    )}
                  >
                    <Icon className="h-6 w-6" />
                  </div>
                  {isSelected && (
                    <div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-primary-foreground">
                      <Check className="h-4 w-4" />
                    </div>
                  )}
                </div>

                <div>
                  <h3 className="text-lg font-semibold">{option.label}</h3>
                  <p className="mt-1 text-muted-foreground">{option.description}</p>
                </div>

                <Separator />

                <ul className="flex-1 space-y-2">
                  {option.details.map((detail) => (
                    <li key={detail} className="flex items-start gap-2 text-sm">
                      <CheckCircle2
                        className={cn(
                          'mt-0.5 h-4 w-4 shrink-0',
                          isSelected ? 'text-primary' : 'text-muted-foreground'
                        )}
                      />
                      <span className="text-muted-foreground">{detail}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </SelectableCard>
          );
        })}
      </div>
    </div>
  );
}

// Step 4: Autonomy Level Selection
function AutonomyStep({
  state,
  updateState,
}: {
  state: WizardState;
  updateState: (updates: Partial<WizardState>) => void;
}) {
  const approvalLabels: Record<string, string> = {
    codeChanges: 'Code Changes',
    issueUpdates: 'Issue Updates',
    architectureDecisions: 'Architecture Decisions',
    sprintPlanning: 'Sprint Planning',
    deployments: 'Deployments',
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">Autonomy Level</h2>
        <p className="mt-1 text-muted-foreground">
          How much control do you want over the AI agents&apos; actions?
        </p>
      </div>

      <div className="grid gap-4">
        {autonomyOptions.map((option) => {
          const Icon = option.icon;
          const isSelected = state.autonomyLevel === option.id;

          return (
            <SelectableCard
              key={option.id}
              selected={isSelected}
              onClick={() => updateState({ autonomyLevel: option.id })}
            >
              <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
                <div className="flex items-start gap-4">
                  <div
                    className={cn(
                      'flex h-10 w-10 shrink-0 items-center justify-center rounded-lg',
                      isSelected ? 'bg-primary text-primary-foreground' : 'bg-muted'
                    )}
                  >
                    <Icon className="h-5 w-5" />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold">{option.label}</h3>
                      {isSelected && (
                        <div className="flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground">
                          <Check className="h-3 w-3" />
                        </div>
                      )}
                    </div>
                    <p className="text-sm text-muted-foreground">{option.description}</p>
                    <p className="mt-1 text-xs text-muted-foreground">
                      <span className="font-medium">Best for:</span> {option.recommended}
                    </p>
                  </div>
                </div>

                <div className="flex flex-wrap gap-2 md:justify-end">
                  {Object.entries(option.approvals).map(([key, requiresApproval]) => (
                    <Badge
                      key={key}
                      variant={requiresApproval ? 'default' : 'secondary'}
                      className="text-xs"
                    >
                      {requiresApproval ? 'Approve' : 'Auto'}:{' '}
                      {approvalLabels[key]}
                    </Badge>
                  ))}
                </div>
              </div>
            </SelectableCard>
          );
        })}
      </div>

      <Card className="bg-muted/50">
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-base">
            <AlertCircle className="h-4 w-4" />
            Approval Matrix
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="pb-2 text-left font-medium">Action Type</th>
                  <th className="pb-2 text-center font-medium">Full Control</th>
                  <th className="pb-2 text-center font-medium">Milestone</th>
                  <th className="pb-2 text-center font-medium">Autonomous</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {Object.keys(autonomyOptions[0].approvals).map((key) => (
                  <tr key={key}>
                    <td className="py-2 text-muted-foreground">{approvalLabels[key]}</td>
                    {autonomyOptions.map((option) => (
                      <td key={option.id} className="py-2 text-center">
                        {option.approvals[key as keyof typeof option.approvals] ? (
                          <Badge variant="outline" className="text-xs">
                            Required
                          </Badge>
                        ) : (
                          <span className="text-xs text-muted-foreground">Automatic</span>
                        )}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// Step 5: Agent Chat Placeholder
function AgentChatStep() {
  const mockMessages = [
    {
      id: 1,
      role: 'agent',
      name: 'Product Owner Agent',
      message:
        "Hello! I'm your Product Owner agent. I'll help you define what we're building. Can you tell me more about your project goals?",
      timestamp: '10:00 AM',
    },
    {
      id: 2,
      role: 'user',
      name: 'You',
      message:
        "I want to build an e-commerce platform for selling handmade crafts. It should have user accounts, a product catalog, and checkout.",
      timestamp: '10:02 AM',
    },
    {
      id: 3,
      role: 'agent',
      name: 'Product Owner Agent',
      message:
        "Great! Let me break this down into user stories. For the MVP, I'd suggest focusing on: user registration/login, product browsing with categories, and a simple cart checkout. Should we also include seller accounts or just a single store?",
      timestamp: '10:03 AM',
    },
  ];

  return (
    <div className="space-y-6">
      <div>
        <div className="flex items-center gap-2">
          <h2 className="text-2xl font-bold">Requirements Discovery</h2>
          <Badge variant="secondary">Coming in Phase 4</Badge>
        </div>
        <p className="mt-1 text-muted-foreground">
          In the full version, you&apos;ll chat with our Product Owner agent here to define requirements.
        </p>
      </div>

      <Card>
        <CardHeader className="border-b pb-4">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
              <Bot className="h-5 w-5 text-primary" />
            </div>
            <div>
              <CardTitle className="text-base">Product Owner Agent</CardTitle>
              <CardDescription>Requirements discovery and sprint planning</CardDescription>
            </div>
            <Badge variant="outline" className="ml-auto">
              Preview Only
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {/* Chat Messages Area */}
          <div className="max-h-80 space-y-4 overflow-y-auto p-4">
            {mockMessages.map((msg) => (
              <div
                key={msg.id}
                className={cn(
                  'flex gap-3',
                  msg.role === 'user' ? 'flex-row-reverse' : ''
                )}
              >
                <div
                  className={cn(
                    'flex h-8 w-8 shrink-0 items-center justify-center rounded-full',
                    msg.role === 'agent' ? 'bg-primary/10' : 'bg-muted'
                  )}
                >
                  {msg.role === 'agent' ? (
                    <Bot className="h-4 w-4 text-primary" />
                  ) : (
                    <User className="h-4 w-4 text-muted-foreground" />
                  )}
                </div>
                <div
                  className={cn(
                    'max-w-[80%] rounded-lg px-4 py-2',
                    msg.role === 'agent'
                      ? 'bg-muted'
                      : 'bg-primary text-primary-foreground'
                  )}
                >
                  <p className="text-sm">{msg.message}</p>
                  <p
                    className={cn(
                      'mt-1 text-xs',
                      msg.role === 'agent' ? 'text-muted-foreground' : 'text-primary-foreground/70'
                    )}
                  >
                    {msg.timestamp}
                  </p>
                </div>
              </div>
            ))}
          </div>

          {/* Chat Input Area (disabled preview) */}
          <div className="border-t p-4">
            <div className="flex gap-2">
              <Input
                placeholder="Type your message... (disabled in preview)"
                disabled
                className="flex-1"
              />
              <Button disabled>
                <MessageSquare className="h-4 w-4" />
              </Button>
            </div>
            <p className="mt-2 text-center text-xs text-muted-foreground">
              This chat interface is a preview. Full agent interaction will be available in Phase 4.
            </p>
          </div>
        </CardContent>
      </Card>

      <Card className="border-dashed bg-muted/30">
        <CardContent className="flex items-center gap-4 p-6">
          <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
            <Sparkles className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h4 className="font-medium">What to Expect in the Full Version</h4>
            <ul className="mt-2 space-y-1 text-sm text-muted-foreground">
              <li>- Interactive requirements gathering with AI Product Owner</li>
              <li>- Architecture spike with BA and Architect agents</li>
              <li>- Collaborative backlog creation and prioritization</li>
              <li>- Real-time refinement of user stories</li>
            </ul>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// Step 6: Review & Create
function ReviewStep({ state }: { state: WizardState }) {
  const complexity = complexityOptions.find((o) => o.id === state.complexity);
  const clientMode = clientModeOptions.find((o) => o.id === state.clientMode);
  const autonomy = autonomyOptions.find((o) => o.id === state.autonomyLevel);

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">Review Your Project</h2>
        <p className="mt-1 text-muted-foreground">
          Please review your selections before creating the project.
        </p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Basic Info Card */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Basic Information</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div>
              <p className="text-sm font-medium">Project Name</p>
              <p className="text-sm text-muted-foreground">
                {state.projectName || 'Not specified'}
              </p>
            </div>
            <div>
              <p className="text-sm font-medium">Description</p>
              <p className="text-sm text-muted-foreground">
                {state.description || 'No description provided'}
              </p>
            </div>
            <div>
              <p className="text-sm font-medium">Repository</p>
              <p className="text-sm text-muted-foreground">
                {state.repoUrl || 'New repository will be created'}
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Complexity Card */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Project Complexity</CardTitle>
          </CardHeader>
          <CardContent>
            {complexity ? (
              <div className="flex items-start gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                  <complexity.icon className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <p className="font-medium">{complexity.label}</p>
                  <p className="text-sm text-muted-foreground">{complexity.description}</p>
                </div>
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">Not selected</p>
            )}
          </CardContent>
        </Card>

        {/* Client Mode Card */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Interaction Mode</CardTitle>
          </CardHeader>
          <CardContent>
            {clientMode ? (
              <div className="flex items-start gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                  <clientMode.icon className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <p className="font-medium">{clientMode.label}</p>
                  <p className="text-sm text-muted-foreground">{clientMode.description}</p>
                </div>
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">Not selected</p>
            )}
          </CardContent>
        </Card>

        {/* Autonomy Card */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Autonomy Level</CardTitle>
          </CardHeader>
          <CardContent>
            {autonomy ? (
              <div className="flex items-start gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                  <autonomy.icon className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <p className="font-medium">{autonomy.label}</p>
                  <p className="text-sm text-muted-foreground">{autonomy.description}</p>
                </div>
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">Not selected</p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Summary Alert */}
      <Card className="border-primary/50 bg-primary/5">
        <CardContent className="flex items-start gap-4 p-6">
          <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-primary" />
          <div>
            <h4 className="font-medium">Ready to Create</h4>
            <p className="mt-1 text-sm text-muted-foreground">
              Once you create this project, Syndarix will set up your environment and begin the
              requirements discovery phase with the Product Owner agent.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// Main wizard component
export default function ProjectWizardPrototype() {
  const [state, setState] = useState<WizardState>({
    step: 1,
    projectName: '',
    description: '',
    repoUrl: '',
    complexity: null,
    clientMode: null,
    autonomyLevel: null,
  });

  const [isCreating, setIsCreating] = useState(false);
  const [isCreated, setIsCreated] = useState(false);

  // Check if script mode is active (simplified flow)
  const isScriptMode = state.complexity === 'script';

  // For scripts: steps are 1, 2, 5, 6 (skip 3 and 4)
  // For others: steps are 1, 2, 3, 4, 5, 6
  const getLastStep = () => (isScriptMode ? 6 : 6);

  const updateState = (updates: Partial<WizardState>) => {
    setState((prev) => ({ ...prev, ...updates }));
  };

  const canProceed = () => {
    switch (state.step) {
      case 1:
        return state.projectName.trim().length >= 3;
      case 2:
        return state.complexity !== null;
      case 3:
        return isScriptMode || state.clientMode !== null;
      case 4:
        return isScriptMode || state.autonomyLevel !== null;
      case 5:
        return true; // Agent chat is preview only
      case 6:
        return true;
      default:
        return false;
    }
  };

  const goNext = () => {
    if (canProceed()) {
      let nextStep = state.step + 1;

      // For scripts, skip from step 2 directly to step 5 (agent chat)
      if (isScriptMode && state.step === 2) {
        nextStep = 5;
        // Auto-set defaults for skipped steps
        updateState({
          step: nextStep,
          clientMode: 'auto',
          autonomyLevel: 'autonomous',
        });
        return;
      }

      if (nextStep <= getLastStep()) {
        updateState({ step: nextStep });
      }
    }
  };

  const goBack = () => {
    if (state.step > 1) {
      let prevStep = state.step - 1;

      // For scripts, go from step 5 back to step 2
      if (isScriptMode && state.step === 5) {
        prevStep = 2;
      }

      updateState({ step: prevStep });
    }
  };

  const handleCreate = async () => {
    setIsCreating(true);
    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 2000));
    setIsCreating(false);
    setIsCreated(true);
  };

  const handleReset = () => {
    setState({
      step: 1,
      projectName: '',
      description: '',
      repoUrl: '',
      complexity: null,
      clientMode: null,
      autonomyLevel: null,
    });
    setIsCreated(false);
  };

  // Success screen
  if (isCreated) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-4 py-8">
          <div className="mx-auto max-w-2xl">
            <Card className="text-center">
              <CardContent className="space-y-6 p-8">
                <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-green-100 dark:bg-green-900">
                  <CheckCircle2 className="h-8 w-8 text-green-600 dark:text-green-400" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold">Project Created Successfully!</h2>
                  <p className="mt-2 text-muted-foreground">
                    &quot;{state.projectName}&quot; has been created. The Product Owner agent will
                    begin the requirements discovery process shortly.
                  </p>
                </div>
                <div className="flex flex-col justify-center gap-4 sm:flex-row">
                  <Button onClick={() => alert('This would navigate to the project dashboard')}>
                    Go to Project Dashboard
                  </Button>
                  <Button variant="outline" onClick={handleReset}>
                    Create Another Project
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
        <div className="mx-auto max-w-3xl">
          {/* Step Indicator */}
          <div className="mb-8">
            <StepIndicator currentStep={state.step} isScriptMode={isScriptMode} />
          </div>

          {/* Step Content */}
          <Card>
            <CardContent className="p-6 md:p-8">
              {state.step === 1 && <BasicInfoStep state={state} updateState={updateState} />}
              {state.step === 2 && <ComplexityStep state={state} updateState={updateState} />}
              {state.step === 3 && <ClientModeStep state={state} updateState={updateState} />}
              {state.step === 4 && <AutonomyStep state={state} updateState={updateState} />}
              {state.step === 5 && <AgentChatStep />}
              {state.step === 6 && <ReviewStep state={state} />}
            </CardContent>

            {/* Navigation Footer */}
            <Separator />
            <div className="flex items-center justify-between p-6">
              <Button
                variant="ghost"
                onClick={goBack}
                disabled={state.step === 1}
                className={state.step === 1 ? 'invisible' : ''}
              >
                <ArrowLeft className="mr-2 h-4 w-4" />
                Back
              </Button>

              <div className="flex gap-2">
                {state.step < 6 ? (
                  <Button onClick={goNext} disabled={!canProceed()}>
                    Next
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </Button>
                ) : (
                  <Button onClick={handleCreate} disabled={isCreating}>
                    {isCreating ? (
                      <>
                        <span className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
                        Creating...
                      </>
                    ) : (
                      <>
                        <Check className="mr-2 h-4 w-4" />
                        Create Project
                      </>
                    )}
                  </Button>
                )}
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
