// app/dashboard/users/[userId]/page.tsx

"use client";

import React from "react";
import { use } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { MessageSquare } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ConfirmationDialog } from "@/components/layout/ConfirmationDialog";
import { Trash2 } from "lucide-react";

// Custom hooks
import { useUserDetails } from "./hooks/useUserDetails";
import { useMessageSending } from "./hooks/useMessageSending";

// Components
import { UserInfoCard } from "./components/UserInfoCard";
import { UserHeader } from "./components/UserHeader";
import { ConversationHistory } from "./components/ConversationHistory";
import { MessageInput } from "./components/MessageInput";
import { LoadingState } from "./components/LoadingState";

export default function UserDetailPage({ params }: { params: Promise<{ userId: string }> }) {
  // Use React.use to properly handle the Promise-based params in Next.js 15
  const { userId } = use(params);

  // Use custom hooks
  const {
    user,
    isLoading,
    conversations,
    deleteDialogOpen,
    isDeleting,
    setDeleteDialogOpen,
    handleDeleteUser,
    handleRespondentChange,
    fetchUser,
    refreshConversations,
    setConversations
  } = useUserDetails(userId);

  // Helper function to update conversations
  const updateConversations = (updatedConversation: Conversation) => {
    setConversations(prevConversations => {
      const existingIndex = prevConversations.findIndex(
        conv => conv.id === updatedConversation.id
      );

      if (existingIndex >= 0) {
        // Update existing conversation
        return prevConversations.map(conv =>
          conv.id === updatedConversation.id ? updatedConversation : conv
        );
      } else {
        // Add new conversation
        return [...prevConversations, updatedConversation];
      }
    });
  };

  const {
    newMessage,
    setNewMessage,
    isSending,
    handleSendMessage
  } = useMessageSending(userId, conversations, user, updateConversations);

  if (isLoading) {
    return <LoadingState />;
  }

  if (!user) {
    return (
      <div className="container mx-auto py-8" dir="rtl">
        <div className="flex justify-center items-center h-[400px]">
          <div className="text-center">
            <h2 className="text-2xl font-bold mb-2">کاربر پیدا نشد</h2>
            <p className="text-muted-foreground mb-4">
              کاربری که به دنبال آن هستید وجود ندارد یا حذف شده است.
            </p>
            <Button onClick={() => location.href = "/dashboard/users"}>
              بازگشت به کاربران
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8" dir="rtl">
      <UserHeader
        user={user}
        onDelete={() => setDeleteDialogOpen(true)}
        onRefresh={fetchUser}
      />

      <div className="grid md:grid-cols-12 gap-6">
        <UserInfoCard
          user={user}
          handleRespondentChange={handleRespondentChange}
        />

        <Card className="md:col-span-9">
          <CardHeader className="pb-2 border-b">
            <CardTitle className="flex items-center gap-2">
              <MessageSquare className="h-5 w-5" />
              تاریخچه مکالمات
            </CardTitle>
            <CardDescription>
              کل مکالمات: {user._count?.conversations || 0}
            </CardDescription>
          </CardHeader>
          <CardContent className="p-4">
            <ConversationHistory
              conversations={conversations}
              isLoading={isLoading}
              refreshData={refreshConversations}
              userId={userId}
            />
          </CardContent>

          <MessageInput
            newMessage={newMessage}
            setNewMessage={setNewMessage}
            handleSendMessage={handleSendMessage}
            isSending={isSending}
            isDisabled={user.respondent !== "admin"}
            placeholderText={user.respondent === "admin"
              ? "پیام خود را بنویسید..."
              : "برای ارسال پیام دستی، حالت پاسخ‌دهنده را به «دستی» تغییر دهید"}
          />
        </Card>
      </div>

      <ConfirmationDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        title="آیا کاملاً مطمئن هستید؟"
        description={
          <span>
            این کار به طور دائم کاربر <strong>{user.firstName} {user.lastName}</strong> و تمام مکالمات و پیام‌های مرتبط با او را حذف خواهد کرد.
            این عمل قابل بازگشت نیست.
          </span>
        }
        confirmText="حذف"
        cancelText="لغو"
        onConfirm={handleDeleteUser}
        confirmIcon={<Trash2 className="h-4 w-4" />}
        isLoading={isDeleting}
        loadingText="در حال حذف..."
        variant="destructive"
      />
    </div>
  );
}