"use client";
import React, { useState } from "react";
import { PageProps } from "@/components/validations/translations/translation";
import { useApplicationData } from "./hooks";
import { ApplicationData, translations } from "./types";
import { SearchComponent } from "./SearchComponent";
import { ActionButtonsComponent } from "./ActionButtonsComponent";
import { SortingComponent } from "./SortingComponent";
import { PaginationToolsComponent } from "./PaginationToolsComponent";
import { DataDisplayComponent } from "./DataDisplayComponent";
import { FormComponent } from "./FormComponent";

const ApplicationPage: React.FC<PageProps> = ({ lang = "en" }) => {
  // Use the custom hook for paginated data
  const { data, pagination, loading, error, updatePagination, refetch } =
    useApplicationData();

  // State for managing view/edit modes
  const [mode, setMode] = useState<"list" | "create" | "update">("list");
  const [selectedItem, setSelectedItem] = useState<ApplicationData | null>(
    null
  );

  // State for sorting
  const [sortField, setSortField] = useState<string | null>(null);
  const [sortDirection, setSortDirection] = useState<"asc" | "desc" | null>(
    null
  );

  // Available options for dropdowns
  const urlOptions = [
    "/dashboard",
    "/individual",
    "/user",
    "/settings",
    "/reports",
  ];

  const handleUpdateClick = (item: ApplicationData) => {
    setSelectedItem(item);
    setMode("update");
  };

  // Function to handle the create button click
  const handleCreateClick = () => {
    setSelectedItem(null);
    setMode("create");
  };

  // Handle search from the SearchComponent
  const handleSearch = (query: Record<string, string>) => {
    updatePagination({
      page: 1, // Reset to first page on new search
      query: query,
    });
  };

  // Handle sorting
  const handleSort = (field: string) => {
    let direction: "asc" | "desc" | null = "asc";

    if (sortField === field) {
      // Toggle direction if same field is clicked
      if (sortDirection === "asc") {
        direction = "desc";
      } else if (sortDirection === "desc") {
        // Clear sorting if already desc
        field = "";
        direction = null;
      }
    }

    setSortField(field || null);
    setSortDirection(direction);

    updatePagination({
      orderField: field ? [field] : [],
      orderType: direction ? [direction] : [],
    });
  };

  return (
    <div className="container mx-auto px-4 py-6">
      {/* List Mode - Show search, actions, and data display */}
      {mode === "list" && (
        <>
          {/* Search Component */}
          <SearchComponent
            onSearch={handleSearch}
            translations={translations}
            lang={lang}
            urlOptions={urlOptions}
          />

          {/* Action Buttons Component */}
          <ActionButtonsComponent
            onCreateClick={handleCreateClick}
            translations={translations}
            lang={lang}
          />

          {/* Sorting Component */}
          <SortingComponent
            sortField={sortField}
            sortDirection={sortDirection}
            onSort={handleSort}
            translations={translations}
            lang={lang}
          />

          {/* Data Display Component */}
          <div className="mt-6">
            <DataDisplayComponent
              data={data}
              loading={loading}
              error={error}
              onUpdateClick={handleUpdateClick}
              translations={translations}
              lang={lang}
            />
          </div>

          {/* Pagination Tools Component */}
          <div className="mt-4">
            <PaginationToolsComponent
              pagination={pagination}
              updatePagination={updatePagination}
              loading={loading}
              lang={lang}
            />
          </div>
        </>
      )}

      {/* Form Mode - Show create/update/view form */}
      {mode !== "list" && (
        <FormComponent
          initialData={selectedItem || undefined}
          mode={mode}
          refetch={refetch}
          setMode={setMode}
          setSelectedItem={setSelectedItem}
          onCancel={() => setMode("list")}
          lang={lang}
        />
      )}
    </div>
  );
};

export default ApplicationPage;
