import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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 { Shield, Key, Smartphone, Globe, ExternalLink } from 'lucide-react';

const passwordSchema = z.object({
  currentPassword: z.string().min(1, 'Current password is required'),
  newPassword: z.string().min(8, 'Password must be at least 8 characters'),
  confirmPassword: z.string()
}).refine((data) => data.newPassword === data.confirmPassword, {
  message: "Passwords don't match",
  path: ["confirmPassword"]
});

type PasswordFormData = z.infer<typeof passwordSchema>;

export function SecurityTab() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);

  const form = useForm<PasswordFormData>({
    resolver: zodResolver(passwordSchema),
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  });

  const onSubmit = async (data: PasswordFormData) => {
    if (!user) return;
    
    setLoading(true);
    try {
      const { error } = await supabase.auth.updateUser({
        password: data.newPassword
      });

      if (error) throw error;

      form.reset();
      toast({
        title: 'Password updated',
        description: 'Your password has been successfully changed.'
      });
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || 'Failed to update password',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSocialLogin = async (provider: 'google') => {
    try {
      const { error } = await supabase.auth.signInWithOAuth({
        provider: provider
      });

      if (error) throw error;

      toast({
        title: 'Redirecting...',
        description: `Redirecting to ${provider} to link your account.`
      });
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || `Failed to link ${provider} account`,
        variant: 'destructive'
      });
    }
  };

  const handleUnlinkSocial = async (provider: 'google') => {
    try {
      // Note: Supabase doesn't have a direct unlink method
      // This would typically be handled through the admin API or by the user
      toast({
        title: 'Feature not available',
        description: 'Please contact support to unlink social accounts.',
      });
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || `Failed to unlink ${provider} account`,
        variant: 'destructive'
      });
    }
  };

  // Mock data for connected accounts - in real app this would come from user metadata
  const connectedAccounts = [
    {
      provider: 'google',
      connected: user?.app_metadata?.providers?.includes('google') || false,
      email: user?.email
    }
  ];

  return (
    <div className="space-y-8">
      {/* Change Password */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Key className="w-5 h-5" />
          <h3 className="text-lg font-medium">Change Password</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardDescription>
              Update your password to keep your account secure.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="currentPassword">Current Password</Label>
                <Input
                  id="currentPassword"
                  type="password"
                  {...form.register('currentPassword')}
                  placeholder="Enter your current password"
                />
                {form.formState.errors.currentPassword && (
                  <p className="text-sm text-destructive">
                    {form.formState.errors.currentPassword.message}
                  </p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="newPassword">New Password</Label>
                <Input
                  id="newPassword"
                  type="password"
                  {...form.register('newPassword')}
                  placeholder="Enter your new password"
                />
                {form.formState.errors.newPassword && (
                  <p className="text-sm text-destructive">
                    {form.formState.errors.newPassword.message}
                  </p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="confirmPassword">Confirm New Password</Label>
                <Input
                  id="confirmPassword"
                  type="password"
                  {...form.register('confirmPassword')}
                  placeholder="Confirm your new password"
                />
                {form.formState.errors.confirmPassword && (
                  <p className="text-sm text-destructive">
                    {form.formState.errors.confirmPassword.message}
                  </p>
                )}
              </div>

              <Button type="submit" disabled={loading}>
                {loading ? 'Updating...' : 'Update Password'}
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>

      <Separator />

      {/* Social Login Connections */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Globe className="w-5 h-5" />
          <h3 className="text-lg font-medium">Connected Accounts</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardDescription>
              Manage your social login connections for easier access to your account.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {connectedAccounts.map((account) => (
              <div key={account.provider} className="flex items-center justify-between p-4 border rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 bg-muted rounded-full flex items-center justify-center">
                    <Globe className="w-4 h-4" />
                  </div>
                  <div>
                    <p className="font-medium capitalize">{account.provider}</p>
                    {account.connected && account.email && (
                      <p className="text-sm text-muted-foreground">{account.email}</p>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {account.connected ? (
                    <>
                      <Badge variant="secondary">Connected</Badge>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleUnlinkSocial(account.provider as 'google')}
                      >
                        Disconnect
                      </Button>
                    </>
                  ) : (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleSocialLogin(account.provider as 'google')}
                      >
                        Connect
                      </Button>
                  )}
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      </div>

      <Separator />

      {/* Two-Factor Authentication */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Smartphone className="w-5 h-5" />
          <h3 className="text-lg font-medium">Two-Factor Authentication</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardDescription>
              Add an extra layer of security to your account with two-factor authentication.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between p-4 border rounded-lg">
              <div>
                <p className="font-medium">Authenticator App</p>
                <p className="text-sm text-muted-foreground">
                  Use an authenticator app to generate verification codes
                </p>
              </div>
              <Button variant="outline" disabled>
                Coming Soon
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      <Separator />

      {/* Login History */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Shield className="w-5 h-5" />
          <h3 className="text-lg font-medium">Login History</h3>
        </div>
        
        <Card>
          <CardHeader>
            <CardDescription>
              Review your recent login activity and active sessions.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <p className="font-medium">Current Session</p>
                  <p className="text-sm text-muted-foreground">
                    Web • {new Date().toLocaleDateString()}
                  </p>
                </div>
                <Badge variant="secondary">Active</Badge>
              </div>
              
              <div className="text-center p-4 text-muted-foreground">
                <p className="text-sm">No other recent sessions found</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}