import { useState } from 'react';
import { useProfile } from '@/hooks/useProfile';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';

export function SettingsProfile() {
  const { user, loading, updateProfile } = useProfile();
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState({
    full_name: '',
    email: ''
  });
  const [isSaving, setIsSaving] = useState(false);

  // Initialize form with user data
  // In a real app, we'd use useEffect to set this when user loads
  // For simplicity, we'll initialize on mount assuming user exists

  const handleSave = async () => {
    setIsSaving(true);
    try {
      await updateProfile({
        full_name: formData.full_name.trim(),
        email: formData.email.trim()
      });
      setEditMode(false);
    } catch (err) {
      // Error handled by useProfile hook
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin" />
          <p className="mt-2">Loading...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <div className="text-center">
          <p>Please log in to view your profile</p>
        </div>
      </div>
    );
  }

  // Initialize form data if not already set
  // Using a simple approach - in practice this would be in useEffect
  const initialized = formData.full_name !== '' || formData.email !== '';
  if (!initialized && user) {
    setFormData({
      full_name: user.full_name,
      email: user.email
    });
  }

  return (
    <div className="space-y-6">
      <div className="border-t pt-4">
        <Button
          variant="outline"
          onClick={() => setEditMode(!editMode)}
          className="w-full text-left"
        >
          {editMode ? 'Cancel' : 'Edit Profile'}
        </Button>
      </div>

      {editMode ? (
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Edit Profile</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
              <div className="space-y-3">
                <div className="space-y-2">
                  <Label htmlFor="full_name">Full Name</Label>
                  <Input
                    id="full_name"
                    type="text"
                    value={formData.full_name}
                    onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                    required
                    autoComplete="name"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email Address</Label>
                  <Input
                    id="email"
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    required
                    autoComplete="email"
                  />
                </div>
              </div>
              <Button
                type="submit"
                className="w-full"
                disabled={isSaving}
              >
                {isSaving ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  'Save Changes'
                )}
              </Button>
            </form>
          </CardContent>
        </Card>
      ) : (
        <>
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Profile Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="full_name">Full Name</Label>
                <p id="full_name" className="bg-muted px-3 py-2 rounded-md">
                  {user.full_name}
                </p>
              </div>
              <div className="space-y-2">
                <Label htmlFor="email">Email Address</Label>
                <p id="email" className="bg-muted px-3 py-2 rounded-md">
                  {user.email}
                </p>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Account Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>Member Since</Label>
                <p className="bg-muted px-3 py-2 rounded-md">
                  {new Date(user.created_at).toLocaleDateString()}
                </p>
              </div>
              <div className="space-y-2">
                <Label>Account Status</Label>
                <p className={`bg-muted px-3 py-2 rounded-md ${user.is_active ? 'text-green-500' : 'text-red-500'}`}>
                  {user.is_active ? 'Active' : 'Inactive'}
                </p>
              </div>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
