"use client"

import { useGetClientAppointments, useGetClientInsights } from "@/lib/react-query/hooks/clients"
import { useMarkAsNoShow } from "@/lib/react-query/hooks/appointments"
import { useParams, useRouter } from "next/navigation"
import { useState } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { ChevronLeft, ChevronRight, Calendar, Clock, User, Scissors, Wallet, History, Phone, MessageCircle } from "lucide-react"
import { useTranslations } from "next-intl"
import { PageTitle } from "@/components/common/PageTitle"
import { CustomTabs, TabsContent } from "@/components/common/CustomTabs"
import { ClientCallLogs } from "@/components/modules/customers/ClientCallLogs"
import { ClientWhatsAppSessions } from "@/components/modules/customers/ClientWhatsAppSessions"
import { useAuth } from "@/context/AuthContext"

// Helper function to format date and time
const formatDateTime = (start: string, end: string, timezone?: string) => {
    const startDate = new Date(start)
    const endDate = new Date(end)

    const date = startDate.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        timeZone: timezone
    })

    const time = `${startDate.toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
        timeZone: timezone
    })} - ${endDate.toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
        timeZone: timezone
    })}`

    return { date, time }
}

const formatDate = (dateString?: string, timezone?: string) => {
    if (!dateString) return "N/A"
    return new Date(dateString).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        timeZone: timezone
    })
}

export default function ClientAppointmentsPage() {
    const { id } = useParams() as { id: string }
    const router = useRouter()
    const t = useTranslations()
    const { user } = useAuth()
    const timezone = user?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone
    const [currentPage, setCurrentPage] = useState(1)
    const [activeTab, setActiveTab] = useState("appointments")
    const pageSize = 10
    const { mutate: markNoShow, isPending } = useMarkAsNoShow()

    const { data: response, isLoading: appointmentsLoading } = useGetClientAppointments({
        clientId: id,
        page: currentPage,
        limit: pageSize
    })

    const { data: insightsData, isLoading: insightsLoading } = useGetClientInsights(id)

    const appointments = response?.data || []
    const total = response?.meta?.total || 0
    const insights = insightsData?.insights

    const tabItems = [
        { value: "appointments", label: t("customers.appointments.title") },
        { value: "calls", label: t("customers.appointments.callLogs") },
        { value: "whatsapp", label: t("customers.appointments.whatsapp") }
    ]

    if (appointmentsLoading || insightsLoading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
        )
    }

    return (
        <div className="space-y-6">
            <div className="flex items-center gap-4">
                <h1 className="text-gradient font-extrabold text-2xl">{t("customers.appointments.title")}</h1>
            </div>

            {/* Insights Cards */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <Card className="bg-white border-none shadow-sm overflow-hidden text-sm">
                    <CardContent className="p-4 flex items-center gap-4 text-sm">
                        <div className="p-3 bg-blue-50 rounded-xl">
                            <History className="w-6 h-6 text-primary-blue" />
                        </div>
                        <div>
                            <p className="text-sm font-medium text-gray-500">{t("customers.appointments.totalAppointments")}</p>
                            <h3 className="text-xl font-bold text-gray-900">{insights?.totalAppointments || 0}</h3>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-white border-none shadow-sm overflow-hidden">
                    <CardContent className="p-4 flex items-center gap-4">
                        <div className="p-3 bg-emerald-50 rounded-xl">
                            <Wallet className="w-6 h-6 text-emerald-600" />
                        </div>
                        <div>
                            <p className="text-sm font-medium text-gray-500">{t("customers.appointments.totalSpent")}</p>
                            <h3 className="text-xl font-bold text-gray-900">€{insights?.totalSpent || 0}</h3>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-white border-none shadow-sm overflow-hidden">
                    <CardContent className="p-4 flex items-center gap-4">
                        <div className="p-3 bg-purple-50 rounded-xl">
                            <Calendar className="w-6 h-6 text-purple-600" />
                        </div>
                        <div>
                            <p className="text-sm font-medium text-gray-500">{t("customers.appointments.lastAppointment")}</p>
                            <h3 className="text-lg font-bold text-gray-900">{formatDate(insights?.lastAppointmentDate, timezone)}</h3>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-white border-none shadow-sm overflow-hidden">
                    <CardContent className="p-4 flex items-center gap-4">
                        <div className="p-3 bg-orange-50 rounded-xl">
                            <MessageCircle className="w-6 h-6 text-orange-600" />
                        </div>
                        <div>
                            <p className="text-sm font-medium text-gray-500">{t("customers.appointments.lastInteraction")}</p>
                            <h3 className="text-lg font-bold text-gray-900">{formatDate(insights?.lastInteractionDate, timezone)}</h3>
                        </div>
                    </CardContent>
                </Card>
            </div>

            <CustomTabs
                items={tabItems}
                activeValue={activeTab}
                onTabChange={setActiveTab}
            >
                <TabsContent value="appointments">
                    <Card className="shadow-sm border-gray-200">
                        <CardContent className="p-0">
                            <Table>
                                <TableHeader>
                                    <TableRow className="bg-gray-50/50">
                                        <TableHead className="font-semibold text-gray-900 text-left pl-6">{t("customers.appointments.service")}</TableHead>
                                        <TableHead className="font-semibold text-gray-900 text-left">{t("customers.appointments.stylist")}</TableHead>
                                        <TableHead className="font-semibold text-gray-900 text-center">{t("customers.appointments.date")}</TableHead>
                                        <TableHead className="font-semibold text-gray-900 text-center">{t("customers.appointments.time")}</TableHead>
                                        <TableHead className="font-semibold text-gray-900 text-center">{t("customers.appointments.fee")}</TableHead>
                                        <TableHead className="font-semibold text-gray-900 text-center">{t("customers.appointments.status")}</TableHead>
                                        <TableHead className="font-semibold text-gray-900 text-center">{t("staff.detail.actions")}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {!appointments || appointments.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={7} className="text-center py-12 text-gray-500">
                                                <div className="flex flex-col items-center gap-2">
                                                    <Calendar className="w-8 h-8 text-gray-300" />
                                                    <p>{t("customers.appointments.noAppointments")}</p>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        appointments.map((appointment: any) => {
                                            const { date, time } = formatDateTime(appointment.start, appointment.end, timezone)
                                            return (
                                                <TableRow key={appointment._id} className="hover:bg-gray-50/50 transition-colors text-sm">
                                                    <TableCell className="font-medium text-left pl-6">
                                                        <div className="flex items-center gap-2">
                                                            <div className="p-2 bg-blue-50 rounded-lg shrink-0">
                                                                <Scissors className="w-4 h-4 text-primary-blue" />
                                                            </div>
                                                            <span className="font-medium text-gray-900 line-clamp-2 text-left">
                                                                {appointment.serviceId?.name || "N/A"}
                                                            </span>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="whitespace-nowrap text-left">
                                                        <span className="text-gray-700 text-sm">{appointment.stylistId?.name || "N/A"}</span>
                                                    </TableCell>
                                                    <TableCell className="text-gray-600 whitespace-nowrap text-center">{date}</TableCell>
                                                    <TableCell className="whitespace-nowrap text-center">
                                                        <div className="flex items-center justify-center gap-1.5 text-gray-600">
                                                            <Clock className="w-3.5 h-3.5 shrink-0" />
                                                            <span>{time}</span>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="font-semibold text-emerald-600 whitespace-nowrap text-center">
                                                        €{appointment.appointmentFee || 0}
                                                    </TableCell>
                                                    <TableCell className="whitespace-nowrap text-center">
                                                        <Badge
                                                            variant="outline"
                                                            className={`rounded-full px-2.5 py-0.5 text-[10px] font-medium inline-flex ${appointment.status === "confirmed" ? "bg-emerald-50 text-emerald-700 border-emerald-200" :
                                                                appointment.status === "cancelled" ? "bg-red-50 text-red-700 border-red-200" :
                                                                    (appointment.status === "no-show" || appointment.status === "no_show") ? "bg-orange-50 text-orange-700 border-orange-200" :
                                                                        appointment.status === "pending" ? "bg-blue-50 text-blue-700 border-blue-200" :
                                                                            "bg-gray-50 text-gray-700 border-gray-200"
                                                                }`}
                                                        >
                                                            {(appointment.status === "no-show" || appointment.status === "no_show") ? t("customers.appointments.noShow").toUpperCase() : appointment.status?.toUpperCase() || "PENDING"}
                                                        </Badge>
                                                    </TableCell>
                                                    <TableCell className="text-center">
                                                        {appointment.status === "pending" && (
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                onClick={() => markNoShow(appointment._id)}
                                                                disabled={isPending}
                                                                className="h-8 text-[10px] font-semibold border-orange-200 text-orange-700 hover:bg-orange-50 hover:text-orange-800"
                                                            >
                                                                {t("customers.appointments.markAsNoShow")}
                                                            </Button>
                                                        )}
                                                    </TableCell>
                                                </TableRow>
                                            )
                                        })
                                    )}
                                </TableBody>
                            </Table>

                            {/* Pagination */}
                            {total > pageSize && (
                                <div className="flex items-center justify-between px-6 py-4 bg-gray-50/50 border-t items-center">
                                    <div className="text-sm text-gray-500">
                                        {t("common.showing")} <span className="font-medium text-gray-900">{((currentPage - 1) * pageSize) + 1}</span> {t("common.to")} <span className="font-medium text-gray-900">{Math.min(currentPage * pageSize, total)}</span> {t("common.of")} <span className="font-medium text-gray-900">{total}</span> {t("staff.detail.appointments").toLowerCase()}
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                                            disabled={currentPage === 1}
                                            className="h-8 w-8 p-0"
                                        >
                                            <ChevronLeft className="h-4 w-4" />
                                        </Button>
                                        <div className="text-sm font-medium text-gray-700 min-w-20 text-center">
                                            {t("staff.detail.page")} {currentPage} {t("common.of")} {Math.ceil(total / pageSize)}
                                        </div>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setCurrentPage(prev => prev + 1)}
                                            disabled={currentPage >= Math.ceil(total / pageSize)}
                                            className="h-8 w-8 p-0"
                                        >
                                            <ChevronRight className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>
                <TabsContent value="calls">
                    <ClientCallLogs clientId={id} />
                </TabsContent>
                <TabsContent value="whatsapp">
                    <ClientWhatsAppSessions clientId={id} />
                </TabsContent>
            </CustomTabs>
        </div>
    )
}
