import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/hooks/useAuth';
import { supabase } from '@/integrations/supabase/client';
import { Download, BarChart3, Upload, FileText, History } from 'lucide-react';
export function DataExportTab() {
  const {
    user,
    profile
  } = useAuth();
  const {
    toast
  } = useToast();
  const [exportLoading, setExportLoading] = useState(false);
  const [exportProgress, setExportProgress] = useState(0);
  const handleDataExport = async () => {
    if (!user) return;
    setExportLoading(true);
    setExportProgress(0);
    try {
      // Simulate export progress
      const steps = ['Collecting profile data...', 'Gathering reviews...', 'Collecting ride credits...', 'Gathering top lists...', 'Packaging data...', 'Preparing download...'];
      for (let i = 0; i < steps.length; i++) {
        await new Promise(resolve => setTimeout(resolve, 500));
        setExportProgress((i + 1) / steps.length * 100);
      }

      // In a real implementation, this would:
      // 1. Fetch all user data from various tables
      // 2. Package it into a structured format (JSON/CSV)
      // 3. Create a downloadable file

      const exportData = {
        profile: profile,
        export_date: new Date().toISOString(),
        data_types: ['profile', 'reviews', 'ride_credits', 'top_lists']
      };
      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json'
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      toast({
        title: 'Export complete',
        description: 'Your data has been exported and downloaded successfully.'
      });
    } catch (error: any) {
      toast({
        title: 'Export failed',
        description: error.message || 'Failed to export your data',
        variant: 'destructive'
      });
    } finally {
      setExportLoading(false);
      setExportProgress(0);
    }
  };
  const handleImportData = () => {
    toast({
      title: 'Coming soon',
      description: 'Data import functionality will be available in a future update.'
    });
  };
  return <div className="space-y-8">
      {/* Personal Statistics */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <BarChart3 className="w-5 h-5" />
          <h3 className="text-lg font-medium">Personal Statistics</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardDescription>
              Overview of your activity and contributions to ThrillWiku.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-muted/50 rounded-lg">
                <div className="text-2xl font-bold text-primary">
                  {profile?.review_count || 0}
                </div>
                <div className="text-sm text-muted-foreground">Reviews</div>
              </div>
              
              <div className="text-center p-4 bg-muted/50 rounded-lg">
                <div className="text-2xl font-bold text-primary">
                  {profile?.ride_count || 0}
                </div>
                <div className="text-sm text-muted-foreground">Rides</div>
              </div>
              
              <div className="text-center p-4 bg-muted/50 rounded-lg">
                <div className="text-2xl font-bold text-primary">
                  {profile?.coaster_count || 0}
                </div>
                <div className="text-sm text-muted-foreground">Coasters</div>
              </div>
              
              <div className="text-center p-4 bg-muted/50 rounded-lg">
                <div className="text-2xl font-bold text-primary">
                  {profile?.park_count || 0}
                </div>
                <div className="text-sm text-muted-foreground">Parks</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Separator />

      {/* Data Export */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Download className="w-5 h-5" />
          <h3 className="text-lg font-medium">Export Your Data</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardTitle>Download Your Data</CardTitle>
            <CardDescription>
              Export all your personal data in a machine-readable format. This includes your profile, 
              reviews, ride credits, top lists, and account activity.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex flex-wrap gap-2">
              <Badge variant="secondary">Profile Information</Badge>
              <Badge variant="secondary">Reviews & Ratings</Badge>
              <Badge variant="secondary">Ride Credits</Badge>
              <Badge variant="secondary">Top Lists</Badge>
              <Badge variant="secondary">Account Activity</Badge>
            </div>
            
            {exportLoading && <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span>Exporting data...</span>
                  <span>{Math.round(exportProgress)}%</span>
                </div>
                <Progress value={exportProgress} />
              </div>}
            
            <Button onClick={handleDataExport} disabled={exportLoading} className="w-fit">
              <Download className="w-4 h-4 mr-2" />
              {exportLoading ? 'Exporting...' : 'Export My Data'}
            </Button>
            
            <p className="text-sm text-muted-foreground">
              Your data will be provided in JSON format. Processing may take a few moments 
              for accounts with lots of activity.
            </p>
          </CardContent>
        </Card>
      </div>

      

      {/* Data Import */}
      

      

      {/* Account Activity */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <History className="w-5 h-5" />
          <h3 className="text-lg font-medium">Account Activity</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardTitle>Recent Activity Log</CardTitle>
            <CardDescription>
              Your recent account activities and important events.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-center gap-3 p-3 border rounded-lg">
                <div className="w-2 h-2 bg-primary rounded-full"></div>
                <div className="flex-1">
                  <p className="text-sm font-medium">Profile updated</p>
                  <p className="text-xs text-muted-foreground">
                    {profile?.updated_at ? new Date(profile.updated_at).toLocaleString() : 'Recently'}
                  </p>
                </div>
              </div>
              
              <div className="flex items-center gap-3 p-3 border rounded-lg">
                <div className="w-2 h-2 bg-muted rounded-full"></div>
                <div className="flex-1">
                  <p className="text-sm font-medium">Account created</p>
                  <p className="text-xs text-muted-foreground">
                    {profile?.created_at ? new Date(profile.created_at).toLocaleString() : 'N/A'}
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>;
}