"use client"

import React, { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ArrowLeft, Send, RefreshCw, Search, User } from "lucide-react";
import { toast } from "sonner";
import { clientFetch } from "@/lib/client-utils";
import debounce from "lodash/debounce";

interface User {
  telegramUserId: string;
  telegramUsername: string | null;
}

interface Store {
  _id: string;
  name: string;
}

export default function NewChatForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  // State management
  const [buyerId, setBuyerId] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState<User[]>([]);
  const [initialMessage, setInitialMessage] = useState("");
  const [vendorStores, setVendorStores] = useState<Store[]>([]);
  const [selectedStore, setSelectedStore] = useState<string>("");
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  
  // Loading states
  const [searching, setSearching] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loadingUser, setLoadingUser] = useState(false);
  const [loadingStores, setLoadingStores] = useState(false);
  
  // UI state
  const [open, setOpen] = useState(false);
  
  // Parse URL parameters for buyerId and fetch user details if present
  useEffect(() => {
    const buyerIdParam = searchParams.get('buyerId');
    if (buyerIdParam) {
      setBuyerId(buyerIdParam);
    }
  }, [searchParams]);
  
  // Fetch vendor stores on component mount
  useEffect(() => {
    fetchVendorStores();
  }, []);
  
  // Fetch user information if buyer ID changes
  useEffect(() => {
    if (buyerId && vendorStores.length > 0) {
      fetchUserById(buyerId);
    }
  }, [buyerId, vendorStores]);
  
  // Fetch user information by ID
  const fetchUserById = async (userId: string) => {
    if (!userId || !vendorStores[0]?._id) return;
    
    setLoadingUser(true);
    try {
      const userData = await clientFetch(`/chats/user/${userId}`);
      if (userData) {
        setSelectedUser(userData);
        setSearchQuery(userData.telegramUsername || `User ${userId}`);
      }
    } catch (error) {
      console.error("Error fetching user:", error);
      // Still keep the buyerId
    } finally {
      setLoadingUser(false);
    }
  };

  // Fetch vendor stores
  const fetchVendorStores = async () => {
    setLoadingStores(true);
    try {
      // Get stores
      const stores = await clientFetch('/storefront');
      
      // Handle both array and single object responses
      if (Array.isArray(stores)) {
        setVendorStores(stores);
        if (stores.length > 0) {
          setSelectedStore(stores[0]._id);
        }
      } else if (stores && typeof stores === 'object' && stores._id) {
        const singleStore = [stores];
        setVendorStores(singleStore);
        setSelectedStore(stores._id);
      }
    } catch (error) {
      console.error("Error fetching stores:", error);
      toast.error("Failed to load your stores");
      
      // Redirect if there's a login issue
      if (error instanceof Error && error.message.includes('logged in')) {
        router.push("/auth/login");
      }
    } finally {
      setLoadingStores(false);
    }
  };

  // Debounced search function
  const searchUsers = debounce(async (query: string) => {
    if (!query.trim() || !selectedStore) return;

    setSearching(true);
    try {
      const results = await clientFetch(
        `/chats/search/users?query=${encodeURIComponent(query)}&storeId=${selectedStore}`
      );
      setSearchResults(results);
    } catch (error) {
      console.error("Error searching users:", error);
      toast.error("Failed to search users");
    } finally {
      setSearching(false);
    }
  }, 300);

  // Handle search input change
  const handleSearchChange = (value: string) => {
    setSearchQuery(value);
    searchUsers(value);
    setOpen(true);
  };

  // Handle user selection
  const handleUserSelect = (user: User) => {
    setBuyerId(user.telegramUserId);
    setSelectedUser(user);
    setSearchQuery(user.telegramUsername || user.telegramUserId);
    setOpen(false);
  };
  
  // Navigation handlers
  const handleBackClick = () => {
    router.push("/dashboard/chats");
  };
  
  // Start new chat
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!buyerId || !initialMessage.trim() || !selectedStore) {
      toast.error("Please fill in all required fields");
      return;
    }
    
    setLoading(true);
    try {
      const response = await clientFetch('/chats', {
        method: 'POST',
        body: JSON.stringify({
          buyerId,
          storeId: selectedStore,
          initialMessage: initialMessage.trim()
        }),
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      // Navigate to the new chat
      toast.success("Chat created successfully");
      router.push(`/dashboard/chats/${response._id}`);
    } catch (error) {
      console.error("Error creating chat:", error);
      toast.error("Failed to create chat. Please try again.");
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="flex items-center space-x-2">
          <Button variant="ghost" size="icon" onClick={handleBackClick}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <span>Start a New Conversation</span>
        </CardTitle>
        <CardDescription>
          Start a new conversation with a customer by their Telegram ID
        </CardDescription>
      </CardHeader>
      
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="buyerId">Customer Telegram ID or Username</Label>
            <div className="relative">
              <Input
                id="buyerId"
                value={searchQuery}
                onChange={(e) => handleSearchChange(e.target.value)}
                placeholder="Search by username or ID..."
                className="pr-10"
              />
              <div className="absolute inset-y-0 right-0 flex items-center pr-3">
                {loadingUser ? (
                  <RefreshCw className="h-4 w-4 animate-spin text-muted-foreground" />
                ) : (
                  <Search className="h-4 w-4 text-muted-foreground" />
                )}
              </div>
              
              {open && searchQuery && (
                <div className="absolute z-50 w-full mt-1 border bg-card rounded-md shadow-md max-h-[300px] overflow-auto">
                  {searching ? (
                    <div className="flex items-center justify-center py-6 text-sm text-muted-foreground">
                      <RefreshCw className="h-4 w-4 animate-spin mr-2" />
                      Searching...
                    </div>
                  ) : searchResults.length === 0 ? (
                    <div className="py-6 text-center text-sm text-muted-foreground">
                      No customers found
                    </div>
                  ) : (
                    <div className="py-1">
                      {searchResults.map((user) => (
                        <button
                          key={user.telegramUserId}
                          onClick={() => handleUserSelect(user)}
                          type="button"
                          className="w-full flex items-center px-4 py-3 hover:bg-accent text-left"
                        >
                          <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-primary mr-3">
                            <User className="h-4 w-4" />
                          </div>
                          <div className="flex flex-col">
                            <span className="font-medium">
                              {user.telegramUsername || "No username"}
                            </span>
                            <span className="text-xs text-muted-foreground">
                              ID: {user.telegramUserId}
                            </span>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
            <p className="text-sm text-muted-foreground">
              This is the customer's Telegram ID or username. You can search for them above or ask them to use the /myid command in your Telegram bot.
            </p>
            
            {buyerId && !searchQuery && (
              <div className="p-2 border rounded-md bg-muted/20 mt-2">
                <p className="text-sm font-medium">
                  Using Telegram ID: {buyerId}
                </p>
              </div>
            )}
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="initialMessage">Initial Message (Optional)</Label>
            <Textarea
              id="initialMessage"
              value={initialMessage}
              onChange={(e) => setInitialMessage(e.target.value)}
              placeholder="Hello! How can I help you today?"
              rows={4}
            />
          </div>
          
          <div className="flex justify-end space-x-2">
            <Button
              type="button"
              variant="outline"
              onClick={handleBackClick}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={loading || !buyerId || vendorStores.length === 0}>
              {loading ? (
                <>
                  <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                  Creating...
                </>
              ) : (
                <>
                  <Send className="mr-2 h-4 w-4" />
                  Start Conversation
                </>
              )}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
} 