'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Edit, Trash2, Bell, Mail, MailCheck, Home, ClipboardList, Sparkles } from 'lucide-react';
import { toast } from 'sonner';

import { usersApi, notificationsApi, emailsApi, subscriptionsApi, onboardingEmailsApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Separator } from '@/components/ui/separator';

export function UserDetailClient() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const userId = Number(params.id);

  // Dialog states
  const [showPushDialog, setShowPushDialog] = useState(false);
  const [showEmailDialog, setShowEmailDialog] = useState(false);
  const [pushTitle, setPushTitle] = useState('Test Notification');
  const [pushBody, setPushBody] = useState('This is a test push notification from honeyDue Admin.');
  const [emailSubject, setEmailSubject] = useState('Test Email from honeyDue');
  const [emailBody, setEmailBody] = useState('This is a test email sent from the honeyDue Admin Panel.');

  const { data: user, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => usersApi.get(userId),
    enabled: !!userId,
  });

  const { data: subscription } = useQuery({
    queryKey: ['subscription', 'user', userId],
    queryFn: () => subscriptionsApi.getByUser(userId),
    enabled: !!userId,
  });

  const updateSubscriptionMutation = useMutation({
    mutationFn: (data: { is_free: boolean }) => {
      if (!subscription) throw new Error('No subscription');
      return subscriptionsApi.update(subscription.id, data);
    },
    onSuccess: () => {
      toast.success('Subscription updated');
      queryClient.invalidateQueries({ queryKey: ['subscription', 'user', userId] });
    },
    onError: () => {
      toast.error('Failed to update subscription');
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () => usersApi.delete(userId),
    onSuccess: () => {
      toast.success('User deactivated successfully');
      queryClient.invalidateQueries({ queryKey: ['users'] });
      router.push('/users');
    },
    onError: () => {
      toast.error('Failed to deactivate user');
    },
  });

  const sendPushMutation = useMutation({
    mutationFn: () => notificationsApi.sendTestNotification({
      user_id: userId,
      title: pushTitle,
      body: pushBody,
    }),
    onSuccess: (data) => {
      toast.success(`Push notification sent to ${data.devices.ios + data.devices.android} device(s)`);
      setShowPushDialog(false);
    },
    onError: (error: Error & { response?: { data?: { error?: string; details?: string } } }) => {
      const errorMsg = error.response?.data?.error || error.response?.data?.details || error.message;
      toast.error(`Failed to send notification: ${errorMsg}`);
    },
  });

  const sendEmailMutation = useMutation({
    mutationFn: () => emailsApi.sendTestEmail({
      user_id: userId,
      subject: emailSubject,
      body: emailBody,
    }),
    onSuccess: (data) => {
      toast.success(`Email sent to ${data.to}`);
      setShowEmailDialog(false);
    },
    onError: (error: Error & { response?: { data?: { error?: string; details?: string } } }) => {
      const errorMsg = error.response?.data?.error || error.response?.data?.details || error.message;
      toast.error(`Failed to send email: ${errorMsg}`);
    },
  });

  const sendOnboardingEmailMutation = useMutation({
    mutationFn: (emailType: 'no_residence' | 'no_tasks') => onboardingEmailsApi.send({
      user_id: userId,
      email_type: emailType,
    }),
    onSuccess: (data) => {
      toast.success(`Onboarding email sent to ${data.email}`);
    },
    onError: (error: Error & { response?: { data?: { error?: string; details?: string } } }) => {
      const errorMsg = error.response?.data?.error || error.response?.data?.details || error.message;
      toast.error(`Failed to send onboarding email: ${errorMsg}`);
    },
  });

  const sendPostVerificationEmailMutation = useMutation({
    mutationFn: () => emailsApi.sendPostVerificationEmail({ user_id: userId }),
    onSuccess: (data) => {
      toast.success(`Post-verification email sent to ${data.to}`);
    },
    onError: (error: Error & { response?: { data?: { error?: string; details?: string } } }) => {
      const errorMsg = error.response?.data?.error || error.response?.data?.details || error.message;
      toast.error(`Failed to send email: ${errorMsg}`);
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error || !user) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load user</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/users">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{user.username}</h1>
            <p className="text-muted-foreground">{user.email}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href={`/users/${userId}/edit`}>
              <Edit className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </Button>
          <Button
            variant="destructive"
            onClick={() => {
              if (confirm('Are you sure you want to deactivate this user?')) {
                deleteMutation.mutate();
              }
            }}
            disabled={deleteMutation.isPending}
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Deactivate
          </Button>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Basic Info */}
        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>User account details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Username
                </div>
                <div>{user.username}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Email
                </div>
                <div>{user.email}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  First Name
                </div>
                <div>{user.first_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Last Name
                </div>
                <div>{user.last_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Phone
                </div>
                <div>{user.phone_number || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Joined
                </div>
                <div>{new Date(user.date_joined).toLocaleDateString()}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Timezone
                </div>
                <div>{user.timezone || '-'}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Status */}
        <Card>
          <CardHeader>
            <CardTitle>Status</CardTitle>
            <CardDescription>Account status and permissions</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Active
                </div>
                <Badge variant={user.is_active ? 'default' : 'secondary'}>
                  {user.is_active ? 'Yes' : 'No'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Email Verified
                </div>
                <Badge variant={user.verified ? 'default' : 'outline'}>
                  {user.verified ? 'Yes' : 'No'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Staff
                </div>
                <Badge variant={user.is_staff ? 'default' : 'outline'}>
                  {user.is_staff ? 'Yes' : 'No'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Superuser
                </div>
                <Badge variant={user.is_superuser ? 'default' : 'outline'}>
                  {user.is_superuser ? 'Yes' : 'No'}
                </Badge>
              </div>
            </div>

            <Separator />

            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Residences
                </div>
                <div className="text-2xl font-bold">{user.residence_count}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Tasks Created
                </div>
                <div className="text-2xl font-bold">{user.task_count}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Subscription */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>Subscription</CardTitle>
            <CardDescription>User subscription and access settings</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Tier
                </div>
                <Badge variant={subscription?.tier === 'pro' ? 'default' : 'secondary'}>
                  {subscription?.tier || 'free'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Platform
                </div>
                <div>{subscription?.platform || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Auto Renew
                </div>
                <Badge variant={subscription?.auto_renew ? 'default' : 'outline'}>
                  {subscription?.auto_renew ? 'Yes' : 'No'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">
                  Expires
                </div>
                <div>
                  {subscription?.expires_at
                    ? new Date(subscription.expires_at).toLocaleDateString()
                    : '-'}
                </div>
              </div>
            </div>

            <Separator />

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="is-free" className="text-base">
                  Free Access (No Limitations)
                </Label>
                <p className="text-sm text-muted-foreground">
                  When enabled, this user bypasses all tier limitations regardless of subscription status or global settings.
                </p>
              </div>
              <Switch
                id="is-free"
                checked={subscription?.is_free ?? false}
                onCheckedChange={(checked) => {
                  updateSubscriptionMutation.mutate({ is_free: checked });
                }}
                disabled={updateSubscriptionMutation.isPending}
              />
            </div>
          </CardContent>
        </Card>

        {/* Residences */}
        {user.residences && user.residences.length > 0 && (
          <Card className="md:col-span-2">
            <CardHeader>
              <CardTitle>Residences</CardTitle>
              <CardDescription>Properties owned by this user</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {user.residences.map((residence) => (
                  <div
                    key={residence.id}
                    className="flex items-center justify-between p-3 border rounded-lg"
                  >
                    <div>
                      <Link
                        href={`/residences/${residence.id}`}
                        className="font-medium text-blue-600 hover:underline"
                      >
                        {residence.name}
                      </Link>
                      <div className="text-sm text-muted-foreground">
                        {residence.is_owner ? 'Owner' : 'Shared User'}
                      </div>
                    </div>
                    <Badge variant={residence.is_active ? 'default' : 'secondary'}>
                      {residence.is_active ? 'Active' : 'Inactive'}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Testing */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>Testing</CardTitle>
            <CardDescription>Send test notifications, emails, and onboarding campaigns to this user</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex gap-4 flex-wrap">
            {/* Push Notification Dialog */}
            <Dialog open={showPushDialog} onOpenChange={setShowPushDialog}>
              <DialogTrigger asChild>
                <Button variant="outline">
                  <Bell className="mr-2 h-4 w-4" />
                  Send Test Push
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Send Test Push Notification</DialogTitle>
                  <DialogDescription>
                    Send a test push notification to {user.username}&apos;s registered devices.
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label htmlFor="push-title">Title</Label>
                    <Input
                      id="push-title"
                      value={pushTitle}
                      onChange={(e) => setPushTitle(e.target.value)}
                      placeholder="Notification title"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="push-body">Body</Label>
                    <Textarea
                      id="push-body"
                      value={pushBody}
                      onChange={(e) => setPushBody(e.target.value)}
                      placeholder="Notification message"
                      rows={3}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setShowPushDialog(false)}>
                    Cancel
                  </Button>
                  <Button
                    onClick={() => sendPushMutation.mutate()}
                    disabled={sendPushMutation.isPending || !pushTitle || !pushBody}
                  >
                    {sendPushMutation.isPending ? 'Sending...' : 'Send Push'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>

            {/* Email Dialog */}
            <Dialog open={showEmailDialog} onOpenChange={setShowEmailDialog}>
              <DialogTrigger asChild>
                <Button variant="outline">
                  <Mail className="mr-2 h-4 w-4" />
                  Send Test Email
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Send Test Email</DialogTitle>
                  <DialogDescription>
                    Send a test email to {user.email}
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label htmlFor="email-subject">Subject</Label>
                    <Input
                      id="email-subject"
                      value={emailSubject}
                      onChange={(e) => setEmailSubject(e.target.value)}
                      placeholder="Email subject"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email-body">Body</Label>
                    <Textarea
                      id="email-body"
                      value={emailBody}
                      onChange={(e) => setEmailBody(e.target.value)}
                      placeholder="Email content"
                      rows={5}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setShowEmailDialog(false)}>
                    Cancel
                  </Button>
                  <Button
                    onClick={() => sendEmailMutation.mutate()}
                    disabled={sendEmailMutation.isPending || !emailSubject || !emailBody}
                  >
                    {sendEmailMutation.isPending ? 'Sending...' : 'Send Email'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
            </div>

            <Separator />

            {/* Onboarding Emails */}
            <div>
              <Label className="text-base font-medium">Onboarding Emails</Label>
              <p className="text-sm text-muted-foreground mb-3">
                Send onboarding campaign emails to encourage user engagement
              </p>
              <div className="flex gap-4 flex-wrap">
                <Button
                  variant="outline"
                  onClick={() => {
                    if (confirm('Send "Post-Verification" welcome email with tips to this user?')) {
                      sendPostVerificationEmailMutation.mutate();
                    }
                  }}
                  disabled={sendPostVerificationEmailMutation.isPending}
                >
                  <Sparkles className="mr-2 h-4 w-4" />
                  {sendPostVerificationEmailMutation.isPending ? 'Sending...' : 'Welcome Tips Email'}
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    if (confirm('Send "No Residence" onboarding email to this user?')) {
                      sendOnboardingEmailMutation.mutate('no_residence');
                    }
                  }}
                  disabled={sendOnboardingEmailMutation.isPending}
                >
                  <Home className="mr-2 h-4 w-4" />
                  {sendOnboardingEmailMutation.isPending ? 'Sending...' : 'No Residence Email'}
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    if (confirm('Send "No Tasks" onboarding email to this user?')) {
                      sendOnboardingEmailMutation.mutate('no_tasks');
                    }
                  }}
                  disabled={sendOnboardingEmailMutation.isPending}
                >
                  <ClipboardList className="mr-2 h-4 w-4" />
                  {sendOnboardingEmailMutation.isPending ? 'Sending...' : 'No Tasks Email'}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
