"use client"

import { useState, useEffect, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { ShapedAvatar } from "@/components/ui/shaped-avatar"
import { ShapeSelector } from "@/components/ui/shape-selector"
import { Switch } from "@/components/ui/switch"
import { Separator } from "@/components/ui/separator"
import { PREDEFINED_SHAPES, ProfileShape, ProfileState, saveProfileState, loadProfileState } from "@/lib/profile-shapes"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { TemplateSwitcher } from "@/components/template-switcher"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { getMyProfile, updateProfile, updateSettings } from "@/actions/profile-actions"
import { logout } from "@/actions/auth-actions"
import { useUserStore } from "@/lib/store"
import { Loader2, AlertCircle, CheckCircle2 } from "lucide-react"
import { useToast } from "@/hooks/use-toast"

const ArrowLeftIcon = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="20"
    height="20"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="m12 19-7-7 7-7" />
    <path d="M19 12H5" />
  </svg>
)

const CameraIcon = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z" />
    <circle cx="12" cy="13" r="3" />
  </svg>
)

const LogOutIcon = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
    <polyline points="16 17 21 12 16 7" />
    <line x1="21" y1="12" x2="9" y2="12" />
  </svg>
)

const AlertTriangleIcon = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="48"
    height="48"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" />
    <path d="M12 9v4" />
    <path d="M12 17h.01" />
  </svg>
)

const PauseCircleIcon = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="48"
    height="48"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <circle cx="12" cy="12" r="10" />
    <line x1="10" y1="15" x2="10" y2="9" />
    <line x1="14" y1="15" x2="14" y2="9" />
  </svg>
)

export default function SettingsPage() {
  const router = useRouter()
  const { toast } = useToast()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const { user, setUser, updateUser: updateUserStore } = useUserStore()
  
  const [formData, setFormData] = useState({
    displayName: "",
    username: "",
    email: "",
    bio: "",
    notifications: true,
    emailNotifications: false,
    privateAccount: false,
  })
  
  // Profile picture and shape state
  const [profilePicUrl, setProfilePicUrl] = useState<string | undefined>()
  const [profileShape, setProfileShape] = useState<ProfileShape>(PREDEFINED_SHAPES[0])
  const [uploadedFile, setUploadedFile] = useState<File | null>(null)
  
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  
  // Load saved profile state on component mount
  useEffect(() => {
    const savedState = loadProfileState()
    if (savedState) {
      if (savedState.profilePicUrl) {
        setProfilePicUrl(savedState.profilePicUrl)
      }
      if (savedState.profileShape) {
        setProfileShape(savedState.profileShape)
      }
    }
  }, [])

  // Load profile data from backend
  useEffect(() => {
    const fetchProfile = async () => {
      setIsLoading(true)
      try {
        const result = await getMyProfile()

        if (result.success && result.profile) {
          const profile = result.profile
          setFormData({
            displayName: profile.name || "",
            username: profile.username || "",
            email: profile.email || "",
            bio: profile.bio || "",
            notifications: true,
            emailNotifications: false,
            privateAccount: false,
          })

          if (profile.image) {
            setProfilePicUrl(profile.image)
          }
        } else {
          // Check if error is related to invalid token
          const errorMsg = result.error || ""
          
          if (errorMsg.includes("token") || errorMsg.includes("authenticated") || errorMsg.includes("auth")) {
            // Invalid token - logout and redirect
            await logout()
            router.push("/login")
            return
          }
          
          toast({
            variant: "destructive",
            title: "Error",
            description: errorMsg || "Failed to load profile data",
          })
        }
      } catch (error) {
        toast({
          variant: "destructive",
          title: "Error",
          description: "Failed to load profile data",
        })
      } finally {
        setIsLoading(false)
      }
    }

    fetchProfile()
  }, [toast, router])

  const [showDeleteWarning, setShowDeleteWarning] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [showDeactivateModal, setShowDeactivateModal] = useState(false)
  const [deleteConfirmText, setDeleteConfirmText] = useState("")
  const [isDeleting, setIsDeleting] = useState(false)
  const [isDeactivating, setIsDeactivating] = useState(false)

  const handleSave = async () => {
    setIsSaving(true)
    
    try {
      // Save profile state to localStorage for shape
      const profileState: ProfileState = {
        profilePicUrl,
        profileShape
      }
      saveProfileState(profileState)
      
      // Prepare form data for backend
      const formDataToSend = new FormData()
      formDataToSend.append("name", formData.displayName)
      formDataToSend.append("username", formData.username)
      formDataToSend.append("bio", formData.bio)
      
      // Add image if uploaded
      if (uploadedFile) {
        formDataToSend.append("image", uploadedFile)
      }
      
      // Update profile on backend
      const result = await updateProfile(formDataToSend)
      
      if (result.success) {
        if (result.profile) {
          updateUserStore(result.profile)
        }
        
        // Save settings separately
        const settingsResult = await updateSettings({
          notifications: formData.notifications,
          emailNotifications: formData.emailNotifications,
          privateAccount: formData.privateAccount,
        })
        
        toast({
          title: "Success",
          description: "Profile updated successfully",
        })
        
        router.push("/profile")
      } else {
        toast({
          variant: "destructive",
          title: "Error",
          description: result.error || "Failed to update profile",
        })
      }
    } catch (error) {
      toast({
        variant: "destructive",
        title: "Error",
        description: "An unexpected error occurred",
      })
    } finally {
      setIsSaving(false)
    }
  }
  
  // Handle profile picture upload
  const handlePhotoUpload = () => {
    fileInputRef.current?.click()
  }
  
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      // Store the file for upload
      setUploadedFile(file)
      
      // Use URL.createObjectURL for preview
      const imageUrl = URL.createObjectURL(file)
      setProfilePicUrl(imageUrl)
    }
  }

  const handleLogout = async () => {
    await logout()
    router.push("/login")
  }

  const handleDeleteAccount = () => {
    setShowDeleteWarning(false)
    setShowDeleteConfirm(true)
  }

  const handleFinalDelete = async () => {
    if (deleteConfirmText.toLowerCase() !== "delete") return

    setIsDeleting(true)
    // TODO: Implement actual deletion API call
    await new Promise((resolve) => setTimeout(resolve, 2000))

    router.push("/")
  }

  const handleDeactivateAccount = async () => {
    setIsDeactivating(true)
    // TODO: Implement actual deactivation API call
    await new Promise((resolve) => setTimeout(resolve, 2000))

    router.push("/")
  }

  if (isLoading) {
    return (
      <div className="p-2 sm:p-4 flex items-center justify-center min-h-screen">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-primary" />
          <p className="text-muted-foreground">Loading settings...</p>
        </div>
      </div>
    )
  }

  // Get initials for avatar fallback
  const initials = formData.displayName
    ? formData.displayName.split(' ').map(n => n[0]).join('').toUpperCase()
    : formData.username?.[0]?.toUpperCase() || '?'

  return (
    <div className="p-2 sm:p-4">
        <div className="flex items-center gap-4 mb-6">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/profile">
              <ArrowLeftIcon />
            </Link>
          </Button>
          <h1 className="text-2xl font-bold">Settings</h1>
        </div>

        <div className="space-y-6">
          <div className="bg-card rounded-xl border border-border p-6 space-y-6">
            <div>
              <h2 className="text-lg font-semibold mb-4">Profile Picture</h2>
              <div className="flex items-center gap-4">
                <ShapedAvatar 
                  src={profilePicUrl || "/placeholder.svg?key=093kx"}
                  fallback={<span className="text-xl font-medium">{initials}</span>}
                  className="w-20 h-20"
                  shape={profileShape}
                />
                <div className="flex flex-col gap-2">
                  <Button 
                    variant="outline" 
                    className="gap-2 bg-transparent"
                    onClick={handlePhotoUpload}
                    disabled={isSaving}
                  >
                    <CameraIcon />
                    Change Photo
                  </Button>
                  {profilePicUrl && (
                    <Button 
                      variant="ghost" 
                      size="sm"
                      onClick={() => {
                        setProfilePicUrl(undefined)
                        setUploadedFile(null)
                      }}
                      disabled={isSaving}
                      className="text-xs text-muted-foreground h-auto p-1"
                    >
                      Remove Photo
                    </Button>
                  )}
                </div>
              </div>
              
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleFileChange}
                className="hidden"
              />
            </div>
            
            <Separator />
            
            <div>
              <ShapeSelector 
                selectedShape={profileShape}
                onShapeChange={setProfileShape}
              />
            </div>

            <Separator />

            <div className="space-y-4">
              <h2 className="text-lg font-semibold">Account Information</h2>

              <div className="space-y-2">
                <Label htmlFor="displayName">Display Name</Label>
                <Input
                  id="displayName"
                  value={formData.displayName}
                  onChange={(e) => setFormData({ ...formData, displayName: e.target.value })}
                  disabled={isSaving}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="username">Username</Label>
                <Input
                  id="username"
                  value={formData.username}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  disabled={isSaving}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  disabled={true}
                  className="bg-muted"
                />
                <p className="text-xs text-muted-foreground">Email cannot be changed</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="bio">Bio</Label>
                <Textarea
                  id="bio"
                  value={formData.bio}
                  onChange={(e) => setFormData({ ...formData, bio: e.target.value })}
                  rows={3}
                  disabled={isSaving}
                />
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl border border-border p-6 space-y-4">
            <TemplateSwitcher />
          </div>

          <div className="bg-card rounded-xl border border-border p-6 space-y-4">
            <h2 className="text-lg font-semibold">Privacy & Notifications</h2>

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Push Notifications</Label>
                <p className="text-sm text-muted-foreground">Receive push notifications</p>
              </div>
              <Switch
                checked={formData.notifications}
                onCheckedChange={(checked) => setFormData({ ...formData, notifications: checked })}
                disabled={isSaving}
              />
            </div>

            <Separator />

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Email Notifications</Label>
                <p className="text-sm text-muted-foreground">Receive email updates</p>
              </div>
              <Switch
                checked={formData.emailNotifications}
                onCheckedChange={(checked) => setFormData({ ...formData, emailNotifications: checked })}
                disabled={isSaving}
              />
            </div>

            <Separator />

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Private Account</Label>
                <p className="text-sm text-muted-foreground">Only followers can see your posts</p>
              </div>
              <Switch
                checked={formData.privateAccount}
                onCheckedChange={(checked) => setFormData({ ...formData, privateAccount: checked })}
                disabled={isSaving}
              />
            </div>
          </div>

          <div className="bg-card rounded-xl border border-destructive/50 p-6 space-y-4">
            <h2 className="text-lg font-semibold text-destructive">Danger Zone</h2>
            <p className="text-sm text-muted-foreground">
              Irreversible actions that will affect your account and data.
            </p>

            <Separator />

            <div className="space-y-3">
              <div className="flex items-start justify-between gap-4">
                <div className="space-y-1 flex-1">
                  <Label className="text-base">Deactivate Account</Label>
                  <p className="text-sm text-muted-foreground">
                    Temporarily hide your profile and posts. Your data will be retained and you can reactivate anytime.
                  </p>
                </div>
                <Button
                  variant="outline"
                  onClick={() => setShowDeactivateModal(true)}
                  className="shrink-0 bg-transparent border-orange-500 text-orange-500 hover:bg-orange-500 hover:text-white"
                  disabled={isSaving}
                >
                  Deactivate
                </Button>
              </div>

              <Separator />

              <div className="flex items-start justify-between gap-4">
                <div className="space-y-1 flex-1">
                  <Label className="text-base text-destructive">Delete Account</Label>
                  <p className="text-sm text-muted-foreground">
                    Permanently delete your account and all your data. This action cannot be undone.
                  </p>
                </div>
                <Button 
                  variant="destructive" 
                  onClick={() => setShowDeleteWarning(true)} 
                  className="shrink-0"
                  disabled={isSaving}
                >
                  Delete
                </Button>
              </div>
            </div>
          </div>

          <Button 
            onClick={handleSave} 
            className="w-full h-12"
            disabled={isSaving}
          >
            {isSaving ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
                Saving...
              </>
            ) : (
              "Save Changes"
            )}
          </Button>

          <Button
            onClick={handleLogout}
            variant="outline"
            className="w-full h-12 gap-2 text-destructive hover:text-destructive bg-transparent"
            disabled={isSaving}
          >
            <LogOutIcon />
            Logout
          </Button>
        </div>
      <Dialog open={showDeleteWarning} onOpenChange={setShowDeleteWarning}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <div className="flex justify-center mb-4">
              <div className="text-destructive">
                <AlertTriangleIcon />
              </div>
            </div>
            <DialogTitle className="text-center text-xl">Delete Your Account?</DialogTitle>
            <DialogDescription className="text-center space-y-3 pt-2">
              <p className="text-base font-medium text-foreground">
                This will permanently delete your account and all your data.
              </p>
              <div className="text-left space-y-2 bg-muted/50 rounded-lg p-4">
                <p className="text-sm font-semibold text-foreground">What will be deleted:</p>
                <ul className="text-sm space-y-1 list-disc list-inside text-muted-foreground">
                  <li>All your posts and replies</li>
                  <li>All Frindle connections</li>
                  <li>Your profile and personal data</li>
                  <li>All media and content</li>
                </ul>
              </div>
              <p className="text-sm text-destructive font-medium">This action cannot be undone!</p>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col sm:flex-col gap-2">
            <Button variant="outline" onClick={() => setShowDeleteWarning(false)} className="w-full bg-transparent">
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDeleteAccount} className="w-full">
              Continue to Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-center text-xl">Final Confirmation</DialogTitle>
            <DialogDescription className="text-center space-y-4 pt-2">
              <p className="text-base text-foreground">
                Are you absolutely sure? This action is permanent and cannot be reversed.
              </p>
              <div className="space-y-2">
                <Label htmlFor="confirm-delete" className="text-left block">
                  Type <span className="font-bold text-foreground">DELETE</span> to confirm:
                </Label>
                <Input
                  id="confirm-delete"
                  value={deleteConfirmText}
                  onChange={(e) => setDeleteConfirmText(e.target.value)}
                  placeholder="Type DELETE"
                  className="text-center uppercase"
                />
              </div>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col sm:flex-col gap-2">
            <Button
              variant="outline"
              onClick={() => {
                setShowDeleteConfirm(false)
                setDeleteConfirmText("")
              }}
              disabled={isDeleting}
              className="w-full bg-transparent"
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleFinalDelete}
              disabled={deleteConfirmText.toLowerCase() !== "delete" || isDeleting}
              className="w-full"
            >
              {isDeleting ? "Deleting..." : "Delete My Account Forever"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showDeactivateModal} onOpenChange={setShowDeactivateModal}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <div className="flex justify-center mb-4">
              <div className="text-orange-500">
                <PauseCircleIcon />
              </div>
            </div>
            <DialogTitle className="text-center text-xl">Deactivate Your Account?</DialogTitle>
            <DialogDescription className="text-center space-y-3 pt-2">
              <p className="text-base text-foreground">Your account will be temporarily hidden from MyPowerPost.</p>
              <div className="text-left space-y-2 bg-muted/50 rounded-lg p-4">
                <p className="text-sm font-semibold text-foreground">What happens:</p>
                <ul className="text-sm space-y-1 list-disc list-inside text-muted-foreground">
                  <li>Your profile will be hidden</li>
                  <li>Your posts won't be visible</li>
                  <li>Frindle connections will be paused</li>
                  <li>All data will be retained</li>
                </ul>
              </div>
              <p className="text-sm text-orange-600 font-medium">
                You can reactivate your account anytime by logging back in.
              </p>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col sm:flex-col gap-2">
            <Button
              variant="outline"
              onClick={() => setShowDeactivateModal(false)}
              disabled={isDeactivating}
              className="w-full bg-transparent"
            >
              Cancel
            </Button>
            <Button
              onClick={handleDeactivateAccount}
              disabled={isDeactivating}
              className="w-full bg-orange-500 hover:bg-orange-600"
            >
              {isDeactivating ? "Deactivating..." : "Deactivate Account"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
