"use client"

import { cn } from "@mdxui/primitives/lib/utils"
import { Button } from "@mdxui/primitives/button"
import { Textarea } from "@mdxui/primitives/textarea"
import { Label } from "@mdxui/primitives/label"
import { Badge } from "@mdxui/primitives/badge"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@mdxui/primitives/select"
import { useState } from "react"
import type { Severity, ErrorReportData, ErrorReportUser, ErrorDetails, ErrorReportMetadata } from "./types"

const severityOptions: Array<{ value: Severity; label: string; variant: 'secondary' | 'outline' | 'warning' | 'destructive' }> = [
  { value: 'low', label: 'Low', variant: 'secondary' },
  { value: 'medium', label: 'Medium', variant: 'outline' },
  { value: 'high', label: 'High', variant: 'warning' },
  { value: 'critical', label: 'Critical', variant: 'destructive' },
]

interface ErrorReportContentProps {
  showSeverity?: boolean
  errorDetails?: ErrorDetails
  user?: ErrorReportUser
  context?: Record<string, unknown>
  captureMetadata?: boolean
  onSubmit?: (data: ErrorReportData) => Promise<void> | void
  apiEndpoint?: string
  submitLabel?: string
  onSuccess: () => void
  onError: (error: string) => void
}

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

export function ErrorReportContent({
  showSeverity = true,
  errorDetails,
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  submitLabel = "Submit Report",
  onSuccess,
  onError,
}: ErrorReportContentProps) {
  const [description, setDescription] = useState("")
  const [severity, setSeverity] = useState<Severity>("medium")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})

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

    if (description.trim().length < 10) {
      newErrors.description = "Description must be at least 10 characters"
    }

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

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

    setIsSubmitting(true)

    const data: ErrorReportData = {
      description: description.trim(),
      severity,
      errorDetails,
      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 report")
    } finally {
      setIsSubmitting(false)
    }
  }

  const isValid = description.trim().length >= 10

  return (
    <div className="flex flex-col gap-4">
      {/* Description textarea */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="error-description" className="text-sm text-foreground">
          What happened?
        </Label>
        <Textarea
          id="error-description"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Describe what you were doing when the error occurred..."
          rows={4}
          className={cn("resize-y min-h-24 max-h-48", errors.description && "border-destructive")}
        />
        {errors.description && (
          <p className="text-xs text-destructive">{errors.description}</p>
        )}
      </div>

      {/* Severity dropdown */}
      {showSeverity && (
        <div className="flex flex-col gap-1">
          <Label htmlFor="error-severity" className="text-sm text-foreground">
            Severity
          </Label>
          <Select value={severity} onValueChange={(val) => setSeverity(val as Severity)}>
            <SelectTrigger className="w-full">
              <SelectValue>
                {(() => {
                  const selected = severityOptions.find(o => o.value === severity)
                  return selected ? (
                    <Badge variant={selected.variant}>{selected.label}</Badge>
                  ) : null
                })()}
              </SelectValue>
            </SelectTrigger>
            <SelectContent side="top">
              {severityOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  <Badge variant={option.variant}>{option.label}</Badge>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Error details (read-only) */}
      {errorDetails && (errorDetails.message || errorDetails.stack || errorDetails.code) && (
        <div className="flex flex-col gap-1">
          <Label className="text-sm text-foreground">
            Error Details
          </Label>
          <div className="bg-muted/50 border border-border rounded-[var(--radius-md)] p-3 font-mono text-xs overflow-auto max-h-48">
            {errorDetails.code && (
              <div className="text-muted-foreground mb-1">
                <span className="font-semibold">Code:</span> {errorDetails.code}
              </div>
            )}
            {errorDetails.message && (
              <div className="text-destructive mb-1">
                <span className="font-semibold text-muted-foreground">Message:</span> {errorDetails.message}
              </div>
            )}
            {errorDetails.stack && (
              <pre className="text-muted-foreground whitespace-pre-wrap break-all">
                {errorDetails.stack}
              </pre>
            )}
          </div>
        </div>
      )}

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