import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { User, Mail, Phone, 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 { LocationInput } from '../components/ui/LocationInput';
import { api } from '../api/client';
import { useAuth } from '../context/AuthContext';

export function CreateProfilePage() {
  const navigate = useNavigate();
  const { user, updateUser } = useAuth();
  const [fullName, setFullName] = useState(user?.fullName || '');
  const [email, setEmail] = useState(user?.email || '');
  const [phone, setPhone] = useState('');
  const [location, setLocation] = useState('');
  const [bio, setBio] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  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 {
      setError('Failed to upload avatar');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError('');

    try {
      const result = await api.put<{ id: string; fullName: string; phone?: string; location?: string; bio?: string }>('/users/profile', {
        fullName,
        phone: phone || undefined,
        location: location || undefined,
        bio: bio || undefined,
      });
      updateUser(result);
      navigate('/');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save profile');
    } finally {
      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">Create User Profile</h1>
          <p className="text-sm text-gray-500 mt-2">Set up your profile to start buying and selling on the marketplace</p>
        </div>

        <div className="flex justify-center mb-8">
          <div className="relative">
            <Avatar name={fullName || 'U'} 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>

        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-600">{error}</div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <Input label="Full Name" placeholder="Enter your full name" value={fullName} onChange={(e) => setFullName(e.target.value)}
            icon={<User className="w-4 h-4" />} required />
          <Input label="Email Address" type="email" placeholder="Enter your email" value={email} onChange={(e) => setEmail(e.target.value)}
            icon={<Mail className="w-4 h-4" />} required disabled />
          <Input label="Phone" type="tel" placeholder="(XXX) XXX-XXXX" value={phone} onChange={(e) => setPhone(e.target.value)}
            icon={<Phone className="w-4 h-4" />} />
          <LocationInput label="Location" placeholder="E.g. city, state, zip code" value={location} onChange={setLocation} />
          <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}
              placeholder="Tell us a little about yourself"
              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...' : 'Create Profile'}
          </GradientButton>
        </form>
      </Card>
    </div>
  );
}
