"use client";

import { useState, useEffect } from "react";
import {
  getProfileAction,
  updateProfileAction,
  changePasswordAction,
  type UpdateProfileRequest,
  type ChangePasswordRequest,
} from "@/features/users";
import type { User } from "@/core/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

export default function TestProfilePage() {
  const [profile, setProfile] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Profile form state
  const [profileForm, setProfileForm] = useState({
    first_name: "",
    last_name: "",
    phone: "",
    office_address: "",
  });

  // File state
  const [files, setFiles] = useState<{
    gst_certificate: File | null;
    msme_certificate: File | null;
    business_document: File | null;
  }>({
    gst_certificate: null,
    msme_certificate: null,
    business_document: null,
  });

  // Password form state
  const [passwordForm, setPasswordForm] = useState<ChangePasswordRequest>({
    password: "",
    new_password: "",
    new_password_confirmation: "",
  });

  // Load profile
  const loadProfile = async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await getProfileAction();
      if (result.success && result.data) {
        setProfile(result.data);
        setProfileForm({
          first_name: result.data.first_name,
          last_name: result.data.last_name,
          phone: result.data.phone_number || "",
          office_address: result.data.office_address || "",
        });
      } else {
        setError(result.error || "Failed to load profile");
      }
    } catch {
      setError("An error occurred");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProfile();
  }, []);

  // Update profile
  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setSuccess(null);

    try {
      const updateData: UpdateProfileRequest = {
        ...profileForm,
        ...files,
      };

      const result = await updateProfileAction(updateData);
      if (result.success) {
        setSuccess("Profile updated successfully!");
        await loadProfile();
      } else {
        setError(result.error || "Update failed");
      }
    } catch {
      setError("An error occurred");
    } finally {
      setLoading(false);
    }
  };

  // Change password
  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setSuccess(null);

    try {
      const result = await changePasswordAction(passwordForm);
      if (result.success) {
        setSuccess("Password changed successfully!");
        setPasswordForm({
          password: "",
          new_password: "",
          new_password_confirmation: "",
        });
      } else {
        setError(result.error || "Password change failed");
      }
    } catch {
      setError("An error occurred");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto p-8 max-w-4xl">
      <h1 className="text-3xl font-bold mb-8">Profile API Test</h1>

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          {error}
        </div>
      )}

      {success && (
        <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
          {success}
        </div>
      )}

      {/* Current Profile */}
      <Card className="mb-8">
        <CardHeader>
          <CardTitle>Current Profile</CardTitle>
        </CardHeader>
        <CardContent>
          {loading && <p>Loading...</p>}
          {profile && (
            <div className="space-y-2">
              <p>
                <strong>Name:</strong> {profile.first_name} {profile.last_name}
              </p>
              <p>
                <strong>Email:</strong> {profile.email}
              </p>
              <p>
                <strong>Phone:</strong> {profile.phone_number || "N/A"}
              </p>
              <p>
                <strong>Office Address:</strong>{" "}
                {profile.office_address || "N/A"}
              </p>
              <p>
                <strong>Status:</strong> {profile.status}
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Update Profile Form */}
      <Card className="mb-8">
        <CardHeader>
          <CardTitle>Update Profile</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleUpdateProfile} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium mb-1">
                  First Name
                </label>
                <Input
                  value={profileForm.first_name}
                  onChange={(e) =>
                    setProfileForm({
                      ...profileForm,
                      first_name: e.target.value,
                    })
                  }
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">
                  Last Name
                </label>
                <Input
                  value={profileForm.last_name}
                  onChange={(e) =>
                    setProfileForm({
                      ...profileForm,
                      last_name: e.target.value,
                    })
                  }
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">Phone</label>
              <Input
                value={profileForm.phone}
                onChange={(e) =>
                  setProfileForm({ ...profileForm, phone: e.target.value })
                }
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                Office Address
              </label>
              <Input
                value={profileForm.office_address}
                onChange={(e) =>
                  setProfileForm({
                    ...profileForm,
                    office_address: e.target.value,
                  })
                }
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                GST Certificate
              </label>
              <Input
                type="file"
                onChange={(e) =>
                  setFiles({
                    ...files,
                    gst_certificate: e.target.files?.[0] || null,
                  })
                }
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                MSME Certificate
              </label>
              <Input
                type="file"
                onChange={(e) =>
                  setFiles({
                    ...files,
                    msme_certificate: e.target.files?.[0] || null,
                  })
                }
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                Business Document
              </label>
              <Input
                type="file"
                onChange={(e) =>
                  setFiles({
                    ...files,
                    business_document: e.target.files?.[0] || null,
                  })
                }
              />
            </div>

            <Button type="submit" disabled={loading}>
              Update Profile
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Change Password Form */}
      <Card>
        <CardHeader>
          <CardTitle>Change Password</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleChangePassword} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">
                Current Password
              </label>
              <Input
                type="password"
                value={passwordForm.password}
                onChange={(e) =>
                  setPasswordForm({ ...passwordForm, password: e.target.value })
                }
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                New Password
              </label>
              <Input
                type="password"
                value={passwordForm.new_password}
                onChange={(e) =>
                  setPasswordForm({
                    ...passwordForm,
                    new_password: e.target.value,
                  })
                }
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                Confirm New Password
              </label>
              <Input
                type="password"
                value={passwordForm.new_password_confirmation}
                onChange={(e) =>
                  setPasswordForm({
                    ...passwordForm,
                    new_password_confirmation: e.target.value,
                  })
                }
                required
              />
            </div>

            <Button type="submit" disabled={loading}>
              Change Password
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
