import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
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, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { useAuth } from '@/hooks/useAuth';
import { useUsernameValidation } from '@/hooks/useUsernameValidation';
import { User, MapPin, Calendar, Star, Trophy, Settings, Camera, Edit3, Save, X, ArrowLeft, Check, AlertCircle, Loader2, UserX } from 'lucide-react';
import { Profile as ProfileType } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { PhotoUpload } from '@/components/upload/PhotoUpload';
import { profileEditSchema } from '@/lib/validation';
import { LocationDisplay } from '@/components/profile/LocationDisplay';
import { UserBlockButton } from '@/components/profile/UserBlockButton';
import { PersonalLocationDisplay } from '@/components/profile/PersonalLocationDisplay';
import { useProfileFieldAccess } from '@/hooks/useProfileFieldAccess';
export default function Profile() {
  const {
    username
  } = useParams<{
    username?: string;
  }>();
  const navigate = useNavigate();
  const {
    toast
  } = useToast();
  const {
    refreshProfile
  } = useAuth();
  const [profile, setProfile] = useState<ProfileType | null>(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [editForm, setEditForm] = useState({
    username: '',
    display_name: '',
    bio: ''
  });
  const [showUsernameDialog, setShowUsernameDialog] = useState(false);
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [avatarImageId, setAvatarImageId] = useState<string>('');
  const [calculatedStats, setCalculatedStats] = useState({
    rideCount: 0,
    coasterCount: 0,
    parkCount: 0
  });

  // Profile field access checking
  const { canViewField, loading: fieldAccessLoading } = useProfileFieldAccess(profile?.user_id);

  // Username validation
  const usernameValidation = useUsernameValidation(editForm.username, profile?.username);
  useEffect(() => {
    getCurrentUser();
    if (username) {
      fetchProfile(username);
    } else {
      fetchCurrentUserProfile();
    }
  }, [username]);

  const fetchCalculatedStats = async (userId: string) => {
    try {
      // Fetch ride credits stats
      const { data: ridesData, error: ridesError } = await supabase
        .from('user_ride_credits')
        .select(`
          ride_count,
          rides!inner(category, park_id)
        `)
        .eq('user_id', userId);

      if (ridesError) throw ridesError;

      // Calculate total rides count (sum of all ride_count values)
      const totalRides = ridesData?.reduce((sum, credit) => sum + (credit.ride_count || 0), 0) || 0;

      // Calculate coasters count (distinct rides where category is roller_coaster)
      const coasterRides = ridesData?.filter(credit => 
        credit.rides?.category === 'roller_coaster'
      ) || [];
      const uniqueCoasters = new Set(coasterRides.map(credit => credit.rides));
      const coasterCount = uniqueCoasters.size;

      // Calculate parks count (distinct parks where user has ridden at least one ride)
      const parkRides = ridesData?.map(credit => credit.rides?.park_id).filter(Boolean) || [];
      const uniqueParks = new Set(parkRides);
      const parkCount = uniqueParks.size;

      setCalculatedStats({
        rideCount: totalRides,
        coasterCount: coasterCount,
        parkCount: parkCount
      });
    } catch (error: any) {
      console.error('Error fetching calculated stats:', error);
      // Set defaults on error
      setCalculatedStats({
        rideCount: 0,
        coasterCount: 0,
        parkCount: 0
      });
    }
  };
  const getCurrentUser = async () => {
    const {
      data: {
        user
      }
    } = await supabase.auth.getUser();
    setCurrentUser(user);
  };
  const fetchProfile = async (profileUsername: string) => {
    try {
      const { data, error } = await supabase
        .from('profiles')
        .select(`*, location:locations(*)`)
        .eq('username', profileUsername)
        .maybeSingle();

      if (error) throw error;

      if (data) {
        setProfile(data as ProfileType);
        setEditForm({
          username: data.username || '',
          display_name: data.display_name || '',
          bio: data.bio || ''
        });
        setAvatarUrl(data.avatar_url || '');
        setAvatarImageId(data.avatar_image_id || '');
        
        // Fetch calculated stats for this user
        await fetchCalculatedStats(data.user_id);
      }
    } catch (error: any) {
      console.error('Error fetching profile:', error);
      toast({
        variant: "destructive",
        title: "Error loading profile",
        description: error.message
      });
    } finally {
      setLoading(false);
    }
  };
  const fetchCurrentUserProfile = async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) {
        navigate('/auth');
        return;
      }

      const { data, error } = await supabase
        .from('profiles')
        .select(`*, location:locations(*)`)
        .eq('user_id', user.id)
        .maybeSingle();

      if (error) throw error;

      if (data) {
        setProfile(data as ProfileType);
        setEditForm({
          username: data.username || '',
          display_name: data.display_name || '',
          bio: data.bio || ''
        });
        setAvatarUrl(data.avatar_url || '');
        setAvatarImageId(data.avatar_image_id || '');
        
        // Fetch calculated stats for the current user
        await fetchCalculatedStats(user.id);
      }
    } catch (error: any) {
      console.error('Error fetching profile:', error);
      toast({
        variant: "destructive",
        title: "Error loading profile",
        description: error.message
      });
    } finally {
      setLoading(false);
    }
  };
  const validateForm = () => {
    const result = profileEditSchema.safeParse(editForm);
    if (!result.success) {
      const errors: Record<string, string> = {};
      result.error.issues.forEach(issue => {
        if (issue.path[0]) {
          errors[issue.path[0] as string] = issue.message;
        }
      });
      setFormErrors(errors);
      return false;
    }
    if (!usernameValidation.isValid && editForm.username !== profile?.username) {
      setFormErrors({
        username: usernameValidation.error || 'Invalid username'
      });
      return false;
    }
    setFormErrors({});
    return true;
  };
  const handleSaveProfile = async () => {
    if (!profile || !currentUser) return;
    if (!validateForm()) return;
    const usernameChanged = editForm.username !== profile.username;
    if (usernameChanged && !showUsernameDialog) {
      setShowUsernameDialog(true);
      return;
    }
    try {
      const updateData: any = {
        display_name: editForm.display_name,
        bio: editForm.bio,
        avatar_url: avatarUrl,
        avatar_image_id: avatarImageId
      };
      if (usernameChanged) {
        updateData.username = editForm.username;
      }
      const {
        error
      } = await supabase.from('profiles').update(updateData).eq('user_id', currentUser.id);
      if (error) throw error;
      setProfile(prev => prev ? {
        ...prev,
        ...updateData
      } : null);
      setEditing(false);
      setShowUsernameDialog(false);
      if (usernameChanged) {
        toast({
          title: "Profile updated",
          description: "Your username and profile URL have been updated successfully."
        });
        // Navigate to new username URL
        navigate(`/profile/${editForm.username}`);
      } else {
        toast({
          title: "Profile updated",
          description: "Your profile has been updated successfully."
        });
      }
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "Error updating profile",
        description: error.message
      });
    }
  };
  const confirmUsernameChange = () => {
    setShowUsernameDialog(false);
    handleSaveProfile();
  };
  const handleAvatarUpload = async (urls: string[], imageId?: string) => {
    if (!currentUser || !urls[0]) return;
    const newAvatarUrl = urls[0];
    const newImageId = imageId || '';

    // Update local state immediately
    setAvatarUrl(newAvatarUrl);
    setAvatarImageId(newImageId);
    try {
      // Update database immediately
      const {
        error
      } = await supabase.from('profiles').update({
        avatar_url: newAvatarUrl,
        avatar_image_id: newImageId
      }).eq('user_id', currentUser.id);
      if (error) throw error;

      // Update local profile state
      setProfile(prev => prev ? {
        ...prev,
        avatar_url: newAvatarUrl,
        avatar_image_id: newImageId
      } : null);

      // Refresh the auth context to update header avatar
      if (refreshProfile) {
        await refreshProfile();
      }
      toast({
        title: "Avatar updated",
        description: "Your profile picture has been updated successfully."
      });
    } catch (error: any) {
      // Revert local state on error
      setAvatarUrl(profile?.avatar_url || '');
      setAvatarImageId(profile?.avatar_image_id || '');
      toast({
        variant: "destructive",
        title: "Error updating avatar",
        description: error.message
      });
    }
  };
  const isOwnProfile = currentUser && profile && currentUser.id === profile.user_id;
  if (loading) {
    return <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="animate-pulse space-y-6">
            <div className="h-32 bg-muted rounded-lg"></div>
            <div className="h-8 bg-muted rounded w-1/3"></div>
            <div className="h-4 bg-muted rounded w-1/2"></div>
          </div>
        </div>
      </div>;
  }
  if (!profile) {
    return <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <User className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
            <h1 className="text-2xl font-bold mb-4">Profile Not Found</h1>
            <p className="text-muted-foreground mb-6">
              The profile you're looking for doesn't exist.
            </p>
            <Button onClick={() => navigate('/')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Go Home
            </Button>
          </div>
        </div>
      </div>;
  }
  return <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        {/* Profile Header */}
        <div className="relative mb-8">
          <Card>
            <CardContent className="p-8">
              <div className="flex flex-col md:flex-row gap-6">
                <div className="flex flex-col items-center md:items-start">
                  <PhotoUpload 
                    variant="avatar" 
                    maxFiles={1} 
                    maxSizeMB={1} 
                    existingPhotos={canViewField('avatar_url') && profile.avatar_url ? [profile.avatar_url] : []} 
                    onUploadComplete={handleAvatarUpload} 
                    currentImageId={avatarImageId} 
                    onError={error => {
                      toast({
                        title: "Upload Error",
                        description: error,
                        variant: "destructive"
                      });
                    }} 
                    className="mb-4" 
                  />
                  
                  <div className="flex flex-col gap-2 mt-2">
                    {isOwnProfile && !editing && <Button variant="outline" size="sm" onClick={() => setEditing(true)}>
                        <Edit3 className="w-4 h-4 mr-2" />
                        Edit Profile
                      </Button>}
                    
                    {!isOwnProfile && <UserBlockButton targetUserId={profile.user_id} targetUsername={profile.username} />}
                  </div>
                </div>

                <div className="flex-1">
                  {editing && isOwnProfile ? <div className="space-y-4">
                      <div>
                        <Label htmlFor="username">Username</Label>
                        <div className="relative">
                          <Input id="username" value={editForm.username} onChange={e => setEditForm(prev => ({
                        ...prev,
                        username: e.target.value
                      }))} placeholder="your_username" className={`pr-10 ${formErrors.username ? 'border-destructive' : ''}`} />
                          <div className="absolute right-3 top-1/2 -translate-y-1/2">
                            {usernameValidation.isChecking ? <Loader2 className="w-4 h-4 text-muted-foreground animate-spin" /> : editForm.username === profile?.username ? <Check className="w-4 h-4 text-muted-foreground" /> : usernameValidation.isValid ? <Check className="w-4 h-4 text-green-500" /> : usernameValidation.error ? <AlertCircle className="w-4 h-4 text-destructive" /> : null}
                          </div>
                        </div>
                        {formErrors.username && <p className="text-sm text-destructive mt-1">{formErrors.username}</p>}
                        {usernameValidation.error && editForm.username !== profile?.username && <p className="text-sm text-destructive mt-1">{usernameValidation.error}</p>}
                        {usernameValidation.isValid && editForm.username !== profile?.username && <p className="text-sm text-green-600 mt-1">Username is available!</p>}
                        <p className="text-xs text-muted-foreground mt-1">
                          Your profile URL will be /profile/{editForm.username}
                        </p>
                      </div>
                      
                      <div>
                        <Label htmlFor="display_name">Display Name</Label>
                        <Input id="display_name" value={editForm.display_name} onChange={e => setEditForm(prev => ({
                      ...prev,
                      display_name: e.target.value
                    }))} placeholder="Your display name" className={formErrors.display_name ? 'border-destructive' : ''} />
                        {formErrors.display_name && <p className="text-sm text-destructive mt-1">{formErrors.display_name}</p>}
                      </div>
                      
                      <div>
                        <Label htmlFor="bio">Bio</Label>
                        <Textarea id="bio" value={editForm.bio} onChange={e => setEditForm(prev => ({
                      ...prev,
                      bio: e.target.value
                    }))} placeholder="Tell us about yourself..." rows={3} className={formErrors.bio ? 'border-destructive' : ''} />
                        {formErrors.bio && <p className="text-sm text-destructive mt-1">{formErrors.bio}</p>}
                      </div>

                      <div className="flex gap-2">
                        <Button onClick={handleSaveProfile} size="sm" disabled={usernameValidation.isChecking || editForm.username !== profile?.username && !usernameValidation.isValid}>
                          <Save className="w-4 h-4 mr-2" />
                          Save Changes
                        </Button>
                        <Button variant="outline" onClick={() => {
                      setEditing(false);
                      setFormErrors({});
                      setEditForm({
                        username: profile?.username || '',
                        display_name: profile?.display_name || '',
                        bio: profile?.bio || ''
                      });
                    }} size="sm">
                          <X className="w-4 h-4 mr-2" />
                          Cancel
                        </Button>
                      </div>
                    </div> : <div>
                      <div className="flex items-center gap-3 mb-2">
                        <h1 className="text-3xl font-bold">
                          {profile.display_name || profile.username}
                        </h1>
                        {profile.display_name && <Badge variant="secondary" className="cursor-pointer hover:bg-secondary/80" onClick={() => navigate(`/profile/${profile.username}`)}>@{profile.username}</Badge>}
                      </div>
                      
                      {canViewField('bio') && profile.bio && (
                        <p className="text-muted-foreground mb-4 max-w-2xl">
                          {profile.bio}
                        </p>
                      )}

                      <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                        <div className="flex items-center gap-1">
                          <Calendar className="w-4 h-4" />
                          Joined {new Date(profile.created_at).toLocaleDateString('en-US', {
                        month: 'long',
                        year: 'numeric'
                      })}
                        </div>
                        
                        {/* Show pronouns if enabled and privacy allows */}
                        {profile.show_pronouns && canViewField('preferred_pronouns') && profile.preferred_pronouns && (
                          <div className="flex items-center gap-1">
                            <User className="w-4 h-4" />
                            {profile.preferred_pronouns}
                          </div>
                        )}
                        
                        {/* Show personal location if available and privacy allows */}
                        {canViewField('personal_location') && profile.personal_location && (
                          <PersonalLocationDisplay 
                            personalLocation={profile.personal_location} 
                            userId={profile.user_id} 
                            isOwnProfile={isOwnProfile} 
                          />
                        )}
                        
                        {/* Show location only if privacy allows */}
                        {canViewField('location_id') && profile.location && (
                          <LocationDisplay 
                            location={profile.location} 
                            userId={profile.user_id} 
                            isOwnProfile={isOwnProfile} 
                          />
                        )}
                      </div>
                    </div>}
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          <Card>
            <CardContent className="p-4 text-center">
              <div className="text-2xl font-bold text-primary">{calculatedStats.rideCount}</div>
              <div className="text-sm text-muted-foreground">Rides</div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4 text-center">
              <div className="text-2xl font-bold text-accent">{calculatedStats.coasterCount}</div>
              <div className="text-sm text-muted-foreground">Coasters</div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4 text-center">
              <div className="text-2xl font-bold text-secondary">{calculatedStats.parkCount}</div>
              <div className="text-sm text-muted-foreground">Parks</div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4 text-center">
              <div className="text-2xl font-bold text-accent">{profile.review_count}</div>
              <div className="text-sm text-muted-foreground">Reviews</div>
            </CardContent>
          </Card>
        </div>

        {/* Profile Tabs */}
        <Tabs defaultValue="activity" className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="activity">Activity</TabsTrigger>
            <TabsTrigger value="reviews">Reviews</TabsTrigger>
            <TabsTrigger value="lists">Rankings</TabsTrigger>
            <TabsTrigger value="credits">Ride Credits</TabsTrigger>
          </TabsList>

          <TabsContent value="activity" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Recent Activity</CardTitle>
                <CardDescription>
                  Latest reviews, ratings, and achievements
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="text-center py-12">
                  <Trophy className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
                  <h3 className="text-xl font-semibold mb-2">Activity Feed Coming Soon</h3>
                  <p className="text-muted-foreground">
                    Track reviews, ratings, and achievements
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="reviews" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Reviews ({profile.review_count})</CardTitle>
                <CardDescription>
                  Parks and rides reviews
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="text-center py-12">
                  <Star className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
                  <h3 className="text-xl font-semibold mb-2">Reviews Coming Soon</h3>
                  <p className="text-muted-foreground">
                    User reviews and ratings will appear here
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="lists" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Rankings</CardTitle>
                <CardDescription>Personal rankings of rides</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="text-center py-12">
                  <Trophy className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
                  <h3 className="text-xl font-semibold mb-2">Rankings Coming Soon</h3>
                  <p className="text-muted-foreground">
                    Create and share your favorite park and ride rankings
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="credits" className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Ride Credits</CardTitle>
                <CardDescription>
                  Track all the rides you've experienced
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="text-center py-12">
                  <User className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
                  <h3 className="text-xl font-semibold mb-2">Ride Credits Coming Soon</h3>
                  <p className="text-muted-foreground">
                    Log and track your ride experiences
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </main>

      {/* Username Change Confirmation Dialog */}
      <AlertDialog open={showUsernameDialog} onOpenChange={setShowUsernameDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Change Username?</AlertDialogTitle>
            <AlertDialogDescription>
              Changing your username will also change your profile URL from{' '}
              <code className="bg-muted px-1 py-0.5 rounded text-xs">
                /profile/{profile?.username}
              </code>{' '}
              to{' '}
              <code className="bg-muted px-1 py-0.5 rounded text-xs">
                /profile/{editForm.username}
              </code>
              . This means any existing bookmarks or links to your profile will no longer work.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmUsernameChange}>
              Change Username
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>;
}