"use client";

import { useState } from "react";
import { UserIcon } from "@heroicons/react/24/outline";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { PageLayout } from "@/components/templates";
import { useAuthStore } from "@/features/auth/stores/auth.store";
import { useProfileDataLoading } from "@/features/account/hooks";
import {
  useResidenceCardVerification,
  useVerificationFileUpload,
} from "@/features/verification/hooks";
import {
  PersonalInfoCard,
  AddressCard,
  VerificationCard,
  ProfileLoadingSkeleton,
} from "@/features/account/components";

export default function ProfileContainer() {
  const { user } = useAuthStore();
  const [editingProfile, setEditingProfile] = useState(false);
  const [editingAddress, setEditingAddress] = useState(false);

  const { isLoading, error, reload, profile, address } = useProfileDataLoading({
    email: user?.email || "",
    phonenumber: user?.phonenumber || "",
  });

  const verificationQuery = useResidenceCardVerification();
  const fileUpload = useVerificationFileUpload({
    verificationStatus: verificationQuery.data?.status,
  });

  if (isLoading) {
    return (
      <PageLayout
        icon={<UserIcon />}
        title="Profile"
        description="Manage your account information"
        loading
      >
        <ProfileLoadingSkeleton />
      </PageLayout>
    );
  }

  return (
    <PageLayout
      icon={<UserIcon />}
      title="Profile"
      description="Manage your account information"
      error={error}
      onRetry={reload}
    >
      {error && (
        <AlertBanner variant="error" title="Unable to load profile" className="mb-6" elevated>
          {error}
        </AlertBanner>
      )}

      <PersonalInfoCard
        data={{
          firstname: user?.firstname ?? null,
          lastname: user?.lastname ?? null,
          email: user?.email ?? "",
          phonenumber: user?.phonenumber ?? null,
          sfNumber: user?.sfNumber ?? null,
          dateOfBirth: user?.dateOfBirth ?? null,
          gender: user?.gender ?? null,
        }}
        editEmail={profile.values.email ?? ""}
        editPhoneNumber={profile.values.phonenumber ?? ""}
        isEditing={editingProfile}
        isSaving={profile.isSubmitting}
        onEdit={() => setEditingProfile(true)}
        onCancel={() => setEditingProfile(false)}
        onChange={(field, value) => profile.setValue(field, value)}
        onSave={() => {
          void profile
            .handleSubmit()
            .then(() => {
              setEditingProfile(false);
            })
            .catch(() => {
              // Error is handled by useZodForm
            });
        }}
      />

      <AddressCard
        address={{
          address1: address.values.address1,
          address2: address.values.address2,
          city: address.values.city,
          state: address.values.state,
          postcode: address.values.postcode,
          country: address.values.country,
          countryCode: address.values.countryCode,
          phoneNumber: address.values.phoneNumber,
          phoneCountryCode: address.values.phoneCountryCode,
        }}
        isEditing={editingAddress}
        isSaving={address.isSubmitting}
        error={address.submitError}
        onEdit={() => setEditingAddress(true)}
        onCancel={() => setEditingAddress(false)}
        onAddressChange={a => {
          address.setValue("address1", a.address1 ?? "");
          address.setValue("address2", a.address2 ?? "");
          address.setValue("city", a.city ?? "");
          address.setValue("state", a.state ?? "");
          address.setValue("postcode", a.postcode ?? "");
          address.setValue("country", a.country ?? "");
          address.setValue("countryCode", a.countryCode ?? "");
          address.setValue("phoneNumber", a.phoneNumber ?? "");
          address.setValue("phoneCountryCode", a.phoneCountryCode ?? "");
        }}
        onSave={() => {
          void address
            .handleSubmit()
            .then(() => {
              setEditingAddress(false);
            })
            .catch(() => {
              // Error is handled by useZodForm
            });
        }}
      />

      <VerificationCard verificationQuery={verificationQuery} fileUpload={fileUpload} />
    </PageLayout>
  );
}
