"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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@mdxui/primitives/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@mdxui/primitives/tabs"
import { useState } from "react"
import type {
  MessageType,
  ReportIssueData,
  ReportIssueUser,
  ReportIssueSeverity,
  SeverityOption,
} from "./types"

const DEFAULT_TOPICS = [
  "API",
  "Webhooks",
  "Events & Logs",
  "Account & Billing",
  "Other",
]

const DEFAULT_SEVERITY_OPTIONS: SeverityOption[] = [
  { value: "critical", label: "Critical — Service down or data loss" },
  { value: "high", label: "High — Feature broken, no workaround" },
  { value: "medium", label: "Medium — Feature impaired, workaround exists" },
  { value: "low", label: "Low — Minor issue or cosmetic" },
  { value: "question-feature-req", label: "Question / Feature Request — No impact" },
]

const TAB_CONFIG: Record<
  MessageType,
  { label: string; placeholder: string }
> = {
  question: {
    label: "What can we help you with?",
    placeholder: "Describe your question...",
  },
  feedback: {
    label: "What feedback do you have?",
    placeholder: "Share your thoughts, suggestions...",
  },
  bug: {
    label: "What's the bug?",
    placeholder: "Describe the bug or paste error details...",
  },
}

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

interface ReportIssueContentProps {
  defaultTab?: MessageType
  defaultValues?: {
    message?: string
    topic?: string
    severity?: ReportIssueSeverity
  }
  topics?: string[]
  severityOptions?: SeverityOption[]
  user?: ReportIssueUser
  context?: Record<string, unknown>
  captureMetadata?: boolean
  onSubmit?: (data: ReportIssueData) => Promise<void> | void
  apiEndpoint?: string
  apiHeaders?: Record<string, string>
  submitLabel?: string
  onSuccess: () => void
  onError: (error: string) => void
  onTabChange?: (tab: MessageType) => void
}

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

export function ReportIssueContent({
  defaultTab = "question",
  defaultValues,
  topics = DEFAULT_TOPICS,
  severityOptions = DEFAULT_SEVERITY_OPTIONS,
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  apiHeaders,
  submitLabel = "Submit",
  onSuccess,
  onError,
  onTabChange,
}: ReportIssueContentProps) {
  const [name, setName] = useState(user?.name ?? "")
  const [email, setEmail] = useState(user?.email ?? "")
  const [messageType, setMessageType] = useState<MessageType>(defaultTab)
  const [topic, setTopic] = useState(defaultValues?.topic ?? "")
  const [message, setMessage] = useState(defaultValues?.message ?? "")
  const [severity, setSeverity] = useState<ReportIssueSeverity>(
    defaultValues?.severity ?? "medium"
  )
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})

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

    if (name.trim().length < 2) {
      newErrors.name = "Name must be at least 2 characters"
    }
    if (!EMAIL_REGEX.test(email.trim())) {
      newErrors.email = "Please enter a valid email"
    }
    if (message.trim().length < 10) {
      newErrors.message = "Message must be at least 10 characters"
    }

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

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

    setIsSubmitting(true)

    const data: ReportIssueData = {
      name: name.trim(),
      email: email.trim(),
      messageType,
      topic: topic || undefined,
      message: message.trim(),
      severity,
      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",
            ...apiHeaders,
          },
          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 =
    name.trim().length >= 2 &&
    EMAIL_REGEX.test(email.trim()) &&
    message.trim().length >= 10

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

  const tabConfig = TAB_CONFIG[messageType]

  return (
    <div className="flex flex-col gap-4">
      {/* Name / Email */}
      <div className="flex flex-col gap-3">
        <div className="flex flex-col gap-1">
          <Label htmlFor="report-name" className="text-sm text-foreground">
            Name
          </Label>
          <Input
            id="report-name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Your name"
            className={cn(errors.name && "border-destructive")}
          />
          {errors.name && (
            <p className="text-xs text-destructive">{errors.name}</p>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <Label htmlFor="report-email" className="text-sm text-foreground">
            Email
          </Label>
          <Input
            id="report-email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@example.com"
            className={cn(errors.email && "border-destructive")}
          />
          {errors.email && (
            <p className="text-xs text-destructive">{errors.email}</p>
          )}
        </div>
      </div>

      {/* Message Type Tabs */}
      <div className="flex flex-col gap-1">
        <Label className="text-sm text-foreground">Message type</Label>
        <Tabs
          value={messageType}
          onValueChange={(value) => {
            const tab = value as MessageType
            setMessageType(tab)
            onTabChange?.(tab)
          }}
        >
          <TabsList className="w-full">
            <TabsTrigger value="question" className="flex-1">
              Question
            </TabsTrigger>
            <TabsTrigger value="feedback" className="flex-1">
              Feedback
            </TabsTrigger>
            <TabsTrigger value="bug" className="flex-1">
              Bug
            </TabsTrigger>
          </TabsList>

          {/* Shared content below tabs — not inside TabsContent so state is preserved */}
          <div className="sr-only">
            <TabsContent value="question" />
            <TabsContent value="feedback" />
            <TabsContent value="bug" />
          </div>
        </Tabs>
      </div>

      {/* Topic */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="report-topic" className="text-sm text-foreground">
          Topic
        </Label>
        <Select value={topic} onValueChange={setTopic}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Select a topic" />
          </SelectTrigger>
          <SelectContent>
            {topics.map((t) => (
              <SelectItem key={t} value={t}>
                {t}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Message textarea — label/placeholder changes per tab */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="report-message" className="text-sm text-foreground">
          {tabConfig.label}
        </Label>
        <Textarea
          id="report-message"
          autoFocus
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder={tabConfig.placeholder}
          rows={4}
          className={cn(
            "[field-sizing:fixed] resize-y min-h-24 h-32 overflow-y-auto break-all",
            errors.message && "border-destructive"
          )}
        />
        {errors.message && (
          <p className="text-xs text-destructive">{errors.message}</p>
        )}
      </div>

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

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