import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Search } from 'lucide-react';
import { supabase } from '@/lib/supabaseClient';
import { toast } from 'sonner';

export default function ErrorLookup() {
  const [errorId, setErrorId] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleSearch = async () => {
    if (!errorId.trim()) {
      toast.error('Please enter an error ID');
      return;
    }

    setLoading(true);
    try {
      // Search by partial or full request ID
      const { data, error } = await supabase
        .from('request_metadata')
        .select(`
          *,
          request_breadcrumbs(
            timestamp,
            category,
            message,
            level,
            sequence_order
          )
        `)
        .ilike('request_id', `${errorId}%`)
        .not('error_type', 'is', null)
        .limit(1)
        .single();

      if (error || !data) {
        toast.error('Error not found', {
          description: 'No error found with this ID. Please check the ID and try again.',
        });
        return;
      }

      // Navigate to error monitoring with this error pre-selected
      navigate('/admin/error-monitoring', { state: { selectedErrorId: data.request_id } });
    } catch (err) {
      toast.error('Search failed', {
        description: 'An error occurred while searching. Please try again.',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <AdminLayout>
      <div className="max-w-2xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Error Lookup</h1>
          <p className="text-muted-foreground">
            Search for specific errors by their reference ID
          </p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Search by Error ID</CardTitle>
            <CardDescription>
              Enter the error reference ID provided to users (first 8 characters are sufficient)
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex gap-2">
              <Input
                placeholder="e.g., a3f7b2c1"
                value={errorId}
                onChange={(e) => setErrorId(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="font-mono"
              />
              <Button 
                onClick={handleSearch} 
                loading={loading}
                loadingText="Searching..."
                trackingLabel="error-lookup-search"
              >
                <Search className="w-4 h-4 mr-2" />
                Search
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </AdminLayout>
  );
}
