I am building an application in Next.js, TailwindCSS, Appwrite, and Zustand. So now I want you to fix all my bugs and optmize this code

"use client";
import React, { useState, useEffect, useCallback, useRef } from "react";
import {
  FaBriefcase,
  FaPlus,
  FaPaperPlane,
  FaCheck,
  FaSquare,
  FaChevronDown,
  FaChevronUp,
} from "react-icons/fa";
import useProfileStore from "../../../store/profileStore";
import useUserStore from "../../../store/userStore";
import useResumeProjectStore from "../../../store/resumeProjectStore";
import useDocumentViewStore from "../../../store/documentViewStore";
import ProfileForm from "../../dashboard-component/ProfileForm";
import Button from "./ButtonCV";
import Modal from "./ModalCV";
import ChatBubble from "./ChatBubbleCV";

const SECTIONS = [
  "summary",
  "experience",
  "skills",
  "education",
  "certifications",
  "projects",
  "languages",
  "awards",
];

export default function ChatView() {
  const { user } = useUserStore();
  const { userProfiles, fetchProfiles, createProfile } = useProfileStore();
  const { currentProject, updateProject } = useResumeProjectStore();
  const { setCurrentResume, setCurrentCoverLetter, setCurrentEmail } =
    useDocumentViewStore();

  const [selectedProfile, setSelectedProfile] = useState("");
  const [jobDescription, setJobDescription] = useState("");
  const [chatInput, setChatInput] = useState("");
  const [isProfileJobModalOpen, setIsProfileJobModalOpen] = useState(false);
  const [isCreateProfileModalOpen, setIsCreateProfileModalOpen] =
    useState(false);
  const [selectedOptions, setSelectedOptions] = useState({
    resume: false,
    cover: false,
    email: false,
  });
  const [isGenerating, setIsGenerating] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const [resumeGenerated, setResumeGenerated] = useState(false);
  const [isRegenerateOpen, setIsRegenerateOpen] = useState(false);
  const [selectedSections, setSelectedSections] = useState({});

  const [initialMessageShown, setInitialMessageShown] = useState(false);

  const chatContainerRef = useRef(null);

  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop =
        chatContainerRef.current.scrollHeight;
    }
  };

  useEffect(() => {
    if (user) {
      fetchProfiles(user.$id);
    }
  }, [user, fetchProfiles]);

  useEffect(() => {
    if (currentProject) {
      setSelectedProfile(currentProject.profileId || "");
      setJobDescription(currentProject.jobDescription || "");
      if (
        currentProject.resume &&
        Object.keys(currentProject.resume).length > 0
      ) {
        setResumeGenerated(true);
      } else {
        setResumeGenerated(false);
      }

          // Add this condition
    if (currentProject.chatHistory.length === 0 && !initialMessageShown) {
      setInitialMessageShown(true);
    }
    }

  }, [currentProject, initialMessageShown]);

  useEffect(() => {
    scrollToBottom();
  }, [currentProject?.chatHistory]);

  const toggleOption = useCallback((option) => {
    setSelectedOptions((prev) => ({ ...prev, [option]: !prev[option] }));
  }, []);

  const handleCreateProfile = async (profileData) => {
    if (user) {
      try {
        await createProfile(user.$id, profileData);
        setIsCreateProfileModalOpen(false);
        fetchProfiles(user.$id, true);
      } catch (error) {
        console.error("Error creating profile:", error);
      }
    }
  };

  const handleSaveProfileAndJob = async () => {
    if (user && currentProject) {
      try {
        await updateProject(user.$id, currentProject.id, {
          profileId: selectedProfile,
          jobDescription,
        });
        setIsProfileJobModalOpen(false);
      } catch (error) {
        console.error("Error updating project:", error);
      }
    }
  };

  const generateContent = async (type, profile, jobDescription) => {
    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type, profile, jobDescription }),
      });
      const data = await response.json();
      if (!response.ok)
        throw new Error(data.error || "Failed to generate content");

      const updatedChatHistory = [
        ...currentProject.chatHistory,
        { type: "system", content: `Generated ${type} successfully.` },
      ];
      await updateProject(user.$id, currentProject.id, {
        [type === "resume"
          ? "resume"
          : type === "cover"
          ? "coverLetter"
          : "email"]: data.result,
        chatHistory: updatedChatHistory,
      });

      if (type === "resume") {
        setCurrentResume(data.result);
        setResumeGenerated(true);
      } else if (type === "cover") {
        setCurrentCoverLetter(data.result);
      } else if (type === "email") {
        setCurrentEmail(data.result);
      }

      return data.result;
    } catch (error) {
      console.error(`Error generating ${type}:`, error);
      await updateProject(user.$id, currentProject.id, {
        chatHistory: [
          ...currentProject.chatHistory,
          {
            type: "system",
            content: `Error generating ${type}: ${error.message}`,
          },
        ],
      });
      throw error;
    }
  };

  const handleGenerate = async () => {
    if (!selectedProfile || !jobDescription) {
      alert("Please select a profile and enter a job description first.");
      return;
    }
    setIsGenerating(true);
    setResumeGenerated(false);
    const profile = userProfiles.find((p) => p.id === selectedProfile);
    const types = Object.entries(selectedOptions)
      .filter(([_, isSelected]) => isSelected)
      .map(([type]) => type);

    for (const type of types) {
      try {
        await generateContent(type, profile, jobDescription);
      } catch (error) {
        console.error(`Error generating ${type}:`, error);
      }
    }
    setIsGenerating(false);
  };

  const handleSendMessage = async () => {
    if (!chatInput.trim()) return;
    setIsSending(true);
    let message = chatInput.trim();
    setChatInput("");

    const sectionsToRegenerate = Object.entries(selectedSections)
      .filter(([_, isSelected]) => isSelected)
      .map(([section]) => section);

    try {
      const newUserMessage = { type: "user", content: message };
      const updatedChatHistory = [
        ...currentProject.chatHistory,
        newUserMessage,
      ];

      await updateProject(user.$id, currentProject.id, {
        chatHistory: updatedChatHistory,
      });

      let apiEndpoint = "/api/resume";
      let apiBody = {
        action: "chat",
        message,
        chatHistory: updatedChatHistory,
        resume: currentProject.resume,
        jobDescription: currentProject.jobDescription,
      };

      if (sectionsToRegenerate.length > 0) {
        const originalSections = sectionsToRegenerate.reduce((acc, section) => {
          acc[section] = currentProject.resume.sections[section];
          return acc;
        }, {});

        apiBody = {
          action: "regenerate",
          selectedSections: sectionsToRegenerate,
          profile: userProfiles.find((p) => p.id === selectedProfile),
          jobDescription: currentProject.jobDescription,
          currentResume: currentProject.resume,
          message,
          originalSections,
        };
      }

      const response = await fetch(apiEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(apiBody),
      });

      if (!response.ok) throw new Error("Failed to get response");
      const data = await response.json();

      let newAssistantMessage;
      if (sectionsToRegenerate.length > 0) {
        await updateProject(user.$id, currentProject.id, {
          resume: data.result,
        });
        setCurrentResume(data.result);
        newAssistantMessage = { type: "assistant", content: data.reply };
      } else {
        newAssistantMessage = { type: "assistant", content: data.reply };
      }

      await updateProject(user.$id, currentProject.id, {
        chatHistory: [...updatedChatHistory, newAssistantMessage],
      });

      scrollToBottom();
    } catch (error) {
      console.error("Error sending message:", error);
    } finally {
      setIsSending(false);
      setSelectedSections({});
      setIsRegenerateOpen(false);
    }
  };

  const handleSectionSelect = (section) => {
    setSelectedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  return (
    <div className="flex flex-col h-full relative">
      {/* Chat history */}
      <div ref={chatContainerRef} className="flex-1 overflow-y-auto p-4">
  {initialMessageShown && (
    <ChatBubble
      message={{ type: "assistant", content: "initial" }}
      isInitialMessage={true}
      showRegenerate={false}
    />
  )}
  {currentProject?.chatHistory.map((message, index) => (
    <ChatBubble
      key={index}
      message={message}
      isInitialMessage={false}
      showRegenerate={false}
    />
  ))}
  {isGenerating && (
    <ChatBubble
      message={{ type: "assistant", content: "Generating..." }}
      isLoading={true}
      showRegenerate={false}
    />
  )}
</div>

      {/* Regenerate section */}
      {resumeGenerated && (
        <div className="bg-gray-50 border-t border-gray-200 p-3">
          <button
            className="text-indigo-600 font-semibold flex items-center"
            onClick={() => setIsRegenerateOpen((prev) => !prev)}
          >
            {isRegenerateOpen ? (
              <FaChevronUp className="mr-1" />
            ) : (
              <FaChevronDown className="mr-1" />
            )}
            Regenerate Sections
          </button>
          {isRegenerateOpen && (
            <div className="mt-2">
              <div className="flex flex-wrap gap-2">
                {SECTIONS.map((section) => (
                  <button
                    key={section}
                    onClick={() => handleSectionSelect(section)}
                    className={`text-xs px-3 py-1.5 rounded-md flex items-center ${
                      selectedSections[section]
                        ? "bg-indigo-600 text-white hover:bg-indigo-700"
                        : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                    }`}
                  >
                    {selectedSections[section] ? (
                      <FaCheck className="mr-1.5" />
                    ) : (
                      <FaSquare className="mr-1.5 rounded-md" />
                    )}
                    {section.charAt(0).toUpperCase() + section.slice(1)}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Options */}
      <div className="bg-gray-50 border-t border-gray-200 p-3">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <Button
            onClick={() => setIsProfileJobModalOpen(true)}
            className="text-xs px-3 py-1.5 flex items-center"
          >
            <FaBriefcase className="mr-1.5" /> Set Profile & Job
          </Button>
          <div className="flex flex-wrap gap-2">
            {["resume", "cover", "email"].map((option) => (
              <button
                key={option}
                onClick={() => toggleOption(option)}
                className={`text-xs px-3 py-1.5 rounded-md flex items-center ${
                  selectedOptions[option]
                    ? "bg-indigo-600 text-white hover:bg-indigo-700"
                    : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                }`}
              >
                {selectedOptions[option] ? (
                  <FaCheck className="mr-1.5" />
                ) : (
                  <FaSquare className="mr-1.5 rounded-md" />
                )}
                {option === "cover"
                  ? "Cover Letter"
                  : option.charAt(0).toUpperCase() + option.slice(1)}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Input area */}
      <div className="bg-white border-t border-gray-200 p-4">
        <div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
          <input
            type="text"
            value={chatInput}
            onChange={(e) => setChatInput(e.target.value)}
            placeholder="Type your message..."
            className="flex-grow px-4 py-2 text-sm text-gray-700 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-600"
            onKeyDown={(e) => {
              if (e.key === "Enter") handleSendMessage();
            }}
          />
          <div className="flex space-x-2">
            <Button
              onClick={handleSendMessage}
              className="flex-grow sm:flex-grow-0"
              disabled={!chatInput.trim() || isSending}
            >
              <FaPaperPlane className="mr-2" />{" "}
              {isSending ? "Sending..." : "Send"}
            </Button>
            <Button
              onClick={handleGenerate}
              className="flex-grow sm:flex-grow-0 bg-green-600 hover:bg-green-700 focus:ring-green-600"
              disabled={
                isGenerating ||
                !selectedProfile ||
                !jobDescription ||
                !Object.values(selectedOptions).some(Boolean)
              }
            >
              {isGenerating ? "Generating..." : "Generate"}
            </Button>
          </div>
        </div>
      </div>

      {/* Modals */}
      <Modal
        isOpen={isProfileJobModalOpen}
        onClose={() => setIsProfileJobModalOpen(false)}
        title="Set Profile & Job Description"
      >
        <div className="space-y-4">
          <div>
            <label
              htmlFor="profile"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Select a Profile
            </label>
            {userProfiles && userProfiles.length > 0 ? (
              <select
                id="profile"
                value={selectedProfile}
                onChange={(e) => setSelectedProfile(e.target.value)}
                className="w-full px-3 py-2 text-sm text-gray-700 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-600"
              >
                <option value="">Select a profile</option>
                {userProfiles.map((profile) => (
                  <option key={profile.id} value={profile.id}>
                    {profile.profileName}
                  </option>
                ))}
              </select>
            ) : (
              <div className="text-sm text-gray-500">
                No profiles found. Please create a profile.
              </div>
            )}
            <Button
              onClick={() => setIsCreateProfileModalOpen(true)}
              className="mt-2"
            >
              <FaPlus className="mr-2" /> Create New Profile
            </Button>
          </div>
          <div>
            <label
              htmlFor="jobDescription"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Job Description
            </label>
            <textarea
              id="jobDescription"
              value={jobDescription}
              onChange={(e) => setJobDescription(e.target.value)}
              placeholder="Paste job description here..."
              className="w-full px-3 py-2 text-sm text-gray-700 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-600"
              rows="6"
            ></textarea>
          </div>
          <div className="flex justify-end">
            <Button onClick={handleSaveProfileAndJob}>
              <FaCheck className="mr-2" /> Confirm
            </Button>
          </div>
        </div>
      </Modal>

      <Modal
        isOpen={isCreateProfileModalOpen}
        onClose={() => setIsCreateProfileModalOpen(false)}
        title="Create New Profile"
      >
        <ProfileForm onSubmit={handleCreateProfile} />
      </Modal>
    </div>
  );
}