"use client"

import { cn } from "@mdxui/primitives/lib/utils"
import { Button } from "@mdxui/primitives/button"
import { Input } from "@mdxui/primitives/input"
import { Textarea } from "@mdxui/primitives/textarea"
import { Label } from "@mdxui/primitives/label"
import { Badge } from "@mdxui/primitives/badge"
import { Checkbox } from "@mdxui/primitives/checkbox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@mdxui/primitives/select"
import { useState } from "react"
import type { BugReportData, BugReportUser, BugSeverity } from "./types"

const SEVERITY_OPTIONS: Array<{ value: BugSeverity; label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }> = [
  { value: 'cosmetic', label: 'Cosmetic', variant: 'secondary' },
  { value: 'minor', label: 'Minor', variant: 'outline' },
  { value: 'major', label: 'Major', variant: 'default' },
  { value: 'critical', label: 'Critical', variant: 'destructive' },
]

interface BugReportContentProps {
  showStepsToReproduce?: boolean
  showWorkedBefore?: boolean
  user?: BugReportUser
  context?: Record<string, unknown>
  captureMetadata?: boolean
  onSubmit?: (data: BugReportData) => Promise<void> | void
  apiEndpoint?: string
  submitLabel?: string
  onSuccess: () => void
  onError: (error: string) => void
}

function captureCurrentMetadata() {
  return {
    url: window.location.href,
    timestamp: new Date().toISOString(),
    viewport: { width: window.innerWidth, height: window.innerHeight },
    userAgent: navigator.userAgent,
  }
}

export function BugReportContent({
  showStepsToReproduce = true,
  showWorkedBefore = true,
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  submitLabel = "Submit Bug Report",
  onSuccess,
  onError,
}: BugReportContentProps) {
  const [title, setTitle] = useState("")
  const [expected, setExpected] = useState("")
  const [actual, setActual] = useState("")
  const [stepsToReproduce, setStepsToReproduce] = useState("")
  const [severity, setSeverity] = useState<BugSeverity>("minor")
  const [workedBefore, setWorkedBefore] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (title.trim().length < 5) {
      newErrors.title = "Title must be at least 5 characters"
    }
    if (expected.trim().length < 10) {
      newErrors.expected = "Expected behavior must be at least 10 characters"
    }
    if (actual.trim().length < 10) {
      newErrors.actual = "Actual behavior must be at least 10 characters"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async () => {
    if (!validate()) return

    setIsSubmitting(true)

    const data: BugReportData = {
      title: title.trim(),
      expected: expected.trim(),
      actual: actual.trim(),
      stepsToReproduce: showStepsToReproduce && stepsToReproduce.trim() ? stepsToReproduce.trim() : undefined,
      severity,
      workedBefore: showWorkedBefore ? workedBefore : undefined,
      user,
      context,
      metadata: captureMetadata ? captureCurrentMetadata() : undefined,
    }

    try {
      if (onSubmit) {
        await onSubmit(data)
      } else if (apiEndpoint) {
        const response = await fetch(apiEndpoint, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
        })
        if (!response.ok) {
          throw new Error(`Failed to submit: ${response.statusText}`)
        }
      }
      onSuccess()
    } catch (err) {
      onError(err instanceof Error ? err.message : "Failed to submit bug report")
    } finally {
      setIsSubmitting(false)
    }
  }

  const isValid =
    title.trim().length >= 5 &&
    expected.trim().length >= 10 &&
    actual.trim().length >= 10

  const selectedSeverityOption = SEVERITY_OPTIONS.find(opt => opt.value === severity)

  return (
    <div className="flex flex-col gap-4">
      {/* Title */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="bug-title" className="text-sm text-foreground">
          Bug Title
        </Label>
        <Input
          id="bug-title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="Brief summary of the issue"
          className={cn(errors.title && "border-destructive")}
        />
        {errors.title && (
          <p className="text-xs text-destructive">{errors.title}</p>
        )}
      </div>

      {/* Expected Behavior */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="bug-expected" className="text-sm text-foreground">
          Expected Behavior
        </Label>
        <Textarea
          id="bug-expected"
          value={expected}
          onChange={(e) => setExpected(e.target.value)}
          placeholder="What did you expect to happen?"
          rows={3}
          className={cn("resize-y min-h-20 max-h-32", errors.expected && "border-destructive")}
        />
        {errors.expected && (
          <p className="text-xs text-destructive">{errors.expected}</p>
        )}
      </div>

      {/* Actual Behavior */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="bug-actual" className="text-sm text-foreground">
          Actual Behavior
        </Label>
        <Textarea
          id="bug-actual"
          value={actual}
          onChange={(e) => setActual(e.target.value)}
          placeholder="What actually happened?"
          rows={3}
          className={cn("resize-y min-h-20 max-h-32", errors.actual && "border-destructive")}
        />
        {errors.actual && (
          <p className="text-xs text-destructive">{errors.actual}</p>
        )}
      </div>

      {/* Steps to Reproduce */}
      {showStepsToReproduce && (
        <div className="flex flex-col gap-1">
          <Label htmlFor="bug-steps" className="text-sm text-foreground">
            Steps to Reproduce <span className="text-muted-foreground">(optional)</span>
          </Label>
          <Textarea
            id="bug-steps"
            value={stepsToReproduce}
            onChange={(e) => setStepsToReproduce(e.target.value)}
            placeholder="1. Go to...&#10;2. Click on...&#10;3. Observe..."
            rows={3}
            className="resize-y min-h-20 max-h-32"
          />
        </div>
      )}

      {/* Severity */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="bug-severity" className="text-sm text-foreground">
          Severity
        </Label>
        <Select value={severity} onValueChange={(value) => setSeverity(value as BugSeverity)}>
          <SelectTrigger className="w-full">
            <SelectValue>
              {selectedSeverityOption && (
                <Badge variant={selectedSeverityOption.variant}>
                  {selectedSeverityOption.label}
                </Badge>
              )}
            </SelectValue>
          </SelectTrigger>
          <SelectContent side="top">
            {SEVERITY_OPTIONS.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                <Badge variant={opt.variant}>{opt.label}</Badge>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Worked Before Toggle */}
      {showWorkedBefore && (
        <div className="flex items-center gap-2">
          <Checkbox
            id="bug-worked-before"
            checked={workedBefore}
            onCheckedChange={(checked) => setWorkedBefore(checked === true)}
          />
          <Label htmlFor="bug-worked-before" className="text-sm text-foreground cursor-pointer">
            This worked before (regression)
          </Label>
        </div>
      )}

      {/* Submit Button */}
      <Button
        onClick={handleSubmit}
        disabled={!isValid || isSubmitting}
        className="w-full"
      >
        {isSubmitting ? "Submitting..." : submitLabel}
      </Button>
    </div>
  )
}
