"use client";

import { useState, useEffect } from "react";
import { useTheme } from "next-themes";
import { useAuth } from "@/lib/auth-context";
import api from "@/lib/api";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import {
  Bell,
  KeyRound,
  Monitor,
  Moon,
  Palette,
  Save,
  Shield,
  Sun,
  User,
} from "lucide-react";
import { TwoFactorSettings } from "@/components/two-factor-settings";

const sections = [
  { id: "profile", label: "Profile", icon: User },
  { id: "security", label: "Security", icon: Shield },
  { id: "password", label: "Password", icon: KeyRound },
  { id: "appearance", label: "Appearance", icon: Palette },
  { id: "notifications", label: "Notifications", icon: Bell },
] as const;

type Section = (typeof sections)[number]["id"];

export default function SettingsPage() {
  const { user, refreshUser } = useAuth();
  const { theme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [activeSection, setActiveSection] = useState<Section>("profile");
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState("");
  const [error, setError] = useState("");

  const [form, setForm] = useState({
    name: user?.name || "",
    email: user?.email || "",
    phone: user?.phone || "",
    country_of_residence: user?.country_of_residence || "",
    city: user?.city || "",
    nationality: user?.nationality || "",
  });

  const [passwordForm, setPasswordForm] = useState({
    current_password: "",
    password: "",
    password_confirmation: "",
  });

  const [notifications, setNotifications] = useState({
    email_marketing: true,
    email_updates: true,
    push_notifications: false,
  });

  useEffect(() => {
    setMounted(true);
    const saved = localStorage.getItem("notification_preferences");
    if (saved) {
      try {
        setNotifications(JSON.parse(saved));
      } catch {
        // ignore invalid JSON
      }
    }
  }, []);

  if (!user) return null;

  const initials = user.name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);

  const clearMessages = () => {
    setError("");
    setSuccess("");
  };

  const handleProfileUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    clearMessages();

    try {
      await api.put("/api/user", form);
      await refreshUser();
      setSuccess("Profile updated successfully.");
    } catch (err: unknown) {
      const error = err as { response?: { data?: { message?: string } } };
      setError(error.response?.data?.message || "Failed to update profile.");
    } finally {
      setIsLoading(false);
    }
  };

  const handlePasswordUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    clearMessages();

    try {
      await api.put("/api/user", passwordForm);
      setSuccess("Password updated successfully.");
      setPasswordForm({
        current_password: "",
        password: "",
        password_confirmation: "",
      });
    } catch (err: unknown) {
      const error = err as { response?: { data?: { message?: string } } };
      setError(error.response?.data?.message || "Failed to update password.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleThemeChange = (newTheme: string) => {
    setTheme(newTheme);
    setSuccess("Appearance updated.");
  };

  const handleNotificationChange = (key: keyof typeof notifications, checked: boolean) => {
    const updated = { ...notifications, [key]: checked };
    setNotifications(updated);
    localStorage.setItem("notification_preferences", JSON.stringify(updated));
    setSuccess("Notification preferences saved.");
  };

  return (
    <div className="space-y-4 sm:space-y-6">
      <div>
        <h1 className="font-display text-xl font-semibold text-foreground sm:text-2xl">
          Settings
        </h1>
        <p className="text-xs text-muted-foreground sm:text-sm">
          Manage your profile and account preferences.
        </p>
      </div>

      {success && (
        <div className="rounded-md border border-green-200 bg-green-50 p-3 text-sm text-green-800 dark:border-green-800 dark:bg-green-950 dark:text-green-200">
          {success}
        </div>
      )}

      {error && (
        <div className="rounded-md border border-destructive/20 bg-destructive/10 p-3 text-sm text-destructive">
          {error}
        </div>
      )}

      <div className="flex flex-col gap-6 lg:flex-row">
        {/* Sidebar Navigation */}
        <nav className="w-full shrink-0 lg:w-56">
          <Card>
            <CardContent className="p-2">
              <ul className="space-y-1">
                {sections.map((section) => {
                  const Icon = section.icon;
                  return (
                    <li key={section.id}>
                      <button
                        onClick={() => {
                          setActiveSection(section.id);
                          clearMessages();
                        }}
                        className={cn(
                          "flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
                          activeSection === section.id
                            ? "bg-primary/10 text-primary"
                            : "text-muted-foreground hover:bg-muted hover:text-foreground"
                        )}
                      >
                        <Icon className="h-4 w-4" />
                        {section.label}
                      </button>
                    </li>
                  );
                })}
              </ul>
            </CardContent>
          </Card>
        </nav>

        {/* Content Area */}
        <div className="flex-1">
          {/* Profile Section */}
          {activeSection === "profile" && (
            <Card>
              <CardHeader>
                <CardTitle>Profile Information</CardTitle>
                <CardDescription>
                  Update your personal information and public profile.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="mb-6 flex items-center gap-4">
                  <Avatar className="h-16 w-16">
                    <AvatarImage src={user.avatar || undefined} />
                    <AvatarFallback className="bg-primary/10 text-lg font-medium text-primary">
                      {initials}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <p className="font-medium">{user.name}</p>
                    <p className="text-sm text-muted-foreground">{user.email}</p>
                    <p className="mt-1 text-xs text-muted-foreground capitalize">
                      Role: {user.roles?.[0] ? (typeof user.roles[0] === 'string' ? user.roles[0] : user.roles[0].name) : 'N/A'}
                    </p>
                  </div>
                </div>

                <Separator className="mb-6" />

                <form onSubmit={handleProfileUpdate} className="space-y-4">
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="name">Full Name</Label>
                      <Input
                        id="name"
                        value={form.name}
                        onChange={(e) => setForm({ ...form, name: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="email">Email</Label>
                      <Input
                        id="email"
                        type="email"
                        value={form.email}
                        onChange={(e) => setForm({ ...form, email: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="phone">Phone</Label>
                      <Input
                        id="phone"
                        value={form.phone}
                        onChange={(e) => setForm({ ...form, phone: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="nationality">Nationality</Label>
                      <Input
                        id="nationality"
                        value={form.nationality}
                        onChange={(e) => setForm({ ...form, nationality: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="country">Country of Residence</Label>
                      <Input
                        id="country"
                        value={form.country_of_residence}
                        onChange={(e) =>
                          setForm({ ...form, country_of_residence: e.target.value })
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="city">City</Label>
                      <Input
                        id="city"
                        value={form.city}
                        onChange={(e) => setForm({ ...form, city: e.target.value })}
                      />
                    </div>
                  </div>
                  <Button type="submit" disabled={isLoading}>
                    <Save className="mr-2 h-4 w-4" />
                    {isLoading ? "Saving..." : "Save Changes"}
                  </Button>
                </form>
              </CardContent>
            </Card>
          )}

          {/* Security (2FA) Section */}
          {activeSection === "security" && <TwoFactorSettings />}

          {/* Password Section */}
          {activeSection === "password" && (
            <Card>
              <CardHeader>
                <CardTitle>Change Password</CardTitle>
                <CardDescription>
                  Update your password to keep your account secure.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <form onSubmit={handlePasswordUpdate} className="space-y-4">
                  <div className="space-y-4 max-w-md">
                    <div className="space-y-2">
                      <Label htmlFor="current_password">Current Password</Label>
                      <Input
                        id="current_password"
                        type="password"
                        value={passwordForm.current_password}
                        onChange={(e) =>
                          setPasswordForm({ ...passwordForm, current_password: e.target.value })
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="password">New Password</Label>
                      <Input
                        id="password"
                        type="password"
                        value={passwordForm.password}
                        onChange={(e) =>
                          setPasswordForm({ ...passwordForm, password: e.target.value })
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="password_confirmation">Confirm New Password</Label>
                      <Input
                        id="password_confirmation"
                        type="password"
                        value={passwordForm.password_confirmation}
                        onChange={(e) =>
                          setPasswordForm({
                            ...passwordForm,
                            password_confirmation: e.target.value,
                          })
                        }
                      />
                    </div>
                  </div>
                  <Button type="submit" disabled={isLoading}>
                    <KeyRound className="mr-2 h-4 w-4" />
                    {isLoading ? "Updating..." : "Update Password"}
                  </Button>
                </form>
              </CardContent>
            </Card>
          )}

          {/* Appearance Section */}
          {activeSection === "appearance" && (
            <Card>
              <CardHeader>
                <CardTitle>Appearance</CardTitle>
                <CardDescription>
                  Customize how the dashboard looks and feels.
                </CardDescription>
              </CardHeader>
              <CardContent>
                {!mounted ? (
                  <div className="h-24 animate-pulse rounded-lg bg-muted" />
                ) : (
                  <div className="space-y-4">
                    <Label>Theme</Label>
                    <div className="inline-grid grid-cols-3 gap-2">
                      <button
                        onClick={() => handleThemeChange("light")}
                        className={cn(
                          "flex flex-col items-center gap-1.5 rounded-lg border-2 px-4 py-3 transition-colors",
                          theme === "light"
                            ? "border-primary bg-primary/5"
                            : "border-muted hover:border-muted-foreground/30"
                        )}
                      >
                        <Sun className="h-5 w-5" />
                        <span className="text-sm font-medium">Light</span>
                      </button>
                      <button
                        onClick={() => handleThemeChange("dark")}
                        className={cn(
                          "flex flex-col items-center gap-1.5 rounded-lg border-2 px-4 py-3 transition-colors",
                          theme === "dark"
                            ? "border-primary bg-primary/5"
                            : "border-muted hover:border-muted-foreground/30"
                        )}
                      >
                        <Moon className="h-5 w-5" />
                        <span className="text-sm font-medium">Dark</span>
                      </button>
                      <button
                        onClick={() => handleThemeChange("system")}
                        className={cn(
                          "flex flex-col items-center gap-1.5 rounded-lg border-2 px-4 py-3 transition-colors",
                          theme === "system"
                            ? "border-primary bg-primary/5"
                            : "border-muted hover:border-muted-foreground/30"
                        )}
                      >
                        <Monitor className="h-6 w-6" />
                        <span className="text-sm font-medium">System</span>
                      </button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Notifications Section */}
          {activeSection === "notifications" && (
            <Card>
              <CardHeader>
                <CardTitle>Notifications</CardTitle>
                <CardDescription>
                  Choose how you want to be notified.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <NotificationToggle
                    label="Marketing emails"
                    description="Receive emails about new features and promotions."
                    checked={notifications.email_marketing}
                    onChange={(checked) =>
                      handleNotificationChange("email_marketing", checked)
                    }
                  />
                  <Separator />
                  <NotificationToggle
                    label="Product updates"
                    description="Receive emails about product updates and changes."
                    checked={notifications.email_updates}
                    onChange={(checked) =>
                      handleNotificationChange("email_updates", checked)
                    }
                  />
                  <Separator />
                  <NotificationToggle
                    label="Push notifications"
                    description="Receive push notifications in your browser."
                    checked={notifications.push_notifications}
                    onChange={(checked) =>
                      handleNotificationChange("push_notifications", checked)
                    }
                  />
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

function NotificationToggle({
  label,
  description,
  checked,
  onChange,
}: {
  label: string;
  description: string;
  checked: boolean;
  onChange: (checked: boolean) => void;
}) {
  return (
    <div className="flex items-center justify-between">
      <div className="space-y-0.5">
        <p className="text-sm font-medium">{label}</p>
        <p className="text-xs text-muted-foreground">{description}</p>
      </div>
      <button
        type="button"
        role="switch"
        aria-checked={checked}
        onClick={() => onChange(!checked)}
        className={cn(
          "relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors",
          checked ? "bg-primary" : "bg-muted"
        )}
      >
        <span
          className={cn(
            "pointer-events-none block h-4 w-4 rounded-full bg-white shadow-sm transition-transform",
            checked ? "translate-x-4" : "translate-x-0"
          )}
        />
      </button>
    </div>
  );
}
