import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Camera } from 'lucide-react';
import { Input } from '../components/ui/Input';
import { GradientButton } from '../components/ui/GradientButton';
import { Card } from '../components/ui/Card';
import { Avatar } from '../components/ui/Avatar';
import { Toggle } from '../components/ui/Toggle';
import { LocationInput } from '../components/ui/LocationInput';
import { useAuth } from '../context/AuthContext';
import { api } from '../api/client';

export function UpdateProfilePage() {
  const navigate = useNavigate();
  const { user, updateUser } = useAuth();

  const [fullName, setFullName] = useState(user?.fullName || '');
  const [email] = useState(user?.email || '');
  const [phone, setPhone] = useState(user?.phone || '');
  const [location, setLocation] = useState(user?.location || '');
  const [bio, setBio] = useState(user?.bio || '');
  const [showEmail, setShowEmail] = useState(user?.showEmail ?? false);
  const [showPhone, setShowPhone] = useState(user?.showPhone ?? true);
  const [showLocation, setShowLocation] = useState(user?.showLocation ?? true);
  const [saving, setSaving] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string | undefined>(user?.avatar || undefined);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setAvatarPreview(URL.createObjectURL(file));
    try {
      const formData = new FormData();
      formData.append('avatar', file);
      const result = await api.upload<Record<string, unknown>>('/users/avatar', formData);
      updateUser(result);
    } catch {}
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const updated = await api.put('/users/profile', {
        fullName, phone, location, bio, showEmail, showPhone, showLocation,
      });
      updateUser(updated as Record<string, unknown>);
      navigate('/');
    } catch {}
    setSaving(false);
  };

  return (
    <div className="max-w-lg mx-auto px-4 py-12">
      <Card padding="lg">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-gray-900">Update Profile Information</h1>
          <p className="text-sm text-gray-500 mt-2">Edit your profile and update information shown publicly</p>
        </div>

        <div className="flex justify-center mb-8">
          <div className="relative">
            <Avatar name={fullName} size="xl" src={avatarPreview} />
            <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleAvatarChange} />
            <button type="button" onClick={() => fileInputRef.current?.click()} className="absolute -bottom-1 -right-1 p-2 bg-gradient-to-r from-pink-500 to-primary-600 rounded-full text-white shadow-lg cursor-pointer">
              <Camera className="w-4 h-4" />
            </button>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-5">
          <Input label="Full Name" value={fullName} onChange={(e) => setFullName(e.target.value)} required />

          <div className="flex items-end gap-3">
            <div className="flex-1">
              <Input label="Email" value={email} disabled />
            </div>
            <div className="pb-0.5">
              <Toggle checked={showEmail} onChange={setShowEmail} label="Public" />
            </div>
          </div>

          <div className="flex items-end gap-3">
            <div className="flex-1">
              <Input label="Phone" value={phone} onChange={(e) => setPhone(e.target.value)} />
            </div>
            <div className="pb-0.5">
              <Toggle checked={showPhone} onChange={setShowPhone} label="Public" />
            </div>
          </div>

          <div className="flex items-end gap-3">
            <div className="flex-1">
              <LocationInput label="Location" value={location} onChange={setLocation} />
            </div>
            <div className="pb-0.5">
              <Toggle checked={showLocation} onChange={setShowLocation} label="Public" />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1.5">Bio</label>
            <textarea value={bio} onChange={(e) => setBio(e.target.value)} rows={3}
              className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none" />
          </div>

          <GradientButton type="submit" className="w-full" size="lg" disabled={saving}>
            {saving ? 'Saving...' : 'Save Changes'}
          </GradientButton>
        </form>
      </Card>
    </div>
  );
}
