/**
 * Example: Manage Profile Content Component
 * Demonstrates proper usage of updateProfileAction with files
 *
 * IMPORTANT NOTES:
 * 1. Files passed through Server Actions are serialized (lose File nature)
 * 2. For production file uploads, consider direct client-to-API calls
 * 3. This example shows both approaches
 */

"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import {
  getProfileAction,
  updateProfileAction,
} from "@/features/users/actions/profile-actions";
import { profileService } from "@/core/api";
import type { User } from "@/core/api";

export function ManageProfileContentExample() {
  const [user, setUser] = useState<User | null>(null);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [isUpdating, setIsUpdating] = useState(false);
  const toast = useToastEnhanced();

  // Load profile on mount
  useEffect(() => {
    const loadProfile = async () => {
      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 || "");
      }
    };
    loadProfile();
  }, []);

  /**
   * APPROACH 1: Update via Server Action (works for text fields)
   * Files may not work perfectly due to Server Action serialization
   */
  const handleSubmitViaServerAction = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsUpdating(true);

    try {
      const result = await updateProfileAction({
        first_name: firstName.trim() || user?.first_name || "",
        last_name: lastName.trim() || user?.last_name || "",
        phone_number: phone.trim() || user?.phone_number || "",
        address: address.trim() || undefined,
      });

      if (result.success) {
        toast.success({
          title: "Profile updated",
          description: "Your profile has been successfully updated.",
        });
        // Refresh profile
        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);
    }
  };

  /**
   * APPROACH 2: Direct API call for file uploads (bypasses Server Actions)
   * This is the recommended approach for file uploads
   */
  const handleFileUpload = async (
    file: File,
    fieldName: "gst_certificate" | "msme_certificate" | "business_document"
  ) => {
    setIsUpdating(true);

    try {
      // Get current profile first
      const currentProfile = user || (await profileService.getProfile());

      if (!currentProfile) {
        toast.error({ title: "Error", description: "Profile not found" });
        return;
      }

      // Build FormData with all required fields + new file
      const formData = new FormData();
      formData.append("first_name", currentProfile.first_name || "");
      formData.append("last_name", currentProfile.last_name || "");
      formData.append("phone_number", currentProfile.phone_number || "");
      if (currentProfile.address) {
        formData.append("address", currentProfile.address);
      }
      if (currentProfile.office_address) {
        formData.append("office_address", currentProfile.office_address);
      }

      // Add the new file
      formData.append(fieldName, file);

      // Direct API call (bypasses Server Actions)
      const token = localStorage.getItem("teertham_auth_token");
      await profileService.updateProfile(
        {
          first_name: currentProfile.first_name || "",
          last_name: currentProfile.last_name || "",
          phone_number: currentProfile.phone_number || "",
          address: currentProfile.address || undefined,
          [fieldName]: file, // File object passed directly
        },
        token || undefined
      );

      toast.success({
        title: "File uploaded",
        description: "Your document has been uploaded successfully.",
      });

      // Refresh profile
      const { success, data } = await getProfileAction();
      if (success && data) {
        setUser(data);
      }
    } catch (error) {
      console.error(error);
      toast.error({
        title: "Error",
        description: "Failed to upload file",
      });
    } finally {
      setIsUpdating(false);
    }
  };

  return (
    <form onSubmit={handleSubmitViaServerAction} className="space-y-4">
      <div>
        <Label htmlFor="firstName">First Name</Label>
        <Input
          id="firstName"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
          disabled={isUpdating}
          required
        />
      </div>

      <div>
        <Label htmlFor="lastName">Last Name</Label>
        <Input
          id="lastName"
          value={lastName}
          onChange={(e) => setLastName(e.target.value)}
          disabled={isUpdating}
          required
        />
      </div>

      <div>
        <Label htmlFor="phone">Phone Number</Label>
        <Input
          id="phone"
          type="tel"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          disabled={isUpdating}
          required
        />
      </div>

      <div>
        <Label htmlFor="address">Address</Label>
        <Input
          id="address"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          disabled={isUpdating}
        />
      </div>

      {/* File upload example */}
      <div>
        <Label htmlFor="gstCertificate">GST Certificate</Label>
        <Input
          id="gstCertificate"
          type="file"
          accept=".pdf,.jpg,.jpeg,.png"
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) {
              handleFileUpload(file, "gst_certificate");
            }
          }}
          disabled={isUpdating}
        />
      </div>

      <Button type="submit" disabled={isUpdating}>
        {isUpdating ? "Saving..." : "Save Changes"}
      </Button>
    </form>
  );
}
