'use client';

import { useRef, useState } from 'react';
import { useAppStore, type AppSection } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Camera,
  ChevronRight,
  Edit3,
  ListChecks,
  Package,
  Heart,
  Bell,
  Settings,
  HelpCircle,
  Info,
  LogOut,
  UserPlus,
  LogIn,
  ShoppingBag,
  Star,
  ImagePlus,
} from 'lucide-react';

const quickAvatars = [
  { emoji: '😊', bg: 'bg-amber-100 dark:bg-amber-900/30' },
  { emoji: '👨', bg: 'bg-sky-100 dark:bg-sky-900/30' },
  { emoji: '👩', bg: 'bg-pink-100 dark:bg-pink-900/30' },
  { emoji: '🧑', bg: 'bg-emerald-100 dark:bg-emerald-900/30' },
  { emoji: '👦', bg: 'bg-violet-100 dark:bg-violet-900/30' },
  { emoji: '👧', bg: 'bg-rose-100 dark:bg-rose-900/30' },
  { emoji: '👴', bg: 'bg-gray-100 dark:bg-gray-800' },
  { emoji: '👵', bg: 'bg-teal-100 dark:bg-teal-900/30' },
  { emoji: '🧔', bg: 'bg-orange-100 dark:bg-orange-900/30' },
  { emoji: '👱', bg: 'bg-yellow-100 dark:bg-yellow-900/30' },
  { emoji: '🧕', bg: 'bg-indigo-100 dark:bg-indigo-900/30' },
  { emoji: '👲', bg: 'bg-lime-100 dark:bg-lime-900/30' },
];

const roleColors: Record<string, string> = {
  general: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  student: 'bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-400',
  houseOwner: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  shopOwner: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
};

const roleLabels: Record<string, string> = {
  general: 'General',
  student: 'Student',
  houseOwner: 'House Owner',
  shopOwner: 'Shop Owner',
};

interface MenuItemProps {
  icon: React.ElementType;
  label: string;
  onClick: () => void;
  danger?: boolean;
}

function MenuItem({ icon: Icon, label, onClick, danger }: MenuItemProps) {
  return (
    <button
      onClick={onClick}
      className={`flex w-full items-center gap-3 rounded-xl px-4 py-3.5 transition-colors duration-150 hover:bg-accent active:bg-accent/80 ${
        danger ? 'text-destructive hover:bg-destructive/5' : ''
      }`}
    >
      <Icon className={`h-5 w-5 ${danger ? 'text-destructive' : 'text-muted-foreground'}`} strokeWidth={1.75} />
      <span className={`flex-1 text-left text-sm font-medium ${danger ? 'text-destructive' : 'text-foreground'}`}>
        {label}
      </span>
      <ChevronRight className={`h-4 w-4 ${danger ? 'text-destructive/50' : 'text-muted-foreground/50'}`} />
    </button>
  );
}

interface StatCardProps {
  value: number | string;
  label: string;
  onClick: () => void;
}

function StatCard({ value, label, onClick }: StatCardProps) {
  return (
    <button
      onClick={onClick}
      className="flex flex-col items-center gap-1 rounded-xl bg-background p-3 transition-colors duration-150 hover:bg-accent active:bg-accent/80"
    >
      <span className="text-lg font-bold text-primary">{value}</span>
      <span className="text-[11px] text-muted-foreground">{label}</span>
    </button>
  );
}

export default function ProfileModule() {
  const { language, isLoggedIn, user, logout, updateUser, setCurrentSection } = useAppStore();
  const [avatarDialogOpen, setAvatarDialogOpen] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const navigateTo = (section: AppSection) => {
    setCurrentSection(section);
  };

  const handleSelectQuickAvatar = async (emoji: string) => {
    updateUser({ avatar: emoji });
    setAvatarDialogOpen(false);
    // Persist to database
    if (user?.id) {
      try {
        await fetch('/api/auth/update-profile', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ userId: user.id, avatar: emoji }),
        });
      } catch { /* silent fail */ }
    }
  };

  const handleGallerySelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = async (event) => {
        const dataUrl = event.target?.result as string;
        updateUser({ avatar: dataUrl });
        setAvatarDialogOpen(false);
        // Persist to database
        if (user?.id) {
          try {
            await fetch('/api/auth/update-profile', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ userId: user.id, avatar: dataUrl }),
            });
          } catch { /* silent fail */ }
        }
      };
      reader.readAsDataURL(file);
    }
    // Reset input so same file can be selected again
    e.target.value = '';
  };

  // Determine what to render inside the avatar
  const renderAvatarContent = (size: string = 'h-24 w-24') => {
    if (!user) return null;

    const initials = user.name
      .split(' ')
      .map((n) => n[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);

    const isEmoji = user.avatar && !user.avatar.startsWith('data:') && !user.avatar.startsWith('http');
    const isImage = user.avatar && (user.avatar.startsWith('data:') || user.avatar.startsWith('http'));

    return (
      <Avatar className={`${size} border-4 border-primary-foreground/20 shadow-xl`}>
        {isImage && user.avatar ? (
          <AvatarImage src={user.avatar} alt={user.name} className="object-cover" />
        ) : null}
        <AvatarFallback
          className={`bg-primary-foreground/20 font-bold text-primary-foreground ${
            isEmoji ? 'text-4xl' : 'text-2xl'
          }`}
        >
          {isEmoji ? user.avatar : initials}
        </AvatarFallback>
      </Avatar>
    );
  };

  // Logged Out State
  if (!isLoggedIn || !user) {
    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col items-center justify-center px-6 py-12">
        {/* App Branding */}
        <div className="mb-8 flex flex-col items-center gap-4">
          <img
            src="/logo-needyfy.png"
            alt="Needyfy Logo"
            className="h-24 w-24 rounded-3xl object-cover shadow-lg shadow-primary/25"
          />
          <div className="text-center">
            <h1 className="gradient-text text-3xl font-bold tracking-tight">
              {t('app.name', language)}
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              {t('app.tagline', language)}
            </p>
          </div>
        </div>

        {/* Login Message */}
        <div className="mb-8 rounded-2xl bg-accent/50 p-6 text-center">
          <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
            <UserPlus className="h-6 w-6 text-primary" />
          </div>
          <p className="text-sm font-medium text-foreground">
            {language === 'en' ? 'Login to access all features' : 'সব ফিচার ব্যবহার করতে লগইন করুন'}
          </p>
          <p className="mt-1 text-xs text-muted-foreground">
            {language === 'en'
              ? 'Manage your listings, orders, and more'
              : 'আপনার তালিকা, অর্ডার এবং আরও অনেক কিছু পরিচালনা করুন'}
          </p>
        </div>

        {/* Auth Buttons */}
        <div className="flex w-full max-w-xs flex-col gap-3">
          <Button
            onClick={() => navigateTo('auth')}
            className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold shadow-md shadow-primary/20"
            size="lg"
          >
            <LogIn className="mr-2 h-4 w-4" />
            {t('profile.login', language)}
          </Button>
          <Button
            variant="outline"
            onClick={() => navigateTo('auth')}
            className="w-full border-primary/20 font-semibold text-primary hover:bg-primary/5"
            size="lg"
          >
            <UserPlus className="mr-2 h-4 w-4" />
            {t('profile.signup', language)}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="custom-scrollbar flex min-h-[calc(100vh-8rem)] flex-col overflow-y-auto pb-6">
      {/* Profile Header */}
      <div className="relative bg-gradient-to-br from-primary via-primary/90 to-primary/70 px-6 pb-8 pt-8">
        <div className="flex flex-col items-center gap-3">
          {/* Avatar with Camera Overlay */}
          <div className="relative">
            {renderAvatarContent()}
            <button
              className="absolute bottom-0 right-0 flex h-8 w-8 items-center justify-center rounded-full bg-primary-foreground shadow-md transition-transform hover:scale-105 active:scale-95"
              onClick={() => setAvatarDialogOpen(true)}
              aria-label="Change avatar"
            >
              <Camera className="h-4 w-4 text-primary" />
            </button>
          </div>

          {/* Name & Email */}
          <div className="text-center">
            <h2 className="text-xl font-bold text-primary-foreground">{user.name}</h2>
            <p className="mt-0.5 text-sm text-primary-foreground/70">{user.email}</p>
            {user.phone && (
              <p className="mt-0.5 text-xs text-primary-foreground/60">{user.phone}</p>
            )}
          </div>

          {/* Role Badges */}
          {user.roles && user.roles.length > 0 && (
            <div className="mt-1 flex flex-wrap items-center justify-center gap-2">
              {user.roles.map((role) => (
                <Badge
                  key={role}
                  variant="secondary"
                  className={`border-0 text-[11px] font-medium ${
                    roleColors[role] || 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300'
                  }`}
                >
                  {roleLabels[role] || role}
                </Badge>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Stats Row */}
      <div className="-mt-4 px-4">
        <Card className="shadow-md">
          <CardContent className="grid grid-cols-4 gap-2 p-2">
            <StatCard value={3} label={language === 'en' ? 'Listings' : 'তালিকা'} onClick={() => navigateTo('profile')} />
            <StatCard value={5} label={language === 'en' ? 'Orders' : 'অর্ডার'} onClick={() => navigateTo('orders')} />
            <StatCard value={8} label={language === 'en' ? 'Favourites' : 'পছন্দ'} onClick={() => navigateTo('favourites')} />
            <StatCard value={12} label={language === 'en' ? 'Reviews' : 'রিভিউ'} onClick={() => navigateTo('profile')} />
          </CardContent>
        </Card>
      </div>

      {/* Menu Items */}
      <div className="mt-6 px-4">
        <Card>
          <CardContent className="p-2">
            <MenuItem
              icon={Edit3}
              label={t('profile.editProfile', language)}
              onClick={() => navigateTo('settings')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={ListChecks}
              label={t('profile.myListings', language)}
              onClick={() => navigateTo('house-rental')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={Package}
              label={t('profile.myOrders', language)}
              onClick={() => navigateTo('orders')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={Heart}
              label={t('fav.title', language)}
              onClick={() => navigateTo('favourites')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={Bell}
              label={t('settings.notifications', language)}
              onClick={() => navigateTo('profile')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={Settings}
              label={t('settings.title', language)}
              onClick={() => navigateTo('settings')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={HelpCircle}
              label={t('settings.help', language)}
              onClick={() => navigateTo('profile')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={Info}
              label={language === 'en' ? 'About Needyfy' : 'Needyfy সম্পর্কে'}
              onClick={() => navigateTo('profile')}
            />
            <Separator className="mx-4" />
            <MenuItem
              icon={LogOut}
              label={t('profile.logout', language)}
              onClick={() => logout()}
              danger
            />
          </CardContent>
        </Card>
      </div>

      {/* Avatar Selection Dialog */}
      <Dialog open={avatarDialogOpen} onOpenChange={setAvatarDialogOpen}>
        <DialogContent className="sm:max-w-[380px]">
          <DialogHeader>
            <DialogTitle>{t('profile.changeAvatar', language)}</DialogTitle>
            <DialogDescription>
              {language === 'en'
                ? 'Choose a quick avatar or upload your own photo'
                : 'একটি দ্রুত অবতার বেছে নিন বা আপনার নিজের ছবি আপলোড করুন'}
            </DialogDescription>
          </DialogHeader>

          {/* Quick Avatars Grid */}
          <div className="space-y-3">
            <h4 className="text-sm font-medium text-muted-foreground">
              {t('profile.quickAvatars', language)}
            </h4>
            <div className="grid grid-cols-4 gap-3">
              {quickAvatars.map((avatar) => (
                <button
                  key={avatar.emoji}
                  onClick={() => handleSelectQuickAvatar(avatar.emoji)}
                  className={`flex h-14 w-full items-center justify-center rounded-full text-2xl transition-all duration-150 hover:scale-110 active:scale-95 ${avatar.bg} ${
                    user?.avatar === avatar.emoji ? 'ring-2 ring-primary ring-offset-2' : ''
                  }`}
                >
                  {avatar.emoji}
                </button>
              ))}
            </div>
          </div>

          <Separator />

          {/* Add from Gallery */}
          <div className="space-y-3">
            <h4 className="text-sm font-medium text-muted-foreground">
              {t('profile.addFromGallery', language)}
            </h4>
            <Button
              variant="outline"
              className="w-full gap-2"
              onClick={() => fileInputRef.current?.click()}
            >
              <ImagePlus className="h-4 w-4" />
              {language === 'en' ? 'Choose Photo' : 'ছবি বেছে নিন'}
            </Button>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleGallerySelect}
            />
          </div>

          {/* Preview current avatar */}
          {user.avatar && (
            <>
              <Separator />
              <div className="flex items-center gap-3">
                <span className="text-xs text-muted-foreground">
                  {language === 'en' ? 'Current:' : 'বর্তমান:'}
                </span>
                <div className="h-10 w-10 overflow-hidden rounded-full bg-primary-foreground/20">
                  {user.avatar.startsWith('data:') || user.avatar.startsWith('http') ? (
                    <img src={user.avatar} alt="Avatar" className="h-full w-full object-cover" />
                  ) : (
                    <div className="flex h-full w-full items-center justify-center text-xl">
                      {user.avatar}
                    </div>
                  )}
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  className="ml-auto text-xs text-destructive hover:text-destructive"
                  onClick={async () => {
                    updateUser({ avatar: undefined });
                    setAvatarDialogOpen(false);
                    // Persist removal to database
                    if (user?.id) {
                      try {
                        await fetch('/api/auth/update-profile', {
                          method: 'POST',
                          headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify({ userId: user.id, avatar: null }),
                        });
                      } catch { /* silent fail */ }
                    }
                  }}
                >
                  {language === 'en' ? 'Remove' : 'সরান'}
                </Button>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
