
import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2, RefreshCw, CheckCircle2, UserCheck, AlertCircle } from 'lucide-react';
import { useRestoreUsers } from '@/hooks/useRestoreUsers';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';

export default function RestoreUsersDialog({ open, onOpenChange, onSuccess }) {
  const { toast } = useToast();
  const { syncUsers, loading: syncLoading } = useRestoreUsers();
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState(null);
  const [hasSynced, setHasSynced] = useState(false);

  const handleSync = async () => {
    setLoading(true);
    setResults(null);
    try {
      const result = await syncUsers();
      if (result.success) {
        setResults(result);
        setHasSynced(true);
        toast({ title: "Sync Successful", description: `Restored ${result.restored_count} users.` });
        if (onSuccess) onSuccess(result.restored_count);
      } else {
        throw new Error(result.error || "Unknown error occurred during sync.");
      }
    } catch (err) {
      toast({ title: "Sync Failed", description: err.message, variant: "destructive" });
    } finally { setLoading(false); }
  };

  const handleClose = () => {
    if (!loading) { setResults(null); setHasSynced(false); onOpenChange(false); }
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
            Sync Authentication Users
          </DialogTitle>
          <DialogDescription>
            This utility scans the authentication database for users that are missing from your main users table and restores them automatically.
          </DialogDescription>
        </DialogHeader>

        <div className="py-4 space-y-4">
          {!hasSynced && !loading && (
            <div className="text-center p-6 bg-muted/50 border rounded-lg">
              <div className="w-12 h-12 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-3">
                <UserCheck className="w-6 h-6" />
              </div>
              <h3 className="font-medium mb-1">Ready to Sync</h3>
              <p className="text-sm text-muted-foreground mb-4">Click the button below to start the synchronization process.</p>
              <Button onClick={handleSync} disabled={loading}>Start Synchronization</Button>
            </div>
          )}

          {loading && (
            <div className="flex flex-col items-center justify-center py-8 space-y-3">
              <Loader2 className="w-8 h-8 animate-spin text-primary" />
              <p className="text-sm font-medium text-muted-foreground">Syncing user database... Please do not close.</p>
            </div>
          )}

          {results && !loading && (
            <div className="space-y-4 animate-in fade-in zoom-in-95 duration-300">
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-muted/50 p-3 rounded border text-center">
                  <div className="text-2xl font-bold">{results.total_auth_users || 0}</div>
                  <div className="text-[10px] text-muted-foreground uppercase font-medium mt-1">Total Auth</div>
                </div>
                <div className="bg-emerald-50 p-3 rounded border border-emerald-100 text-center">
                  <div className="text-2xl font-bold text-emerald-700">+{results.restored_count || 0}</div>
                  <div className="text-[10px] text-emerald-600 uppercase font-medium mt-1">Restored</div>
                </div>
                <div className="bg-primary/5 p-3 rounded border border-primary/10 text-center">
                  <div className="text-2xl font-bold text-primary">{results.updated_count || 0}</div>
                  <div className="text-[10px] text-primary uppercase font-medium mt-1">Updated</div>
                </div>
              </div>

              {results.restored_count > 0 ? (
                <Alert className="bg-emerald-50 border-emerald-200">
                  <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                  <AlertTitle className="text-emerald-800">Success</AlertTitle>
                  <AlertDescription className="text-emerald-700">
                    Successfully restored {results.restored_count} user profiles.
                  </AlertDescription>
                </Alert>
              ) : (
                <Alert>
                  <CheckCircle2 className="h-4 w-4" />
                  <AlertTitle>Up to Date</AlertTitle>
                  <AlertDescription>All authentication accounts already have matching user profiles.</AlertDescription>
                </Alert>
              )}

              {results.restored_users_list?.length > 0 && (
                <div className="border rounded-md">
                  <div className="bg-muted/50 px-3 py-2 border-b text-xs font-semibold text-muted-foreground">
                    Restored Users ({results.restored_users_list.length})
                  </div>
                  <ScrollArea className="h-[150px]">
                    <div className="p-2 space-y-1">
                      {results.restored_users_list.map((u) => (
                        <div key={u.id} className="flex items-center justify-between text-sm p-2 hover:bg-muted/50 rounded">
                          <span className="font-medium">{u.email}</span>
                          <Badge variant="outline" className="text-[10px] h-5">Restored</Badge>
                        </div>
                      ))}
                    </div>
                  </ScrollArea>
                </div>
              )}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose} disabled={loading}>
            {hasSynced ? "Done" : "Cancel"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
