"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ZURICH_UNIVERSITIES, SEMESTERS, COUNTRIES } from "@/lib/constants";
import AvatarUpload from "@/components/avatar-upload";
import UserStats from "@/components/user-stats";
import DeleteAccountDialog from "@/components/delete-account-dialog";
import { Pencil, Save, X, Loader2 } from "lucide-react";
import { toast } from "sonner";

interface User {
  id: string;
  name: string | null;
  email: string;
  emailVerified: boolean;
  image: string | null;
  role: "GUIDE" | "EXPLORER";
  bio: string | null;
  university: string | null;
  semester: string | null;
  countryOfOrigin: string | null;
  createdAt: string | Date;
}

interface GuideStats {
  toursCreated: number;
  totalReviews: number;
  avgRating: number;
  activeBookings: number;
}

interface ExplorerStats {
  bookingsCompleted: number;
  reviewsWritten: number;
  upcomingBookings: number;
}

interface ProfileContentProps {
  user: User;
}

export default function ProfileContent({ user: initialUser }: ProfileContentProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [user, setUser] = useState(initialUser);
  const [stats, setStats] = useState<GuideStats | ExplorerStats | null>(null);
  const [formData, setFormData] = useState({
    name: user.name || "",
    bio: user.bio || "",
    university: user.university || "",
    customUniversity: "",
    semester: user.semester || "",
    countryOfOrigin: user.countryOfOrigin || "",
  });
  const router = useRouter();

  // Fetch user stats
  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await fetch(`/api/users/${user.id}`);
        if (response.ok) {
          const data = await response.json();
          setStats(data.stats);
        }
      } catch (error) {
        console.error("Error fetching stats:", error);
      }
    };

    fetchStats();
  }, [user.id]);

  const handleSave = async () => {
    if (!formData.name.trim()) {
      toast.error("Name is required");
      return;
    }

    if (formData.name.length < 2) {
      toast.error("Name must be at least 2 characters");
      return;
    }

    if (formData.bio.length > 500) {
      toast.error("Bio must be less than 500 characters");
      return;
    }

    if (!formData.university) {
      toast.error("University is required");
      return;
    }

    if (formData.university === "Other - Add your university" && !formData.customUniversity) {
      toast.error("Please enter your university name");
      return;
    }

    if (!formData.semester) {
      toast.error("Semester is required");
      return;
    }

    if (!formData.countryOfOrigin) {
      toast.error("Country of origin is required");
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch("/api/users/me", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: formData.name,
          bio: formData.bio || null,
          university: formData.university === "Other - Add your university" ? formData.customUniversity : formData.university,
          semester: formData.semester,
          countryOfOrigin: formData.countryOfOrigin,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to update profile");
      }

      const updatedUser = await response.json();
      setUser(updatedUser);
      setIsEditing(false);
      toast.success("Profile updated successfully!");
      router.refresh();
    } catch (error) {
      console.error("Error updating profile:", error);
      toast.error("Failed to update profile");
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancel = () => {
    setFormData({
      name: user.name || "",
      bio: user.bio || "",
      university: user.university || "",
      customUniversity: "",
      semester: user.semester || "",
      countryOfOrigin: user.countryOfOrigin || "",
    });
    setIsEditing(false);
  };

  const handleAvatarUpload = (imageUrl: string) => {
    setUser({ ...user, image: imageUrl });
    router.refresh();
  };

  const joinDate = new Date(user.createdAt).toLocaleDateString("en-US", {
    month: "long",
    day: "numeric",
    year: "numeric",
  });

  return (
    <div className="w-full flex justify-center">
      <div className="w-full p-8 max-w-[1400px]">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold">My Profile</h1>
            <p className="text-muted-foreground">Manage your account settings</p>
          </div>
          {!isEditing ? (
            <Button onClick={() => setIsEditing(true)} variant="outline">
              <Pencil className="h-4 w-4 mr-2" />
              Edit Profile
            </Button>
          ) : (
            <div className="flex gap-2">
              <Button onClick={handleCancel} variant="outline" disabled={isLoading}>
                <X className="h-4 w-4 mr-2" />
                Cancel
              </Button>
              <Button onClick={handleSave} disabled={isLoading}>
                {isLoading ? (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <Save className="h-4 w-4 mr-2" />
                )}
                Save Changes
              </Button>
            </div>
          )}
        </div>

        {/* Statistics */}
        {stats && (
          <div className="mb-6">
            <UserStats role={user.role} stats={stats} />
          </div>
        )}

        <div className="grid gap-6 md:grid-cols-3">
          {/* Left Column - Avatar */}
          <Card className="md:col-span-1">
            <CardHeader>
              <CardTitle>Profile Picture</CardTitle>
            </CardHeader>
            <CardContent className="flex flex-col items-center">
              <AvatarUpload
                currentImage={user.image}
                userName={user.name}
                onUploadComplete={handleAvatarUpload}
              />
            </CardContent>
          </Card>

          {/* Right Column - Profile Info */}
          <Card className="md:col-span-2">
            <CardHeader>
              <CardTitle>Profile Information</CardTitle>
              <CardDescription>Update your personal details</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Name */}
              <div className="space-y-2">
                <Label htmlFor="name">Name {isEditing && <span className="text-red-500">*</span>}</Label>
                {isEditing ? (
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="Enter your name"
                    disabled={isLoading}
                  />
                ) : (
                  <p className="text-sm">{user.name || "Not set"}</p>
                )}
              </div>

              <Separator />

              {/* Email */}
              <div className="space-y-2">
                <Label>Email</Label>
                <p className="text-sm text-muted-foreground">{user.email}</p>
                <p className="text-xs text-muted-foreground">Email cannot be changed</p>
              </div>

              <Separator />

              {/* Role */}
              <div className="space-y-2">
                <Label>Role</Label>
                <div>
                  <Badge variant={user.role === "GUIDE" ? "default" : "secondary"}>
                    {user.role}
                  </Badge>
                </div>
              </div>

              <Separator />

              {/* Bio */}
              <div className="space-y-2">
                <Label htmlFor="bio">
                  Bio
                  {isEditing && (
                    <span className="text-xs text-muted-foreground ml-2">
                      ({formData.bio.length}/500)
                    </span>
                  )}
                </Label>
                {isEditing ? (
                  <Textarea
                    id="bio"
                    value={formData.bio}
                    onChange={(e) => setFormData({ ...formData, bio: e.target.value })}
                    placeholder="Tell us about yourself..."
                    rows={4}
                    disabled={isLoading}
                    maxLength={500}
                  />
                ) : (
                  <p className="text-sm whitespace-pre-wrap">
                    {user.bio || "No bio added yet"}
                  </p>
                )}
              </div>

              <Separator />

              {/* University */}
              <div className="space-y-2">
                <Label htmlFor="university">
                  University {isEditing && <span className="text-red-500">*</span>}
                </Label>
                {isEditing ? (
                  <>
                    <Select
                      value={formData.university}
                      onValueChange={(value: string) => {
                        setFormData({ ...formData, university: value });
                        if (value !== "Other - Add your university") {
                          setFormData((prev) => ({ ...prev, customUniversity: "" }));
                        }
                      }}
                      disabled={isLoading}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select your university" />
                      </SelectTrigger>
                      <SelectContent>
                        {ZURICH_UNIVERSITIES.map((uni: string) => (
                          <SelectItem key={uni} value={uni}>
                            {uni}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {formData.university === "Other - Add your university" && (
                      <Input
                        id="customUniversity"
                        type="text"
                        placeholder="Enter your university"
                        value={formData.customUniversity}
                        onChange={(e) =>
                          setFormData({ ...formData, customUniversity: e.target.value })
                        }
                        disabled={isLoading}
                      />
                    )}
                  </>
                ) : (
                  <p className="text-sm">{user.university || "Not set"}</p>
                )}
              </div>

              <Separator />

              {/* Semester */}
              <div className="space-y-2">
                <Label htmlFor="semester">
                  Semester {isEditing && <span className="text-red-500">*</span>}
                </Label>
                {isEditing ? (
                  <Select
                    value={formData.semester}
                    onValueChange={(value: string) =>
                      setFormData({ ...formData, semester: value })
                    }
                    disabled={isLoading}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select your semester" />
                    </SelectTrigger>
                    <SelectContent>
                      {SEMESTERS.map((sem: string) => (
                        <SelectItem key={sem} value={sem}>
                          {sem}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <p className="text-sm">{user.semester || "Not set"}</p>
                )}
              </div>

              <Separator />

              {/* Country of Origin */}
              <div className="space-y-2">
                <Label htmlFor="countryOfOrigin">
                  Country of Origin {isEditing && <span className="text-red-500">*</span>}
                </Label>
                {isEditing ? (
                  <Select
                    value={formData.countryOfOrigin}
                    onValueChange={(value: string) =>
                      setFormData({ ...formData, countryOfOrigin: value })
                    }
                    disabled={isLoading}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select your country" />
                    </SelectTrigger>
                    <SelectContent>
                      {COUNTRIES.map((country: { code: string; name: string; flag: string }) => (
                        <SelectItem key={country.code} value={country.code}>
                          {country.flag} {country.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <p className="text-sm">
                    {COUNTRIES.find((c) => c.code === user.countryOfOrigin)?.flag}{" "}
                    {COUNTRIES.find((c) => c.code === user.countryOfOrigin)?.name || "Not set"}
                  </p>
                )}
              </div>

              <Separator />

              {/* Account Info */}
              <div className="space-y-2">
                <Label>Member Since</Label>
                <p className="text-sm text-muted-foreground">{joinDate}</p>
              </div>

              <div className="space-y-2">
                <Label>Email Verification</Label>
                <div>
                  <Badge variant={user.emailVerified ? "default" : "outline"}>
                    {user.emailVerified ? "Verified" : "Not Verified"}
                  </Badge>
                </div>
              </div>

              <Separator />

              {/* Danger Zone - Delete Account */}
              <div className="space-y-3 pt-4">
                <Label className="text-red-600 font-semibold">Danger Zone</Label>
                <div className="bg-red-50 border border-red-200 rounded-lg p-4 space-y-3">
                  <div>
                    <p className="text-sm font-medium text-red-900">Delete Account</p>
                    <p className="text-xs text-red-700 mt-1">
                      Once you delete your account, there is no going back. Please be certain.
                    </p>
                  </div>
                  <DeleteAccountDialog 
                    userEmail={user.email} 
                    userName={user.name}
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
      
    </div>
  );
}
