import React, { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';
import { 
  User, 
  Camera, 
  Settings as SettingsIcon, 
  Bell, 
  Shield, 
  CreditCard,
  Globe
} from 'lucide-react';

const Settings = () => {
  const { user, login } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  const [profileData, setProfileData] = useState({
    name: user?.name || '',
    email: user?.email || '',
    phone: (user as any)?.phone || '',
    description: (user as any)?.bio || '',
    location: typeof user?.location === 'string' ? user.location : user?.location?.lat ? `${user.location.lat}, ${user.location.lng}` : '',
    facebook: (user as any)?.socialLinks?.facebook || '',
    twitter: (user as any)?.socialLinks?.twitter || '',
    instagram: (user as any)?.socialLinks?.instagram || '',
    linkedin: (user as any)?.socialLinks?.linkedin || '',
  });

  const handleProfileUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // Update user context with new data
      const updatedUser = {
        ...user!,
        name: profileData.name,
        email: profileData.email,
        phone: profileData.phone,
        bio: profileData.description,
        location: profileData.location,
        socialLinks: {
          facebook: profileData.facebook,
          twitter: profileData.twitter,
          instagram: profileData.instagram,
          linkedin: profileData.linkedin,
        }
      };
      
      // Save to localStorage
      localStorage.setItem('user', JSON.stringify(updatedUser));
      
      toast.success('Profile updated successfully!');
    } catch (error) {
      toast.error('Failed to update profile');
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (field: string, value: string) => {
    setProfileData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <div className="p-6 max-w-6xl mx-auto">
      {/* Header Section */}
      <div className="relative mb-8">
        <div className="h-48 bg-gradient-to-r from-orange-400 to-orange-500 rounded-lg relative overflow-hidden">
          <div className="absolute inset-0 bg-black/20"></div>
          <Button 
            variant="outline" 
            size="sm" 
            className="absolute top-4 right-4 bg-white/10 border-white/20 text-white hover:bg-white/20"
          >
            <Camera className="w-4 h-4 mr-2" />
            Upload header
          </Button>
          
          <div className="absolute bottom-6 left-6 flex items-end space-x-4">
            <div className="relative">
              <div className="w-24 h-24 rounded-full border-4 border-white overflow-hidden bg-white">
                <img 
                  src={user?.avatar || "/placeholder.svg"} 
                  alt={user?.name}
                  className="w-full h-full object-cover"
                />
              </div>
              <Button 
                size="sm" 
                className="absolute -bottom-2 -right-2 w-8 h-8 p-0 rounded-full"
              >
                <Camera className="w-4 h-4" />
              </Button>
            </div>
            
            <div className="text-white pb-2">
              <h1 className="text-2xl font-bold flex items-center">
                {user?.name}
                <div className="w-5 h-5 bg-green-500 rounded-full ml-2 flex items-center justify-center">
                  <div className="w-2 h-2 bg-white rounded-full"></div>
                </div>
              </h1>
              <p className="text-white/80 flex items-center mt-1">
                <span className="mr-2">📍</span>
                {typeof user?.location === 'string' ? user.location : 'San Francisco, US'}
                <span className="mx-2">•</span>
                <span className="text-sm">Joined Oct 2023</span>
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Settings Content */}
      <Tabs defaultValue="details" className="space-y-6">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="details" className="flex items-center space-x-2">
            <User className="w-4 h-4" />
            <span>Details</span>
          </TabsTrigger>
          <TabsTrigger value="security" className="flex items-center space-x-2">
            <Shield className="w-4 h-4" />
            <span>Security</span>
          </TabsTrigger>
          <TabsTrigger value="notifications" className="flex items-center space-x-2">
            <Bell className="w-4 h-4" />
            <span>Notifications</span>
          </TabsTrigger>
          <TabsTrigger value="billing" className="flex items-center space-x-2">
            <CreditCard className="w-4 h-4" />
            <span>Billing</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="details">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center text-red-500">
                <div className="w-1 h-6 bg-red-500 mr-3"></div>
                Details
              </CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleProfileUpdate} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div>
                    <Label htmlFor="name">Name *</Label>
                    <Input
                      id="name"
                      value={profileData.name}
                      onChange={(e) => handleInputChange('name', e.target.value)}
                      placeholder="Name"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="phone">Phone *</Label>
                    <Input
                      id="phone"
                      value={profileData.phone}
                      onChange={(e) => handleInputChange('phone', e.target.value)}
                      placeholder="(123) 456 - 789"
                    />
                  </div>
                  <div>
                    <Label htmlFor="email">Email Address *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={profileData.email}
                      onChange={(e) => handleInputChange('email', e.target.value)}
                      placeholder="example@email.com"
                      required
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="description">Description *</Label>
                  <Textarea
                    id="description"
                    value={profileData.description}
                    onChange={(e) => handleInputChange('description', e.target.value)}
                    placeholder="Please enter up to 4000 characters."
                    className="min-h-[120px]"
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label htmlFor="facebook">Facebook Page (optional)</Label>
                    <Input
                      id="facebook"
                      value={profileData.facebook}
                      onChange={(e) => handleInputChange('facebook', e.target.value)}
                      placeholder="https://facebook.com"
                    />
                  </div>
                  <div>
                    <Label htmlFor="twitter">Twitter profile (optional)</Label>
                    <Input
                      id="twitter"
                      value={profileData.twitter}
                      onChange={(e) => handleInputChange('twitter', e.target.value)}
                      placeholder="https://twitter.com"
                    />
                  </div>
                  <div>
                    <Label htmlFor="instagram">Instagram profile (optional)</Label>
                    <Input
                      id="instagram"
                      value={profileData.instagram}
                      onChange={(e) => handleInputChange('instagram', e.target.value)}
                      placeholder="https://instagram.com"
                    />
                  </div>
                  <div>
                    <Label htmlFor="linkedin">LinkedIn page (optional)</Label>
                    <Input
                      id="linkedin"
                      value={profileData.linkedin}
                      onChange={(e) => handleInputChange('linkedin', e.target.value)}
                      placeholder="https://linkedin.com"
                    />
                  </div>
                </div>

                <div className="flex justify-end">
                  <Button 
                    type="submit" 
                    disabled={isLoading}
                    className="bg-red-500 hover:bg-red-600"
                  >
                    {isLoading ? 'Updating...' : 'Update Profile'}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="security">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center text-red-500">
                <div className="w-1 h-6 bg-red-500 mr-3"></div>
                Security Settings
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div>
                <Label htmlFor="current-password">Current Password</Label>
                <Input
                  id="current-password"
                  type="password"
                  placeholder="Enter current password"
                />
              </div>
              <div>
                <Label htmlFor="new-password">New Password</Label>
                <Input
                  id="new-password"
                  type="password"
                  placeholder="Enter new password"
                />
              </div>
              <div>
                <Label htmlFor="confirm-password">Confirm New Password</Label>
                <Input
                  id="confirm-password"
                  type="password"
                  placeholder="Confirm new password"
                />
              </div>
              <Button className="bg-red-500 hover:bg-red-600">
                Update Password
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="notifications">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center text-red-500">
                <div className="w-1 h-6 bg-red-500 mr-3"></div>
                Notification Preferences
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h4 className="font-medium">Email Notifications</h4>
                  <p className="text-sm text-muted-foreground">Receive notifications via email</p>
                </div>
                <Button variant="outline" size="sm">Enable</Button>
              </div>
              <div className="flex items-center justify-between">
                <div>
                  <h4 className="font-medium">Push Notifications</h4>
                  <p className="text-sm text-muted-foreground">Receive push notifications</p>
                </div>
                <Button variant="outline" size="sm">Enable</Button>
              </div>
              <div className="flex items-center justify-between">
                <div>
                  <h4 className="font-medium">SMS Notifications</h4>
                  <p className="text-sm text-muted-foreground">Receive notifications via SMS</p>
                </div>
                <Button variant="outline" size="sm">Enable</Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="billing">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center text-red-500">
                <div className="w-1 h-6 bg-red-500 mr-3"></div>
                Billing Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label htmlFor="card-number">Card Number</Label>
                  <Input
                    id="card-number"
                    placeholder="**** **** **** 1234"
                  />
                </div>
                <div>
                  <Label htmlFor="expiry">Expiry Date</Label>
                  <Input
                    id="expiry"
                    placeholder="MM/YY"
                  />
                </div>
                <div>
                  <Label htmlFor="cvv">CVV</Label>
                  <Input
                    id="cvv"
                    placeholder="123"
                  />
                </div>
                <div>
                  <Label htmlFor="billing-name">Cardholder Name</Label>
                  <Input
                    id="billing-name"
                    placeholder="John Doe"
                  />
                </div>
              </div>
              <Button className="bg-red-500 hover:bg-red-600">
                Update Billing Info
              </Button>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default Settings;