"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"
import { MessageSquare, Mail, Loader2, CheckCircle, AlertCircle, User } from "lucide-react"
import { toast } from "sonner"

interface SupportFeedbackSettingsProps {
  user: any
}

export function SupportFeedbackSettings({ user }: SupportFeedbackSettingsProps) {
  const [feedback, setFeedback] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitStatus, setSubmitStatus] = useState<"idle" | "success" | "error">("idle")

  const handleSubmitFeedback = async () => {
    // Validation
    if (!feedback.trim()) {
      toast.error("Please enter your feedback before submitting")
      return
    }

    if (!user) {
      toast.error("User information not available. Please log in again.")
      return
    }

    setIsSubmitting(true)
    setSubmitStatus("idle")

    try {
      const response = await fetch("/api/feedback", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          feedback: feedback.trim(),
          userEmail: user.email || "Unknown Email",
          userName: user.name || "Unknown User",
          userId: user.id || null,
        }),
      })

      if (response.ok) {
        const result = await response.json()
        setSubmitStatus("success")
        setFeedback("")
        toast.success("Thank you! Your feedback has been sent successfully to G7 Aerospace team.")
        console.log("Feedback sent successfully:", result.messageId)
      } else {
        const errorData = await response.json()
        throw new Error(errorData.error || "Failed to send feedback")
      }
    } catch (error) {
      console.error("Error sending feedback:", error)
      setSubmitStatus("error")
      toast.error("Failed to send feedback. Please try again or contact support directly.")
    } finally {
      setIsSubmitting(false)
      // Reset status after 3 seconds
      setTimeout(() => setSubmitStatus("idle"), 3000)
    }
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5" />
            Send Feedback
          </CardTitle>
          <CardDescription>
            Help us improve G7 Astrum with your feedback. Your message will be sent directly to our development team.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* User Information Display */}
          {user && (
            <div className="bg-gray-50 dark:bg-gray-900/20 border rounded-lg p-3">
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <User className="h-4 w-4" />
                <span>Feedback will be sent from:</span>
              </div>
              <div className="mt-1 text-sm">
                <div className="font-medium">{user.name || "Unknown User"}</div>
                <div className="text-muted-foreground">{user.email || "Unknown Email"}</div>
              </div>
            </div>
          )}

          {/* Feedback Content */}
          <div className="space-y-2">
            <Label htmlFor="feedback">Your Feedback</Label>
            <Textarea
              id="feedback"
              value={feedback}
              onChange={(e) => setFeedback(e.target.value)}
              className="resize-none max-h-48 whitespace-pre-wrap overflow-y-auto break-words" 
              placeholder="Tell us what you think about G7 Astrum, report bugs, suggest features, or share your experience..."
              rows={4}
              disabled={isSubmitting}
              maxLength={1000}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault()
                }
              }}
            />
            <div className="text-xs text-muted-foreground">
              {feedback.length}/1000 characters
            </div>
          </div>
          
          {/* Submit Button with Status */}
          <div className="flex items-center gap-3">
            <Button 
              onClick={handleSubmitFeedback}
              disabled={isSubmitting || !feedback.trim() || !user}
              className="cursor-pointer"
              size="default"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Sending...
                </>
              ) : (
                <>
                  <MessageSquare className="h-4 w-4 mr-2" />
                  Send Feedback
                </>
              )}
            </Button>
            
            {/* Status Indicators */}
            {submitStatus === "success" && (
              <div className="flex items-center gap-2 text-green-600 animate-in fade-in duration-300">
                <CheckCircle className="h-4 w-4" />
                <span className="text-sm font-medium">Sent successfully!</span>
              </div>
            )}
            
            {submitStatus === "error" && (
              <div className="flex items-center gap-2 text-red-600 animate-in fade-in duration-300">
                <AlertCircle className="h-4 w-4" />
                <span className="text-sm font-medium">Failed to send</span>
              </div>
            )}
          </div>

          {/* Info Box */}
          <div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
            <div className="flex items-start gap-2">
              <Mail className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
              <div className="text-sm text-blue-800 dark:text-blue-200">
                <p className="font-medium">Your feedback will be sent to:</p>
                <p className="text-blue-600 dark:text-blue-300">rahmang7aero@gmail.com</p>
                <p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
                  We typically respond within 24 hours during business days.
                </p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Contact Support Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-5 w-5" />
            Contact Support
          </CardTitle>
          <CardDescription>Get help with your account or technical issues</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4 flex gap-2">
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" className="cursor-pointer">
                <Mail className="h-4 w-4 mr-2" />
                Contact Support
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-80 ml-44 flex flex-col items-start justify-center space-y-2">
              <div className="space-y-1">
                <div className="font-medium">Support Contact</div>
                <div className="text-sm text-muted-foreground">
                  <strong>Email:</strong> rahmang7aero@gmail.com
                </div>
                <div className="text-sm text-muted-foreground">
                  <strong>Response Time:</strong> Within 24 hours
                </div>
              </div>
            </PopoverContent>
          </Popover>
        </CardContent>
      </Card>
    </div>
  )
}
