"use client";

import type React from "react";

import { useEffect, useState, useRef } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { Loader2, Upload } from "lucide-react";
import { customerProfileSchema } from "@/lib/validations/profile";
import {
  getProfileAction,
  updateProfileAction,
} from "@/features/users/actions/profile-actions";
import type { User } from "@/core/api/services/auth/auth.types";

export function ManageProfileContent() {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // Profile Form State
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [isUpdating, setIsUpdating] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const toast = useToastEnhanced();

  // Derived state
  const _userName =
    firstName && lastName ? `${firstName} ${lastName}` : firstName || "User";
  const userInitials =
    firstName && lastName
      ? `${firstName[0]}${lastName[0]}`.toUpperCase()
      : firstName
        ? firstName[0].toUpperCase()
        : "U";

  useEffect(() => {
    const fetchProfile = async () => {
      try {
        const { success, data } = await getProfileAction();
        if (success && data) {
          const userData = data;
          setUser(userData);
          setFirstName(userData.first_name || "");
          setLastName(userData.last_name || "");
          setEmail(userData.email || "");
          // Use phone_number from User type
          setPhone(userData.phone_number || "");
          setAddress(userData.address || "");
        } else {
          // Fallback or redirect
          // router.push("/login") // Optional
        }
      } catch (error) {
        console.error("Failed to fetch profile", error);
        toast.error({
          title: "Error",
          description: "Failed to load profile data",
        });
      } finally {
        setIsLoading(false);
      }
    };

    fetchProfile();
  }, []);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsUpdating(true);

    try {
      console.log("[ManageProfile] Submitting profile update", {
        firstName,
        lastName,
        phone,
        address,
      });

      // Prepare form values (trim whitespace)
      const trimmedFirstName = firstName.trim();
      const trimmedLastName = lastName.trim();
      const trimmedPhone = phone.trim();
      const trimmedAddress = address.trim();

      // Merge form data with existing user data to ensure required fields are always present
      // Use form values if provided, otherwise fall back to existing user data
      const finalFirstName = trimmedFirstName || user?.first_name || "";
      const finalLastName = trimmedLastName || user?.last_name || "";
      const finalPhone = trimmedPhone || user?.phone_number || "";

      const updateData = {
        first_name: finalFirstName,
        last_name: finalLastName,
        phone_number: finalPhone,
        address: trimmedAddress || undefined,
      };

      console.log("[ManageProfile] Prepared update data", updateData);

      // Use Zod for robust validation
      const validation = customerProfileSchema.safeParse(updateData);

      if (!validation.success) {
        const firstError = validation.error.errors[0].message;
        console.warn(
          "[ManageProfile] Validation failed",
          validation.error.format()
        );
        toast.error({
          title: "Validation Error",
          description: firstError,
        });
        setIsUpdating(false);
        return;
      }

      console.log("[ManageProfile] Calling updateProfileAction");
      const result = await updateProfileAction(updateData);
      console.log("[ManageProfile] Update result", result);

      if (result.success) {
        toast.success({
          title: "Profile updated",
          description: "Your profile has been successfully updated.",
        });
        // Refresh profile data after successful update
        const { success, data } = await getProfileAction();
        if (success && data) {
          setUser(data);
          setFirstName(data.first_name || "");
          setLastName(data.last_name || "");
          setPhone(data.phone_number || "");
          setAddress(data.address || "");
        }
      } else {
        toast.error({
          title: "Error",
          description: result.error || "Failed to update profile",
        });
      }
    } catch (error) {
      console.error(error);
      toast.error({
        title: "Error",
        description: "An unexpected error occurred",
      });
    } finally {
      setIsUpdating(false);
    }
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        toast.error({
          title: "File too large",
          description: "Please select an image under 5MB",
        });
        return;
      }

      const reader = new FileReader();
      reader.onloadend = () => {
        setProfileImage(reader.result as string);
        toast.success({
          title: "Photo uploaded",
          description: "Your profile photo has been updated",
        });
      };
      reader.readAsDataURL(file);
      // Note: Actual upload logic requires updateProfile API support
    }
  };

  if (isLoading) {
    return (
      <div className="flex justify-center p-8">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-bold text-balance">Manage Profile</h1>
        <p className="text-muted-foreground mt-1">
          Update your personal information
        </p>
      </header>

      <Card className="shadow-md">
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">Profile Photo</CardTitle>
          <CardDescription>Upload your profile picture</CardDescription>
        </CardHeader>
        <CardContent className="pb-6">
          <div className="flex items-center gap-4">
            <Avatar className="h-24 w-24 border-2 border-primary/20">
              {profileImage ? (
                <AvatarImage
                  src={profileImage || "/placeholder.png"}
                  alt="Profile"
                />
              ) : (
                <AvatarFallback className="bg-primary/10 text-primary font-semibold text-2xl">
                  {userInitials}
                </AvatarFallback>
              )}
            </Avatar>
            <div className="flex flex-col gap-2">
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleImageChange}
                className="hidden"
                aria-label="Upload profile photo"
              />
              <Button
                type="button"
                variant="outline"
                onClick={() => fileInputRef.current?.click()}
                className="gap-2"
              >
                <Upload className="h-4 w-4" />
                Upload Photo
              </Button>
              <p className="text-xs text-muted-foreground">
                JPG, PNG or GIF. Max 5MB
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card className="shadow-md">
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">Personal Information</CardTitle>
          <CardDescription>Update your profile details here</CardDescription>
        </CardHeader>
        <CardContent className="pb-6">
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="firstName">First Name</Label>
                <Input
                  id="firstName"
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  disabled={isUpdating}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="lastName">Last Name</Label>
                <Input
                  id="lastName"
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  disabled={isUpdating}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" type="email" value={email} disabled />
              <p className="text-xs text-muted-foreground">
                Email cannot be changed
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="phone">Phone Number</Label>
              <Input
                id="phone"
                type="tel"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                placeholder="+91 9876543210"
                disabled={isUpdating}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="address">Address</Label>
              <Input
                id="address"
                type="text"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                placeholder="Enter your address"
                disabled={isUpdating}
              />
            </div>

            <Button
              type="submit"
              disabled={isUpdating}
              className="w-full md:w-auto"
            >
              {isUpdating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {isUpdating ? "Saving..." : "Save Changes"}
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Keep the Change Password section mostly purely UI for now unless we implement handlePasswordChange similarly */}
      <Card className="shadow-md">
        <CardHeader className="pb-4">
          <CardTitle className="text-lg">Change Password</CardTitle>
          <CardDescription>
            Update your password to keep your account secure
          </CardDescription>
        </CardHeader>
        <CardContent className="pb-6">
          <form
            className="space-y-4"
            onSubmit={(e) => {
              e.preventDefault();
              toast.info({
                title: "Info",
                description: "Password change not implemented in this view yet",
              });
            }}
          >
            <div className="space-y-2">
              <Label htmlFor="current-password">Current Password</Label>
              <Input id="current-password" type="password" />
            </div>

            <div className="space-y-2">
              <Label htmlFor="new-password">New Password</Label>
              <Input id="new-password" type="password" />
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirm-password">Confirm New Password</Label>
              <Input id="confirm-password" type="password" />
            </div>

            <Button
              type="submit"
              variant="outline"
              className="w-full md:w-auto bg-transparent"
            >
              Update Password
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
