'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { toast } from '@/hooks/use-toast';
import { api } from '@/lib/store/api';
import { apiCall, apiErrorMessage } from '@/lib/store/api-call';
import { AppSpinner } from '@/components/ui/app-loader';
import {
  Settings,
  User,
  Shield,
  Database,
  Save,
  Key,
  Eye,
  EyeOff,
  AlertTriangle,
} from 'lucide-react';

export default function SettingsPage() {
  const { data: session, status, update } = useSession();

  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [savingProfile, setSavingProfile] = useState(false);

  const [passwordOpen, setPasswordOpen] = useState(false);
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [savingPassword, setSavingPassword] = useState(false);

  useEffect(() => {
    if (!session?.user) return;
    setName(session.user.name || '');
    setEmail(session.user.email || '');
  }, [session?.user?.id, session?.user?.name, session?.user?.email]);

  const profileDirty =
    (session?.user?.name || '') !== name.trim() ||
    (session?.user?.email || '') !== email.trim();

  const handleSaveProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session?.user?.id) return;

    const trimmedName = name.trim();
    const trimmedEmail = email.trim();

    if (!trimmedName) {
      toast({
        title: 'Name required',
        description: 'Please enter your full name.',
        variant: 'destructive',
      });
      return;
    }

    if (!trimmedEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedEmail)) {
      toast({
        title: 'Valid email required',
        description: 'Please enter a valid email address.',
        variant: 'destructive',
      });
      return;
    }

    setSavingProfile(true);
    try {
      await apiCall(
        api.endpoints.updateUser.initiate({
          id: session.user.id,
          body: {
            name: trimmedName,
            email: trimmedEmail,
            username: trimmedEmail.split('@')[0],
          },
        }),
      );

      await update({
        user: {
          name: trimmedName,
          email: trimmedEmail,
        },
      });

      toast({
        title: 'Profile updated',
        description: 'Your profile information has been saved.',
      });
    } catch (error) {
      toast({
        title: 'Update failed',
        description: apiErrorMessage(error, 'Could not save profile changes.'),
        variant: 'destructive',
      });
    } finally {
      setSavingProfile(false);
    }
  };

  const resetPasswordForm = () => {
    setNewPassword('');
    setConfirmPassword('');
    setShowPassword(false);
    setShowConfirmPassword(false);
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session?.user?.id) return;

    if (newPassword.length < 8) {
      toast({
        title: 'Invalid password',
        description: 'Password must be at least 8 characters long.',
        variant: 'destructive',
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      toast({
        title: 'Password mismatch',
        description: 'New password and confirmation do not match.',
        variant: 'destructive',
      });
      return;
    }

    setSavingPassword(true);
    try {
      await apiCall(
        api.endpoints.updateUser.initiate({
          id: session.user.id,
          body: { password: newPassword },
        }),
      );

      toast({
        title: 'Password changed',
        description: 'Your password has been updated. Use it next time you sign in.',
      });
      resetPasswordForm();
      setPasswordOpen(false);
    } catch (error) {
      toast({
        title: 'Password change failed',
        description: apiErrorMessage(error, 'Could not update password.'),
        variant: 'destructive',
      });
    } finally {
      setSavingPassword(false);
    }
  };

  if (status === 'loading') {
    return (
      <div className="flex min-h-[40vh] items-center justify-center">
        <AppSpinner className="h-8 w-8" />
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div className="flex items-center space-x-3">
        <div className="p-2 bg-primary/10 rounded-lg">
          <Settings className="h-6 w-6 text-primary" />
        </div>
        <div>
          <h1 className="text-3xl font-bold text-foreground">Settings</h1>
          <p className="text-muted-foreground">
            Manage your account profile and security
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-6">
          <Card className="p-6">
            <div className="flex items-center space-x-2 mb-6">
              <User className="h-5 w-5 text-primary" />
              <h3 className="text-lg font-semibold text-foreground">
                Profile Information
              </h3>
            </div>

            <form onSubmit={handleSaveProfile} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="name">Full Name</Label>
                  <Input
                    id="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    autoComplete="name"
                    disabled={savingProfile}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    autoComplete="email"
                    disabled={savingProfile}
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="designation">Position</Label>
                  <Input
                    id="designation"
                    value={session?.user?.position || ''}
                    disabled
                    readOnly
                  />
                  <p className="text-xs text-muted-foreground">
                    Managed by HR / admin
                  </p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="team">Department</Label>
                  <Input
                    id="team"
                    value={session?.user?.department || ''}
                    disabled
                    readOnly
                  />
                  <p className="text-xs text-muted-foreground">
                    Managed by HR / admin
                  </p>
                </div>
              </div>

              <Button
                type="submit"
                className="mt-2"
                disabled={savingProfile || !profileDirty}
              >
                {savingProfile ? (
                  <AppSpinner className="h-4 w-4 mr-2" />
                ) : (
                  <Save className="h-4 w-4 mr-2" />
                )}
                Save Changes
              </Button>
            </form>
          </Card>
        </div>

        <div className="space-y-6">
          <Card className="p-6">
            <div className="flex items-center space-x-2 mb-6">
              <Shield className="h-5 w-5 text-primary" />
              <h3 className="text-lg font-semibold text-foreground">Security</h3>
            </div>

            <div className="space-y-4">
              <Button
                type="button"
                variant="outline"
                className="w-full justify-start"
                onClick={() => setPasswordOpen(true)}
              >
                <Key className="h-4 w-4 mr-2" />
                Change Password
              </Button>
              <p className="text-xs text-muted-foreground">
                Choose a strong password (at least 8 characters). You stay signed
                in after changing it.
              </p>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center space-x-2 mb-6">
              <Database className="h-5 w-5 text-primary" />
              <h3 className="text-lg font-semibold text-foreground">Account</h3>
            </div>

            <div className="space-y-4 text-sm">
              <div>
                <p className="font-medium text-foreground">Role</p>
                <p className="text-muted-foreground">
                  {session?.user?.role?.replaceAll('_', ' ') || '—'}
                </p>
              </div>
              <Separator />
              <div>
                <p className="font-medium text-foreground">Signed in as</p>
                <p className="text-muted-foreground break-all">
                  {session?.user?.email || '—'}
                </p>
              </div>
            </div>
          </Card>
        </div>
      </div>

      <Dialog
        open={passwordOpen}
        onOpenChange={(open) => {
          if (savingPassword) return;
          setPasswordOpen(open);
          if (!open) resetPasswordForm();
        }}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Key className="h-5 w-5" />
              Change Password
            </DialogTitle>
            <DialogDescription>
              Set a new password for your account.
            </DialogDescription>
          </DialogHeader>

          <Alert>
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription>
              After saving, use the new password the next time you sign in.
            </AlertDescription>
          </Alert>

          <form onSubmit={handleChangePassword} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="newPassword">New Password</Label>
              <div className="relative">
                <Input
                  id="newPassword"
                  type={showPassword ? 'text' : 'password'}
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  autoComplete="new-password"
                  disabled={savingPassword}
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
                  onClick={() => setShowPassword((v) => !v)}
                  tabIndex={-1}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirmPassword">Confirm Password</Label>
              <div className="relative">
                <Input
                  id="confirmPassword"
                  type={showConfirmPassword ? 'text' : 'password'}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  autoComplete="new-password"
                  disabled={savingPassword}
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
                  onClick={() => setShowConfirmPassword((v) => !v)}
                  tabIndex={-1}
                >
                  {showConfirmPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>

            <ul className="text-xs space-y-1">
              <li
                className={
                  newPassword.length >= 8
                    ? 'text-green-600'
                    : 'text-muted-foreground'
                }
              >
                At least 8 characters
              </li>
              <li
                className={
                  newPassword === confirmPassword && newPassword.length > 0
                    ? 'text-green-600'
                    : 'text-muted-foreground'
                }
              >
                Passwords match
              </li>
            </ul>

            <div className="flex justify-end gap-2 pt-2">
              <Button
                type="button"
                variant="outline"
                disabled={savingPassword}
                onClick={() => {
                  resetPasswordForm();
                  setPasswordOpen(false);
                }}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={
                  savingPassword ||
                  newPassword.length < 8 ||
                  newPassword !== confirmPassword
                }
              >
                {savingPassword ? (
                  <AppSpinner className="h-4 w-4 mr-2" />
                ) : null}
                Update Password
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
