"use client"
import { useAuth } from "@/context/AuthContext"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { User, Mail, Clock, Shield, CheckCircle, Camera, Loader2, Globe, MapPin, Instagram, Facebook, Phone, Calendar, Info, Link as LinkIcon, Edit, Map } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useUpdateProfileImage } from "@/lib/react-query/hooks/auth"
import { useRef, useState } from "react"
import { useTranslations } from "next-intl"
import { EditProfileModal } from "./EditProfileModal"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

const ProfileMain = () => {
  const { user } = useAuth()
  const updateProfileImage = useUpdateProfileImage()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const t = useTranslations('profile')
  const [isEditModalOpen, setIsEditModalOpen] = useState(false)

  // Handle file selection and upload
  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const formData = new FormData()
      formData.append("image", file)
      updateProfileImage.mutate(formData)
    }
    // Reset input so same file can be selected again
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  // Trigger file input click
  const handleAvatarClick = () => {
    fileInputRef.current?.click()
  }

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <User className="w-12 h-12 mx-auto mb-4 text-gray-400" />
          <p className="text-gray-500">{t('loading')}</p>
        </div>
      </div>
    )
  }

  // Create initials from name
  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(word => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2)
  }

  // Format timezone for display
  const formatTimezone = (timezone: string) => {
    return timezone.replace('_', ' ').replace('/', ' / ')
  }

  return (
    <div className="w-full max-w-4xl mx-auto space-y-6">
      {/* Profile Header Header */}
      <div className="relative overflow-hidden rounded-[2rem] bg-indigo-950 p-1 shadow-2xl">
        <div className="absolute inset-0 bg-primary-gradient opacity-90" />
        <div className="absolute -right-24 -top-24 h-64 w-64 rounded-full bg-white/10 blur-3xl" />
        <div className="absolute -bottom-12 -left-12 h-48 w-48 rounded-full bg-blue-400/20 blur-2xl" />

        <Card className="relative border-0 bg-transparent text-white shadow-none">
          <CardContent className="p-8 sm:p-10">
            <div className="flex flex-col md:flex-row items-center gap-8 md:gap-10">
              {/* Avatar section */}
              <div className="relative group shrink-0">
                <div className="absolute -inset-1 rounded-full bg-linear-to-tr from-blue-400 to-indigo-400 opacity-75 blur-sm transition duration-500 group-hover:opacity-100 group-hover:duration-200" />
                <div
                  className="relative cursor-pointer"
                  onClick={handleAvatarClick}
                >
                  <Avatar className="h-28 w-28 md:h-32 md:w-32 border-4 border-white/20 ring-4 ring-black/10 transition-transform duration-500 group-hover:scale-105 shadow-2xl">
                    <AvatarImage src={user.imageUrl} alt={user?.name ?? ""} className="object-cover" />
                    <AvatarFallback className="text-3xl font-black bg-white text-indigo-950">
                      {getInitials(user?.name || "AV")}
                    </AvatarFallback>
                  </Avatar>
                  <div className={`absolute inset-0 flex items-center justify-center bg-black/40 rounded-full transition-all duration-300 ${updateProfileImage.isPending ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 group-hover:backdrop-blur-xs'}`}>
                    {updateProfileImage.isPending ? (
                      <Loader2 className="w-8 h-8 text-white animate-spin" />
                    ) : (
                      <Camera className="w-8 h-8 text-white" />
                    )}
                  </div>
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleImageSelect}
                  className="hidden"
                />
              </div>

              {/* Profile details */}
              <div className="text-center md:text-left flex-1 space-y-4">
                <div className="space-y-2">
                  <div className="flex flex-col md:flex-row md:items-center gap-3 justify-center md:justify-start">
                    <h1 className="text-3xl md:text-4xl font-black tracking-tight text-white drop-shadow-md">
                      {user.name}
                    </h1>
                    <div className="flex justify-center md:justify-start">
                      <Badge className="bg-white/20 hover:bg-white/30 text-white border-0 backdrop-blur-md px-3 py-1 text-xs font-black uppercase tracking-widest">
                        <CheckCircle className="w-3.5 h-3.5 mr-1.5 text-blue-300" />
                        {t('verified')}
                      </Badge>
                    </div>
                  </div>
                  <div className="flex items-center justify-center md:justify-start gap-2 text-blue-100/80 font-medium">
                    <Mail className="w-4 h-4" />
                    <p className="text-lg">{user.email}</p>
                  </div>
                </div>

                <div className="flex flex-wrap items-center justify-center md:justify-start gap-4">
                  <Button
                    onClick={() => setIsEditModalOpen(true)}
                    className="h-11 px-8 rounded-xl bg-white text-indigo-950 hover:bg-indigo-50 hover:scale-105 transition-all duration-300 font-black shadow-lg shadow-black/10"
                  >
                    <Edit className="w-4 h-4 mr-2" />
                    {t('editProfile')}
                  </Button>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Profile Details Tabs */}
      <Tabs defaultValue="overview" className="w-full">
        <div className="bg-white p-4 rounded-3xl shadow-sm border border-gray-100 mb-6">
          <TabsList className="w-full justify-start h-12 bg-gray-100/80 p-1 rounded-xl gap-1 overflow-x-auto no-scrollbar">
            <TabsTrigger value="overview" className="rounded-lg h-full px-6 text-sm font-bold flex items-center gap-2 transition-all data-[state=active]:bg-blue-950 data-[state=active]:text-white text-gray-600 data-[state=inactive]:hover:bg-gray-200 border-none">
              <Info className="w-4 h-4" />
              <span>{t('businessInformation')}</span>
            </TabsTrigger>

            <TabsTrigger value="schedule" className="rounded-lg h-full px-6 text-sm font-bold flex items-center gap-2 transition-all data-[state=active]:bg-blue-950 data-[state=active]:text-white text-gray-600 data-[state=inactive]:hover:bg-gray-200 border-none">
              <Clock className="w-4 h-4" />
              <span>{t('openingHours')}</span>
            </TabsTrigger>
          </TabsList>
        </div>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6 focus-visible:outline-none">
          <div className="flex flex-col md:flex-row gap-6 items-start">
            {/* Contact Information */}
            <Card className="flex-1 border-0 shadow-sm hover:shadow-md transition-all duration-300 rounded-3xl overflow-hidden">
              <CardHeader className="bg-blue-50/50 pb-4">
                <CardTitle className="flex items-center gap-2 text-lg font-bold text-blue-900">
                  <Mail className="w-5 h-5" />
                  {t('contactInformation')}
                </CardTitle>
              </CardHeader>
              <CardContent className="pt-0 space-y-3">
                <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-2xl hover:bg-blue-50/30 transition-colors">
                  <div className="p-2.5 bg-white rounded-xl shadow-xs">
                    <Mail className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[10px] font-extrabold text-blue-600 uppercase tracking-widest mb-0.5">{t('emailAddress')}</p>
                    <p className="text-sm font-bold text-gray-900 truncate">{user.email}</p>
                  </div>
                </div>


                {user.website && (
                  <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-2xl hover:bg-blue-50/30 transition-colors">
                    <div className="p-2.5 bg-white rounded-xl shadow-xs">
                      <Globe className="w-5 h-5 text-blue-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-[10px] font-extrabold text-blue-600 uppercase tracking-widest mb-0.5">{t('website')}</p>
                      <a href={user.website} target="_blank" rel="noopener noreferrer" className="text-sm font-bold text-blue-600 hover:text-blue-700 hover:underline truncate block transition-colors">
                        {user.website.replace(/^https?:\/\//, '')}
                      </a>
                    </div>
                  </div>
                )}

                {/* Address Information */}
                {(user.address || (user.full_address && (user.full_address.street || user.full_address.city))) && (
                  <div className="space-y-1 pt-0 border-t border-gray-100">
                    <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-2xl hover:bg-blue-50/30 transition-colors">
                      <div className="p-2.5 bg-white rounded-xl shadow-xs">
                        <MapPin className="w-5 h-5 text-blue-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-[10px] font-extrabold text-blue-600 uppercase tracking-widest mb-0.5">{t('address')}</p>
                        <p className="text-sm font-bold text-gray-900 leading-tight">
                          {user.address || user.full_address?.street}
                          {user.full_address?.city && <span className="text-gray-500 font-medium">, {user.full_address.city}</span>}
                        </p>
                        {user.full_address?.country && (
                          <p className="text-xs font-bold text-gray-400 mt-1">{user.full_address.country}</p>
                        )}
                      </div>
                    </div>
                  </div>
                )}

                {/* Social Links */}
                {user.social_links && (user.social_links.instagram || user.social_links.facebook || user.social_links.google || user.social_links.tiktok) && (
                  <div className="pt-0 border-t border-gray-100">
                    <p className="text-[10px] font-extrabold text-blue-600 uppercase tracking-widest mb-3 px-1">{t('socialLinks')}</p>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <SocialLink href={user.social_links?.instagram} icon={Instagram} label="Instagram" color="purple" />
                      <SocialLink href={user.social_links?.facebook} icon={Facebook} label="Facebook" color="blue" />
                      <SocialLink href={user.social_links?.google} icon={Globe} label="Google" color="orange" />
                      <SocialLink href={user.social_links?.tiktok} icon={undefined} label="TikTok" color="gray" isTiktok />
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Business Information */}
            <Card className="flex-1 border-0 shadow-sm hover:shadow-md transition-all duration-300 rounded-3xl overflow-hidden">
              <CardHeader className="bg-indigo-50/50 pb-4">
                <CardTitle className="flex items-center gap-2 text-lg font-bold text-indigo-900">
                  <Info className="w-5 h-5" />
                  {t('businessInformation')}
                </CardTitle>
              </CardHeader>
              <CardContent className="pt-0 space-y-3">
                <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-2xl hover:bg-indigo-50/30 transition-colors">
                  <div className="p-2.5 bg-white rounded-xl shadow-xs">
                    <User className="w-5 h-5 text-indigo-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[10px] font-extrabold text-indigo-600 uppercase tracking-widest mb-0.5">{t('ownerName')}</p>
                    <p className="text-sm font-bold text-gray-900 truncate">{user.owner_name || t('notSet')}</p>
                  </div>
                </div>

                <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-2xl hover:bg-indigo-50/30 transition-colors">
                  <div className="p-2.5 bg-white rounded-xl shadow-xs">
                    <Clock className="w-5 h-5 text-indigo-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[10px] font-extrabold text-indigo-600 uppercase tracking-widest mb-0.5">{t('timezone')}</p>
                    <p className="text-sm font-bold text-gray-900 truncate">{user.timezone ? formatTimezone(user.timezone) : t('notSet')}</p>
                  </div>
                </div>

                <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-2xl hover:bg-indigo-50/30 transition-colors">
                  <div className="p-2.5 bg-white rounded-xl shadow-xs">
                    <Shield className="w-5 h-5 text-indigo-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[10px] font-extrabold text-indigo-600 uppercase tracking-widest mb-0.5">{t('accountStatus')}</p>
                    <div className="flex gap-2">
                      <Badge variant="outline" className="text-green-600 border-green-200 bg-green-50 h-5 px-2 text-[10px] font-extrabold shadow-sm">
                        <CheckCircle className="w-2.5 h-2.5 mr-1" />
                        {t('verified')}
                      </Badge>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>



          </div>
        </TabsContent>



        {/* Working Hours Tab */}
        <TabsContent value="schedule" className="space-y-6 focus-visible:outline-none">
          <div className="grid grid-cols-1 gap-6">
            {/* Opening Hours */}
            {user.opening_hours && user.opening_hours.length > 0 && (
              <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300 rounded-3xl overflow-hidden">
                <CardHeader className="bg-emerald-50/50 pb-4">
                  <CardTitle className="flex items-center gap-2 text-lg font-bold text-emerald-900">
                    <Clock className="w-5 h-5" />
                    {t('openingHours')}
                  </CardTitle>
                </CardHeader>
                <CardContent className="pt-6">
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    {DAYS.map((day) => {
                      const daySlots = user.opening_hours?.filter(oh => oh.day.toLowerCase() === day.toLowerCase()) || [];
                      const isClosed = daySlots.length === 0 || daySlots.every(s => s.closed);

                      return (
                        <div key={day} className={`p-5 rounded-3xl flex flex-col transition-all group ${isClosed ? 'bg-gray-50 border border-gray-100 hover:border-gray-200' : 'bg-emerald-50/50 border border-emerald-100/50 hover:bg-emerald-50 hover:shadow-sm'}`}>
                          <span className="text-xs font-extrabold text-emerald-800 uppercase tracking-widest mb-3 opacity-80">{day}</span>
                          {isClosed ? (
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-bold text-gray-400 italic uppercase">{t('closed')}</span>
                            </div>
                          ) : (
                            <div className="flex flex-col gap-3">
                              {daySlots.filter(s => !s.closed).map((slot, idx) => (
                                <div key={idx} className="flex items-center gap-2">
                                  <span className="text-xl font-black text-emerald-950">{slot.open}</span>
                                  <span className="text-emerald-300 font-bold">→</span>
                                  <span className="text-xl font-black text-emerald-950">{slot.close}</span>
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Holidays */}
            {user.holidays && user.holidays.length > 0 && (
              <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300 rounded-3xl overflow-hidden">
                <CardHeader className="bg-amber-50/50 pb-4">
                  <CardTitle className="flex items-center gap-2 text-lg font-bold text-amber-900">
                    <Calendar className="w-5 h-5" />
                    {t('holidays')}
                  </CardTitle>
                </CardHeader>
                <CardContent className="pt-6">
                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                    {user.holidays.map((holiday) => (
                      <div key={holiday._id || holiday.date} className="flex items-center gap-4 p-5 bg-amber-50/30 rounded-3xl border border-amber-100/30 hover:bg-amber-50 hover:shadow-xs transition-all">
                        <div className="p-3 bg-white rounded-2xl shadow-xs">
                          <Calendar className="w-6 h-6 text-amber-600" />
                        </div>
                        <div>
                          <p className="text-sm font-black text-amber-950 leading-tight mb-0.5">{holiday.reason}</p>
                          <p className="text-[10px] font-extrabold text-amber-700 uppercase tracking-wider">
                            {new Date(holiday.date).toLocaleDateString(undefined, { day: 'numeric', month: 'long', year: 'numeric' })}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </TabsContent>
      </Tabs>

      <EditProfileModal
        user={user}
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
      />
    </div >
  )
}

interface SocialLinkProps {
  href?: string
  icon: any
  label: string
  color: string
  isTiktok?: boolean
}

const SocialLink = ({ href, icon: Icon, label, color, isTiktok }: SocialLinkProps) => {
  if (!href) return null

  const bgColors: Record<string, string> = {
    purple: 'bg-purple-50 hover:bg-purple-100',
    blue: 'bg-blue-50 hover:bg-blue-100',
    orange: 'bg-orange-50 hover:bg-orange-100',
    gray: 'bg-gray-50 hover:bg-gray-100',
  }

  const iconColors: Record<string, string> = {
    purple: 'text-purple-600',
    blue: 'text-blue-600',
    orange: 'text-orange-600',
    gray: 'text-gray-900',
  }

  return (
    <a href={href} target="_blank" rel="noopener noreferrer"
      className={`flex items-center gap-4 p-4 ${bgColors[color]} rounded-2xl transition-all group border border-transparent hover:border-white hover:shadow-md`}>
      <div className={`${iconColors[color]} group-hover:scale-110 transition-transform`}>
        {isTiktok ? <span className="text-xl font-black">♪</span> : Icon && <Icon className="w-6 h-6" />}
      </div>
      <span className="text-sm font-extrabold text-gray-800 tracking-tight">{label}</span>
    </a>
  )
}

export default ProfileMain