"use client";

import { useState } from "react";

import { useRouter } from "next/navigation";

import { toast } from "sonner";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { ARCHETYPES } from "@/data/archetypes";
import { useAuthStore } from "@/stores/auth-store";

export default function ProfilePage() {
  const router = useRouter();
  const { user, updateUser, logout } = useAuthStore();
  const [firstName, setFirstName] = useState(user?.firstName ?? "");
  const [lastName, setLastName] = useState(user?.lastName ?? "");
  const [email, setEmail] = useState(user?.email ?? "");
  const [isSaving, setIsSaving] = useState(false);

  const archetype = user?.archetypeResult ? ARCHETYPES.find((a) => a.id === user.archetypeResult?.primaryArchetype) : null;

  const handleSave = async () => {
    setIsSaving(true);
    await new Promise((r) => setTimeout(r, 500));
    updateUser({ firstName, lastName, email });
    setIsSaving(false);
    toast.success("Profile updated successfully.");
  };

  const handleDeleteAccount = () => {
    logout();
    if (typeof window !== "undefined") {
      localStorage.clear();
    }
    toast.success("Account deleted. Redirecting...");
    setTimeout(() => router.replace("/"), 1500);
  };

  if (!user) return null;

  return (
    <div className="space-y-6 p-6 max-w-2xl">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Profile</h1>
        <p className="text-sm text-gray-500 mt-1">Manage your personal information and account settings.</p>
      </div>

      <Card className="border-gray-100">
        <CardHeader className="pb-3"><CardTitle className="text-base">Personal Information</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-1.5">
              <Label htmlFor="firstName">First Name</Label>
              <Input id="firstName" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="lastName">Last Name</Label>
              <Input id="lastName" value={lastName} onChange={(e) => setLastName(e.target.value)} />
            </div>
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="email">Email Address</Label>
            <Input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <Button className="bg-teal-600 hover:bg-teal-700 text-white" onClick={handleSave} disabled={isSaving}>
            {isSaving ? "Saving..." : "Save Changes"}
          </Button>
        </CardContent>
      </Card>

      <Card className="border-gray-100">
        <CardHeader className="pb-3"><CardTitle className="text-base">Account Information</CardTitle></CardHeader>
        <CardContent className="space-y-3 text-sm">
          {[
            { label: "Member Since", value: new Date(user.createdAt).toLocaleDateString("en-GB", { year: "numeric", month: "long", day: "numeric" }) },
            { label: "Account Status", value: <span className="capitalize text-green-600 font-medium">{user.status}</span> },
            { label: "Metabolic Archetype", value: archetype ? <span style={{ color: archetype.color }} className="font-medium">{archetype.name}</span> : "Not assessed" },
            { label: "Package", value: user.purchasedPackage ? <span className="capitalize font-medium">{user.purchasedPackage}</span> : "No package purchased" },
          ].map(({ label, value }) => (
            <div key={label} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
              <span className="text-gray-500">{label}</span>
              <span className="text-gray-900">{value}</span>
            </div>
          ))}
        </CardContent>
      </Card>

      <Card className="border-gray-100">
        <CardHeader className="pb-3"><CardTitle className="text-base">Change Password</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-1.5">
            <Label>Current Password</Label>
            <Input type="password" placeholder="Enter current password" />
          </div>
          <div className="space-y-1.5">
            <Label>New Password</Label>
            <Input type="password" placeholder="Min 8 characters" />
          </div>
          <div className="space-y-1.5">
            <Label>Confirm New Password</Label>
            <Input type="password" placeholder="Repeat new password" />
          </div>
          <Button variant="outline" onClick={() => toast.success("Password changed (PoC simulation)")}>
            Update Password
          </Button>
        </CardContent>
      </Card>

      <Separator />

      <div className="rounded-xl border border-red-100 bg-red-50 p-5">
        <h3 className="font-semibold text-red-900">Danger Zone</h3>
        <p className="text-sm text-red-600 mt-1 mb-4">Permanently delete your account and all associated data. This cannot be undone.</p>
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <Button variant="outline" className="border-red-200 text-red-700 hover:bg-red-100">
              Delete Account
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
              <AlertDialogDescription>
                This will permanently delete your account, all reports, and assessment data. This action cannot be undone.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction className="bg-red-600 hover:bg-red-700 text-white" onClick={handleDeleteAccount}>
                Delete My Account
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </div>
  );
}
