import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { supabase } from '@/lib/supabaseClient';
import { Building2, AlertCircle, CheckCircle2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

export function CompanyDataBackfill() {
  const [isRunning, setIsRunning] = useState(false);
  const [result, setResult] = useState<{
    success: boolean;
    companies_updated: number;
    headquarters_added: number;
    website_added: number;
    founded_year_added: number;
    description_added: number;
    logo_added: number;
  } | null>(null);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  const handleBackfill = async () => {
    setIsRunning(true);
    setError(null);
    setResult(null);

    try {
      const { data, error: invokeError } = await supabase.functions.invoke(
        'backfill-company-data'
      );

      if (invokeError) throw invokeError;

      setResult(data);
      
      const updates: string[] = [];
      if (data.headquarters_added > 0) updates.push(`${data.headquarters_added} headquarters`);
      if (data.website_added > 0) updates.push(`${data.website_added} websites`);
      if (data.founded_year_added > 0) updates.push(`${data.founded_year_added} founding years`);
      if (data.description_added > 0) updates.push(`${data.description_added} descriptions`);
      if (data.logo_added > 0) updates.push(`${data.logo_added} logos`);
      
      toast({
        title: 'Backfill Complete',
        description: `Updated ${data.companies_updated} companies: ${updates.join(', ')}`,
      });
    } catch (err: any) {
      const errorMessage = err.message || 'Failed to run backfill';
      setError(errorMessage);
      toast({
        title: 'Backfill Failed',
        description: errorMessage,
        variant: 'destructive',
      });
    } finally {
      setIsRunning(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Building2 className="w-5 h-5" />
          Company Data Backfill
        </CardTitle>
        <CardDescription>
          Backfill missing headquarters, website, founding year, description, and logo data for companies from their submission data
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <Alert>
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            This tool will find companies (operators, manufacturers, designers) missing basic information and populate them using data from their approved submissions. Useful for fixing companies that were approved before all fields were properly handled.
          </AlertDescription>
        </Alert>

        {result && (
          <Alert className="border-green-200 bg-green-50 dark:bg-green-950 dark:border-green-800">
            <CheckCircle2 className="h-4 w-4 text-green-600 dark:text-green-400" />
            <AlertDescription className="text-green-900 dark:text-green-100">
              <div className="font-medium">Backfill completed successfully!</div>
              <div className="mt-2 space-y-1">
                <div>Companies updated: {result.companies_updated}</div>
                <div>Headquarters added: {result.headquarters_added}</div>
                <div>Websites added: {result.website_added}</div>
                <div>Founding years added: {result.founded_year_added}</div>
                <div>Descriptions added: {result.description_added}</div>
                <div>Logos added: {result.logo_added}</div>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {error && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <Button
          onClick={handleBackfill}
          disabled={isRunning}
          className="w-full"
          trackingLabel="run-company-data-backfill"
        >
          <Building2 className="w-4 h-4 mr-2" />
          {isRunning ? 'Running Backfill...' : 'Run Company Data Backfill'}
        </Button>
      </CardContent>
    </Card>
  );
}
