"use client"

import { useState } from "react"
import { TopNav } from "@/components/layout/top-nav"
import { BottomNav } from "@/components/layout/bottom-nav"
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 { Switch } from "@/components/ui/switch"
import { Separator } from "@/components/ui/separator"
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"

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 [formData, setFormData] = useState({
    displayName: "Your Name",
    username: "your_username",
    email: "you@example.com",
    bio: "Software developer | Tech enthusiast | Coffee addict",
    notifications: true,
    emailNotifications: false,
    privateAccount: false,
  })

  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 = () => {
    // TODO: Implement save logic
    router.push("/profile")
  }

  const handleLogout = () => {
    // TODO: Implement logout logic
    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)) // Simulate API call

    // Redirect to landing page after deletion
    router.push("/")
  }

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

    // Redirect to landing page after deactivation
    router.push("/")
  }

  return (
    <div className="min-h-screen pb-20 bg-background">
      <TopNav />
      <main className="max-w-2xl mx-auto 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">
                <Avatar className="w-20 h-20">
                  <AvatarImage src="/placeholder.svg?key=093kx" />
                  <AvatarFallback>YN</AvatarFallback>
                </Avatar>
                <Button variant="outline" className="gap-2 bg-transparent">
                  <CameraIcon />
                  Change Photo
                </Button>
              </div>
            </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 })}
                />
              </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 })}
                />
              </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 })}
                />
              </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}
                />
              </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 })}
              />
            </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 })}
              />
            </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 })}
              />
            </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"
                >
                  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">
                  Delete
                </Button>
              </div>
            </div>
          </div>

          <Button onClick={handleSave} className="w-full h-12">
            Save Changes
          </Button>

          <Button
            onClick={handleLogout}
            variant="outline"
            className="w-full h-12 gap-2 text-destructive hover:text-destructive bg-transparent"
          >
            <LogOutIcon />
            Logout
          </Button>
        </div>
      </main>
      <BottomNav />

      <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>
  )
}
