"use client"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Phone, CheckCircle, Loader2, TestTube, MessageCircle, BookOpen, Save, Instagram, Users, ArrowLeft, AlertCircle } from "lucide-react"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
import { useGetAssistantAssignedNumber, useGetAssistantAssignedSMSNumber, useGetAssistantTrainingData, useUpdateAssistantTrainingData, useGetWhatsAppConnectionStatus, useGetInstagramConnectionStatus, useStopInstagramEvents, useStopWhatsAppEvents } from "@/lib/react-query/hooks/assistant"
import { AiOnboarding } from "./components/AiOnboarding"
import { WhatsAppEmbeddedSignup } from "./components/WhatsAppEmbeddedSignup"
import { InstagramIntegration } from "./components/InstagramIntegration"
import { PlatformClientsDialog } from "./components/PlatformClientsDialog"
import { VoiceSelection } from "./components/VoiceSelection"
import { useRouter } from "next/navigation"
import Image from "next/image"
import aivlyWhatsappQr from "@/assets/images/aivly_whatsapp_qr.png"
import { formatPhoneNumber } from "@/lib/utils"
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar"

import { useState, useEffect, useRef } from "react"
import { useTranslations } from "next-intl"
import { useProfile } from "@/lib/react-query/hooks/auth"
import { useGetAIAnalytics, useGetAICallDuration } from "@/lib/react-query/hooks/analytics"

import { AiCapabilities } from "./components/AiCapabilities"

export function AiAssistantMain() {
  const { data: assignedNumber, isLoading: assignedLoading } = useGetAssistantAssignedNumber()
  const { data: assignedSMSNumber } = useGetAssistantAssignedSMSNumber()
  const { data: trainingData, isLoading: trainingLoading } = useGetAssistantTrainingData()
  const { data: whatsappStatus } = useGetWhatsAppConnectionStatus()
  const { data: instagramStatus } = useGetInstagramConnectionStatus()
  const stopInstagram = useStopInstagramEvents()
  const { data: aiAnalytics } = useGetAIAnalytics()
  const { data: callDurationData } = useGetAICallDuration()

  const updateTrainingData = useUpdateAssistantTrainingData()
  const router = useRouter()
  const t = useTranslations()

  const [trainingText, setTrainingText] = useState("")
  const [whatsappClientsOpen, setWhatsappClientsOpen] = useState(false)
  const [instagramClientsOpen, setInstagramClientsOpen] = useState(false)
  const [showOnboarding, setShowOnboarding] = useState(false)
  const [activePlatform, setActivePlatform] = useState<string | null>(null)
  const [isInstagramDeactivateDialogOpen, setIsInstagramDeactivateDialogOpen] = useState(false)
  const [isWhatsAppDeactivateDialogOpen, setIsWhatsAppDeactivateDialogOpen] = useState(false)
  const stopWhatsApp = useStopWhatsAppEvents()
  const { data: profile } = useProfile()

  // Update training text when data loads
  useEffect(() => {
    if (trainingData?.trainingData) {
      setTrainingText(trainingData.trainingData)
    }
  }, [trainingData])

  // Show loading state while checking assigned number
  if (assignedLoading) {
    return (
      <div className="w-full flex items-center justify-center py-12">
        <div className="flex items-center gap-3">
          <Loader2 className="w-6 h-6 animate-spin text-primary" />
          <span className="text-gray-600">{t("assistant.loading.checkingSetup")}</span>
        </div>
      </div>
    )
  }

  // Handle starting onboarding
  if (showOnboarding) {
    return (
      <div className="space-y-4">
        <Button
          variant="ghost"
          onClick={() => setShowOnboarding(false)}
          className="flex items-center gap-2 text-gray-600 hover:text-gray-900"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Overview
        </Button>
        <AiOnboarding onSuccess={() => setShowOnboarding(false)} />
      </div>
    )
  }

  // If user has an assigned number OR we want to show capabilities first
  const hasNumber = !!(assignedNumber?.available && assignedNumber.phoneNumber)

  return (
    <div className="w-full space-y-8">
      {!activePlatform ? (
        <>
          {/* New AI Capabilities Overview */}
          <div className="bg-[#F8FAFC] rounded-2xl p-8 border border-gray-100">
            <AiCapabilities
              assignedNumber={assignedNumber?.phoneNumber || undefined}
              whatsappNumber={(whatsappStatus?.phone || assignedNumber?.phoneNumber) || undefined}
              whatsappConnected={whatsappStatus?.connected}
              instagramConnected={instagramStatus?.connected}
              instagramHandle={instagramStatus?.profile?.username || undefined}
              phoneStats={{
                total: callDurationData?.totalCalls || 0,
                today: callDurationData?.totalDurationMinutes || 0
              }}
              smsStats={{
                total: assignedSMSNumber?.totalSMS || 0,
                today: assignedSMSNumber?.totalConversations || 0
              }}
              onManagePhone={hasNumber ? () => setActivePlatform('phone') : () => setShowOnboarding(true)}
              onManageWhatsapp={() => setActivePlatform('whatsapp')}
              onWhatsappToggle={(checked: boolean) => {
                if (!checked) {
                  setIsWhatsAppDeactivateDialogOpen(true)
                }
              }}
              onManageInstagram={() => setActivePlatform('instagram')}
              onInstagramToggle={(checked: boolean) => {
                if (!checked) {
                  setIsInstagramDeactivateDialogOpen(true)
                }
              }}
              activePlatform={activePlatform || undefined}
              smsNumber={assignedSMSNumber?.phoneNumber || undefined}
              smsConnected={assignedSMSNumber?.available}
            />
          </div>

          <div className="space-y-6">
            <VoiceSelection />

            <Card className="rounded-lg">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <BookOpen className="w-5 h-5 text-primary" />
                  {t("assistant.main.trainingTitle")}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <p className="text-gray-600">
                    {t("assistant.main.trainingDescription")}
                  </p>

                  {trainingLoading ? (
                    <div className="flex items-center justify-center py-8">
                      <Loader2 className="w-6 h-6 animate-spin text-primary" />
                    </div>
                  ) : (
                    <>
                      <Textarea
                        placeholder={t("assistant.main.trainingPlaceholder")}
                        value={trainingText}
                        onChange={(e) => setTrainingText(e.target.value)}
                        rows={8}
                        className="resize-none"
                      />

                      <div className="flex justify-end">
                        <Button
                          onClick={() => updateTrainingData.mutate({ trainingData: trainingText })}
                          disabled={updateTrainingData.isPending}
                          className="bg-primary-gradient text-white"
                        >
                          {updateTrainingData.isPending ? (
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          ) : (
                            <Save className="w-4 h-4 mr-2" />
                          )}
                          {t("assistant.main.saveTraining")}
                        </Button>
                      </div>
                    </>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </>
      ) : (
        <div className="space-y-6">
          <Button
            variant="ghost"
            onClick={() => setActivePlatform(null)}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-900 -ml-2"
          >
            <ArrowLeft className="w-4 h-4" />
            {t("common.back")}
          </Button>
          {activePlatform === 'phone' && (
            <div>
              {hasNumber ? (
                <Card className="rounded-lg">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <CheckCircle className="w-5 h-5 text-green-600" />
                      {t("assistant.main.activeTitle")}
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="flex items-center gap-3 p-4 bg-green-50 border border-green-200 rounded-lg">
                        <Phone className="w-5 h-5 text-green-600" />
                        <div>
                          <p className="font-medium text-green-900">{t("assistant.main.phoneAssigned")}</p>
                          <p className="text-green-700">{assignedNumber?.phoneNumber}</p>
                        </div>
                      </div>
                      <p className="text-gray-600">
                        {t("assistant.main.readyDescription")}
                      </p>
                      <div className="pt-4">
                        <Button
                          onClick={() => router.push('/dashboard/ai-assistant/playground')}
                          className="bg-primary-gradient text-white"
                        >
                          <TestTube className="w-4 h-4 mr-2" />
                          {t("assistant.main.testPlayground")}
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ) : (
                <Card className="rounded-lg border-dashed border-2">
                  <CardContent className="p-8 text-center space-y-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mx-auto">
                      <Phone className="w-6 h-6 text-primary" />
                    </div>
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900">{t("assistant.status.noNumberAssigned")}</h3>
                      <p className="text-sm text-gray-500 max-w-sm mx-auto mt-1">
                        {t("assistant.onboarding.subtitle")}
                      </p>
                    </div>
                    <Button onClick={() => setShowOnboarding(true)} className="bg-primary-gradient text-white">
                      {t("assistant.onboarding.viewNumbers")}
                    </Button>
                  </CardContent>
                </Card>
              )}
            </div>
          )}

          {/* WhatsApp Chat Card */}
          {activePlatform === 'whatsapp' && (
            <div>
              <Card className="rounded-lg">
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <MessageCircle className="w-5 h-5 text-green-600" />
                      {t("assistant.main.whatsappTitle")}
                    </div>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className={`flex items-center gap-3 p-4 rounded-lg border ${whatsappStatus?.connected ? "bg-green-50 border-green-200" : "bg-yellow-50 border-yellow-200"}`}>
                      <MessageCircle className={`w-5 h-5 ${whatsappStatus?.connected ? "text-green-600" : "text-yellow-600"}`} />
                      <div>
                        <p className={`font-medium ${whatsappStatus?.connected ? "text-green-900" : "text-yellow-900"}`}>{t("assistant.main.whatsappIntegration")}</p>
                        <p className={whatsappStatus?.connected ? "text-green-700" : "text-yellow-700"}>
                          {whatsappStatus?.connected ? t("assistant.main.whatsappConnected") : t("assistant.main.whatsappConnection")}
                        </p>
                      </div>
                    </div>
                    <p className="text-gray-600">
                      {t("assistant.main.whatsappDescription")}
                    </p>

                    <div className="pt-4 border-t">
                      <div className="max-w-md mx-auto">
                        <div className="text-center">
                          <h3 className="text-lg font-semibold text-gray-900 mb-2">{t("assistant.main.whatsappNumber")}</h3>
                          <div className="flex items-center justify-center gap-3 p-4 bg-primary/5 border border-primary/20 rounded-lg">
                            <Phone className="w-6 h-6 text-primary" />
                            <div>
                              <p className="text-sm text-gray-600">{t("assistant.main.whatsappNumber")}</p>
                              <p className="text-xl font-bold text-primary">
                                {formatPhoneNumber(whatsappStatus?.phone || assignedNumber?.phoneNumber || "")}
                              </p>
                            </div>
                          </div>
                          <p className="text-sm text-gray-600 mt-3">
                            {t("assistant.main.whatsappNumberDescription")}
                          </p>
                        </div>
                      </div>
                    </div>

                    <div className="flex flex-col items-center gap-3 border-t pt-4">
                      {whatsappStatus?.connected ? (
                        <div className="flex flex-col items-center gap-3">
                          <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 px-4 py-1.5 text-sm font-semibold uppercase">
                            {whatsappStatus.status}
                          </Badge>
                          <Button
                            onClick={() => setWhatsappClientsOpen(true)}
                            variant="outline"
                            className="border-green-200 text-green-700 hover:bg-green-50 hover:text-green-800 gap-2"
                          >
                            <Users className="w-4 h-4" />
                            View WhatsApp Clients
                          </Button>
                        </div>
                      ) : (
                        <>
                          <WhatsAppEmbeddedSignup />
                          <p className="text-sm text-gray-500">{t("assistant.main.linkAccount")}</p>
                        </>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Instagram Chat Card */}
          {activePlatform === 'instagram' && (
            <div>
              <Card className="rounded-lg">
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="bg-gradient-to-tr from-[#f9ce34] via-[#ee2a7b] to-[#6228d7] p-1.5 rounded-lg">
                        <Instagram className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <div className="text-lg font-bold">{t("assistant.main.instagramTitle")}</div>
                        <div className="text-sm font-normal text-gray-500">{t("assistant.main.instagramSubtitle")}</div>
                      </div>
                    </div>
                    {instagramStatus?.connected && (
                      <Badge variant="outline" className="bg-green-100 text-green-700 border-green-200 px-3 py-1 rounded-full text-xs font-bold uppercase">
                        {instagramStatus.status}
                      </Badge>
                    )}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-6">
                    {instagramStatus?.connected ? (
                      <>
                        <div className="flex items-center gap-3 p-4 bg-green-50 border border-green-200 rounded-lg">
                          <CheckCircle className="w-5 h-5 text-green-600" />
                          <p className="font-medium text-green-900">{t("assistant.main.instagramConnectedSuccess")}</p>
                        </div>

                        <div className="bg-gray-50 rounded-xl p-6 flex flex-col md:flex-row items-center gap-6 border border-gray-100 shadow-sm transition-all hover:bg-white hover:shadow-md cursor-default">
                          <div className="relative">
                            <Avatar className="w-24 h-24 border-4 border-white shadow-lg overflow-hidden ring-2 ring-gray-100">
                              {instagramStatus.profile?.profilePictureUrl ? (
                                <AvatarImage src={instagramStatus.profile.profilePictureUrl} className="object-cover" />
                              ) : (
                                <AvatarFallback className="bg-gradient-to-tr from-[#f9ce34] via-[#ee2a7b] to-[#6228d7] text-white text-2xl font-bold">
                                  {(instagramStatus.profile?.name || instagramStatus.profile?.username || "I").charAt(0).toUpperCase()}
                                </AvatarFallback>
                              )}
                            </Avatar>
                            <div className="absolute -bottom-1 -right-1 bg-white rounded-full p-1.5 shadow-md ring-1 ring-gray-100">
                              <Instagram className="w-4 h-4 text-[#E1306C]" />
                            </div>
                          </div>

                          <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-4">
                            <div className="col-span-1 md:col-span-2">
                              <h3 className="text-2xl font-bold text-gray-900 tracking-tight">
                                {instagramStatus.profile?.name || instagramStatus.profile?.username}
                              </h3>
                            </div>

                            <div className="space-y-1">
                              <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest leading-none">{t("assistant.main.emailLabel")}</p>
                              <p className="text-sm font-semibold text-gray-700 break-all">{instagramStatus.profile?.email || t("assistant.main.notAvailable")}</p>
                            </div>

                            <div className="space-y-1">
                              <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest leading-none">{t("assistant.main.mediaCountLabel")}</p>
                              <p className="text-sm font-semibold text-gray-700">{instagramStatus.profile?.mediaCount ?? t("assistant.main.notAvailable")} {t("assistant.main.postsLabel")}</p>
                            </div>

                            <div className="space-y-1">
                              <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest leading-none">{t("assistant.main.followersLabel")}</p>
                              <p className="text-sm font-semibold text-gray-700">{instagramStatus.profile?.followersCount ?? t("assistant.main.notAvailable")}</p>
                            </div>

                            <div className="space-y-1">
                              <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest leading-none">{t("assistant.main.followingLabel")}</p>
                              <p className="text-sm font-semibold text-gray-700">{instagramStatus.profile?.followsCount ?? t("assistant.main.notAvailable")}</p>
                            </div>
                          </div>
                        </div>
                      </>
                    ) : (
                      <>
                        <div className="flex items-center gap-3 p-4 rounded-lg border bg-pink-50 border-pink-200">
                          <Instagram className="w-5 h-5 text-pink-600" />
                          <div>
                            <p className="font-medium text-pink-900">{t("assistant.main.instagramTitle")}</p>
                            <p className="text-pink-700">{t("assistant.main.instagramDescription")}</p>
                          </div>
                        </div>
                        <div className="flex flex-col items-center gap-3 border-t pt-4">
                          <InstagramIntegration />
                        </div>
                      </>
                    )}
                    {instagramStatus?.connected && (
                      <div className="flex justify-center pt-2">
                        <Button
                          onClick={() => setInstagramClientsOpen(true)}
                          variant="outline"
                          className="border-pink-200 text-pink-700 hover:bg-pink-50 hover:text-pink-800 gap-2"
                        >
                          <Users className="w-4 h-4" />
                          View Instagram Clients
                        </Button>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>
          )}
        </div>
      )}

      <PlatformClientsDialog
        open={whatsappClientsOpen}
        onOpenChange={setWhatsappClientsOpen}
        platform="whatsapp"
      />
      <PlatformClientsDialog
        open={instagramClientsOpen}
        onOpenChange={setInstagramClientsOpen}
        platform="instagram"
      />

      <AlertDialog open={isInstagramDeactivateDialogOpen} onOpenChange={setIsInstagramDeactivateDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-2">
              <AlertCircle className="w-6 h-6 text-red-600" />
            </div>
            <AlertDialogTitle className="text-xl font-bold text-gray-900">
              {t("assistant.main.instagramDeactivationTitle") || "Deactivate Instagram"}
            </AlertDialogTitle>
            <AlertDialogDescription className="text-gray-600 leading-relaxed">
              {t("assistant.main.confirmDeactivateInstagram")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter className="mt-4">
            <AlertDialogCancel className="bg-gray-100 hover:bg-gray-200 text-gray-700 border-none transition-all">
              {t("common.cancel") || "Cancel"}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => stopInstagram.mutate()}
              className="bg-red-600 hover:bg-red-700 text-white shadow-sm transition-all"
            >
              {t("common.deactivate") || "Deactivate"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <AlertDialog open={isWhatsAppDeactivateDialogOpen} onOpenChange={setIsWhatsAppDeactivateDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-2">
              <AlertCircle className="w-6 h-6 text-red-600" />
            </div>
            <AlertDialogTitle className="text-xl font-bold text-gray-900">
              {t("assistant.main.whatsappDeactivationTitle") || "Deactivate WhatsApp"}
            </AlertDialogTitle>
            <AlertDialogDescription className="text-gray-600 leading-relaxed">
              {t("assistant.main.confirmDeactivateWhatsapp")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter className="mt-4">
            <AlertDialogCancel className="bg-gray-100 hover:bg-gray-200 text-gray-700 border-none transition-all">
              {t("common.cancel") || "Cancel"}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => stopWhatsApp.mutate()}
              className="bg-red-600 hover:bg-red-700 text-white shadow-sm transition-all"
            >
              {t("common.deactivate") || "Deactivate"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
