"use client"

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from "@/components/common/button";
import { Input } from "@/components/common/input";
import { Label } from "@/components/common/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/common/card";
import { Store, Search } from "lucide-react";
import { useToast } from "@/lib/hooks/use-toast";

export default function StoreSelector() {
  const [storeId, setStoreId] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  const searchParams = useSearchParams();
  const { toast } = useToast();

  // Initialize with current storeId from URL
  useEffect(() => {
    const currentStoreId = searchParams.get('storeId');
    if (currentStoreId) {
      setStoreId(currentStoreId);
    }
  }, [searchParams]);

  const handleStoreSelect = async () => {
    if (!storeId.trim()) {
      toast({
        title: "Error",
        description: "Please enter a store ID",
        variant: "destructive",
      });
      return;
    }

    setIsLoading(true);
    
    try {
      // Navigate to analytics with the selected storeId
      router.push(`/dashboard/analytics?storeId=${encodeURIComponent(storeId.trim())}`);
      
      toast({
        title: "Store Selected",
        description: `Analytics will now show data for store: ${storeId}`,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to switch store",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleStoreSelect();
    }
  };

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Store className="h-5 w-5" />
          Select Store
        </CardTitle>
        <CardDescription>
          Enter the store ID to view analytics for that store
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="storeId">Store ID</Label>
          <div className="flex gap-2">
            <Input
              id="storeId"
              type="text"
              placeholder="Enter store ID..."
              value={storeId}
              onChange={(e) => setStoreId(e.target.value)}
              onKeyPress={handleKeyPress}
              className="flex-1"
            />
            <Button 
              onClick={handleStoreSelect}
              disabled={isLoading || !storeId.trim()}
              size="icon"
            >
              <Search className="h-4 w-4" />
            </Button>
          </div>
        </div>
        
        <Button 
          onClick={handleStoreSelect}
          disabled={isLoading || !storeId.trim()}
          className="w-full"
        >
          {isLoading ? "Loading..." : "View Analytics"}
        </Button>
        
        {searchParams.get('storeId') && (
          <div className="text-sm text-muted-foreground text-center">
            Currently viewing: {searchParams.get('storeId')}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 

