'use client'

import type React from 'react'
import { useMemo, useState } from 'react'
import { Button } from '../../components/Button'
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from '../../components/Card'
import { Checkbox } from '../../components/Checkbox'
import { Input } from '../../components/Input'
import { Label } from '../../components/Label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../components/Select'
import { Textarea } from '../../components/Textarea'
import {
  SvgAddSquare,
  SvgAiSparkles,
  SvgDocumentSetting,
  SvgTools,
} from '../../icons'

type Step =
  | 'CHOOSE_GOAL'
  | 'DEFINE_COMPONENT'
  | 'SELECT_SOURCE_TYPE'
  | 'PROVIDE_SOURCE'
  | 'REFINE_DOCS'
  | 'REFINE_FIX'
  | 'ADD_INSPIRATION'
  | 'ADD_INSTRUCTIONS'
  | 'GENERATED'

const sourceOptions = {
  SHADCN: 'Shadcn Component Name',
  URL: 'URL to Source',
  CODE: 'Pasted Code Snippet',
  OTHER: 'Local Path or Other',
} as const

type SourceOptionKey = keyof typeof sourceOptions
type SourceOptionValue = (typeof sourceOptions)[SourceOptionKey]

const mainGoals = {
  BUILD: 'Build a new component from scratch',
  DOCS: 'Create or update documentation (MDX & stories)',
  FIX: 'Fix an existing component',
} as const

type MainGoalValue = (typeof mainGoals)[keyof typeof mainGoals]

const docOptions = {
  KEEP_EXAMPLES: 'Keep existing examples',
  USE_CONTENT: 'Use existing content from MDX',
  MORE_EXAMPLES: 'Generate additional examples',
} as const

type DocOptionKey = keyof typeof docOptions

interface GoalCardProps {
  icon: React.ReactNode
  title: MainGoalValue
  onClick: () => void
}

const GoalCard: React.FC<GoalCardProps> = ({ icon, title, onClick }) => (
  <button
    onClick={onClick}
    className="flex w-full flex-col items-center justify-center space-y-3 rounded-lg border bg-background-alt p-6 text-center transition-colors hover:border-primary"
  >
    {icon}
    <p className="font-semibold">{title}</p>
  </button>
)

export const PromptGenerator = () => {
  const [componentName, setComponentName] = useState('')
  const [sourceType, setSourceType] = useState<SourceOptionValue>(
    sourceOptions.SHADCN,
  )
  const [sourceValue, setSourceValue] = useState('')
  const [mainGoal, setMainGoal] = useState<MainGoalValue | ''>('')
  const [docSelections, setDocSelections] = useState<
    Partial<Record<DocOptionKey, boolean>>
  >({})
  const [fixInstructions, setFixInstructions] = useState('')
  const [inspirationComponents, setInspirationComponents] = useState<string[]>([
    '',
  ])
  const [specificInstructions, setSpecificInstructions] = useState('')
  const [finalPrompt, setFinalPrompt] = useState('')
  const [_copyStatus, setCopyStatus] = useState('')
  const [currentStep, setCurrentStep] = useState<Step>('CHOOSE_GOAL')

  const handleGoalSelection = (goal: MainGoalValue) => {
    setMainGoal(goal)
    setCurrentStep('DEFINE_COMPONENT')
  }

  const handleDocSelection = (key: DocOptionKey, checked: boolean) => {
    setDocSelections((prev) => ({ ...prev, [key]: checked }))
  }

  const handleInspirationChange = (index: number, value: string) => {
    const newInspirations = [...inspirationComponents]
    newInspirations[index] = value
    setInspirationComponents(newInspirations)
  }

  const addInspirationRow = () => {
    setInspirationComponents([...inspirationComponents, ''])
  }

  const resetWizard = () => {
    setComponentName('')
    setSourceType(sourceOptions.SHADCN)
    setSourceValue('')
    setMainGoal('')
    setDocSelections({})
    setFixInstructions('')
    setInspirationComponents([''])
    setSpecificInstructions('')
    setFinalPrompt('')
    setCopyStatus('')
    setCurrentStep('CHOOSE_GOAL')
  }

  const generatePrompt = () => {
    let prompt = `Component: \`${componentName}\`\n`
    if (mainGoal === mainGoals.BUILD) {
      prompt += `Source Type: ${sourceType}\n`
      prompt += `Source: ${sourceType === sourceOptions.CODE ? `\n\`\`\`\n${sourceValue}\n\`\`\`` : `\`${sourceValue}\``}\n`
    }
    prompt += `Goal: ${mainGoal}\n`

    if (mainGoal === mainGoals.DOCS) {
      const selected = (Object.keys(docSelections) as DocOptionKey[])
        .filter((key) => docSelections[key])
        .map((key) => docOptions[key])
      if (selected.length > 0) {
        prompt += `Doc Options: ${selected.join(', ')}\n`
      }
    }

    if (mainGoal === mainGoals.FIX) {
      prompt += `Fix Instructions: ${fixInstructions}\n`
    }

    const inspirations = inspirationComponents
      .map((s) => s.trim())
      .filter(Boolean)
    if (inspirations.length > 0) {
      prompt += `Inspiration Components: ${inspirations.map((i) => `\`${i}\``).join(', ')}\n`
    }

    if (specificInstructions.trim()) {
      prompt += `Specific Instructions: ${specificInstructions.trim()}\n`
    }

    setFinalPrompt(prompt)
    void navigator.clipboard.writeText(prompt)
    setCopyStatus('Copied!')
    setCurrentStep('GENERATED')
    setTimeout(() => setCopyStatus(''), 3000)
  }

  const renderStep = () => {
    switch (currentStep) {
      case 'CHOOSE_GOAL':
        return (
          <CardContent className="grid grid-cols-1 gap-4 md:grid-cols-3">
            <GoalCard
              icon={<SvgAddSquare className="h-8 w-8 text-primary" />}
              title={mainGoals.BUILD}
              onClick={() => handleGoalSelection(mainGoals.BUILD)}
            />
            <GoalCard
              icon={<SvgDocumentSetting className="h-8 w-8 text-primary" />}
              title={mainGoals.DOCS}
              onClick={() => handleGoalSelection(mainGoals.DOCS)}
            />
            <GoalCard
              icon={<SvgTools className="h-8 w-8 text-primary" />}
              title={mainGoals.FIX}
              onClick={() => handleGoalSelection(mainGoals.FIX)}
            />
          </CardContent>
        )
      case 'DEFINE_COMPONENT':
        return (
          <CardContent>
            <Label htmlFor="componentName">Component Name or Path</Label>
            <Input
              id="componentName"
              placeholder="e.g., Button or components/Button.tsx"
              value={componentName}
              onChange={(e) => setComponentName(e.target.value)}
            />
          </CardContent>
        )
      case 'SELECT_SOURCE_TYPE':
        return (
          <CardContent>
            <Label>Where is the component coming from?</Label>
            <Select
              onValueChange={(value: SourceOptionValue) => setSourceType(value)}
              value={sourceType}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select a source..." />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(sourceOptions).map(([key, value]) => (
                  <SelectItem key={key} value={value}>
                    {value}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </CardContent>
        )
      case 'PROVIDE_SOURCE':
        return (
          <CardContent>
            <Label htmlFor="sourceValue">Source</Label>
            {sourceType === sourceOptions.CODE ? (
              <Textarea
                id="sourceValue"
                placeholder="Paste component code here..."
                value={sourceValue}
                onChange={(e) => setSourceValue(e.target.value)}
                rows={10}
              />
            ) : (
              <Input
                id="sourceValue"
                placeholder={
                  sourceType === sourceOptions.SHADCN
                    ? 'e.g., Dropdown Menu'
                    : sourceType === sourceOptions.URL
                      ? 'e.g., https://ui.shadcn.com/docs/components/dropdown-menu'
                      : 'e.g., components/Select.tsx'
                }
                value={sourceValue}
                onChange={(e) => setSourceValue(e.target.value)}
              />
            )}
          </CardContent>
        )
      case 'REFINE_DOCS':
        return (
          <CardContent className="space-y-3">
            <Label>Documentation Options</Label>
            {(Object.keys(docOptions) as DocOptionKey[]).map((key) => (
              <div key={key} className="flex items-center gap-2">
                <Checkbox
                  id={key}
                  checked={!!docSelections[key]}
                  onCheckedChange={(checked) =>
                    handleDocSelection(key, !!checked)
                  }
                />
                <Label htmlFor={key}>{docOptions[key]}</Label>
              </div>
            ))}
          </CardContent>
        )
      case 'REFINE_FIX':
        return (
          <CardContent>
            <Label htmlFor="fixInstructions">Describe the issue</Label>
            <Textarea
              id="fixInstructions"
              placeholder="e.g., The component is not rendering correctly on mobile..."
              value={fixInstructions}
              onChange={(e) => setFixInstructions(e.target.value)}
            />
          </CardContent>
        )
      case 'ADD_INSPIRATION':
        return (
          <CardContent className="space-y-2">
            <Label>
              Any other components we should look at for inspiration?
            </Label>
            {inspirationComponents.map((val, i) => (
              <Input
                key={i}
                placeholder="e.g., components/Select.tsx"
                value={val}
                onChange={(e) => handleInspirationChange(i, e.target.value)}
              />
            ))}
            <Button variant="ghost" size="sm" onClick={addInspirationRow}>
              + Add another
            </Button>
          </CardContent>
        )
      case 'ADD_INSTRUCTIONS':
        return (
          <CardContent>
            <Label htmlFor="specificInstructions">
              Any other specific instructions?
            </Label>
            <Textarea
              id="specificInstructions"
              placeholder="e.g., Take colors from SelectContent and copy into new DropdownContent."
              value={specificInstructions}
              onChange={(e) => setSpecificInstructions(e.target.value)}
            />
          </CardContent>
        )
      case 'GENERATED':
        return (
          <CardContent className="flex flex-col items-center justify-center space-y-4 text-center">
            <div className="bg-success-faded flex h-16 w-16 items-center justify-center rounded-full">
              <SvgAiSparkles className="h-8 w-8 text-success" />
            </div>
            <div className="space-y-1">
              <p className="font-semibold">Your AI prompt has been created!</p>
              <p className="text-sm text-muted-foreground">
                It has been copied to your clipboard.
              </p>
            </div>
            <pre className="w-full whitespace-pre-wrap rounded-md border bg-background p-4 text-left text-sm">
              {finalPrompt}
            </pre>
            <Button onClick={resetWizard} className="mt-4">
              Go Again!
            </Button>
          </CardContent>
        )
      default:
        return null
    }
  }

  const nextStep = () => {
    switch (currentStep) {
      case 'DEFINE_COMPONENT':
        if (mainGoal === mainGoals.BUILD) {
          setCurrentStep('SELECT_SOURCE_TYPE')
        } else if (mainGoal === mainGoals.DOCS) {
          setCurrentStep('REFINE_DOCS')
        } else if (mainGoal === mainGoals.FIX) {
          setCurrentStep('REFINE_FIX')
        }
        break
      case 'SELECT_SOURCE_TYPE':
        setCurrentStep('PROVIDE_SOURCE')
        break
      case 'PROVIDE_SOURCE':
        setCurrentStep('ADD_INSPIRATION')
        break
      case 'REFINE_DOCS':
      case 'REFINE_FIX':
        setCurrentStep('ADD_INSPIRATION')
        break
      case 'ADD_INSPIRATION':
        setCurrentStep('ADD_INSTRUCTIONS')
        break
      case 'ADD_INSTRUCTIONS':
        generatePrompt()
        break
    }
  }

  const prevStep = () => {
    switch (currentStep) {
      case 'DEFINE_COMPONENT':
        setCurrentStep('CHOOSE_GOAL')
        break
      case 'SELECT_SOURCE_TYPE':
        setCurrentStep('DEFINE_COMPONENT')
        break
      case 'PROVIDE_SOURCE':
        setCurrentStep('SELECT_SOURCE_TYPE')
        break
      case 'REFINE_DOCS':
      case 'REFINE_FIX':
        setCurrentStep('DEFINE_COMPONENT')
        break
      case 'ADD_INSPIRATION':
        if (mainGoal === mainGoals.BUILD) {
          setCurrentStep('PROVIDE_SOURCE')
        } else {
          setCurrentStep('REFINE_DOCS')
        }
        break
      case 'ADD_INSTRUCTIONS':
        setCurrentStep('ADD_INSPIRATION')
        break
    }
  }

  const canGoNext = useMemo(() => {
    switch (currentStep) {
      case 'DEFINE_COMPONENT':
        return componentName.trim() !== ''
      case 'PROVIDE_SOURCE':
        return sourceValue.trim() !== ''
      default:
        return true
    }
  }, [currentStep, componentName, sourceValue])

  const cardTitle = useMemo(() => {
    if (currentStep === 'CHOOSE_GOAL') return 'What do you want to do?'
    return 'AI Prompt Generator'
  }, [currentStep])

  return (
    <Card className="my-6 max-w-2xl">
      <CardHeader>
        <CardTitle>{cardTitle}</CardTitle>
      </CardHeader>
      {renderStep()}
      {currentStep !== 'GENERATED' && currentStep !== 'CHOOSE_GOAL' && (
        <CardFooter className="flex justify-between">
          <Button
            variant="ghost"
            onClick={prevStep}
            disabled={currentStep === 'DEFINE_COMPONENT'}
          >
            Back
          </Button>
          <Button onClick={nextStep} disabled={!canGoNext}>
            {currentStep === 'ADD_INSTRUCTIONS' ? 'Generate Prompt' : 'Next'}
          </Button>
        </CardFooter>
      )}
    </Card>
  )
}
