'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion } from 'framer-motion';
import {
  User,
  Shield,
  Trash2,
  LogOut,
  ChevronLeft,
  Bell,
  Lock,
  HelpCircle,
  MessageCircle,
  FileText,
  Eye,
  Loader2,
  AlertTriangle,
  X
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import toast, { Toaster } from 'react-hot-toast';
import AuthService from '../services/AuthService';
import { changePassword, deleteMyAccount, submitReport } from '../utils/api';

export default function SettingsPage() {
  const { t, i18n } = useTranslation();
  const router = useRouter();
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deletePassword, setDeletePassword] = useState('');
  const [isDeleting, setIsDeleting] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  const [showContactDialog, setShowContactDialog] = useState(false);
  const [contactSubject, setContactSubject] = useState('');
  const [contactBody, setContactBody] = useState('');
  const [isSendingContact, setIsSendingContact] = useState(false);

  const handleSignOut = () => {
    AuthService.deleteToken();
    toast.success(t('logout-success'));
    router.push('/');
  };

  const handleDeleteAccount = async () => {
    if (!deletePassword) {
      toast.error(t('enter-password-prompt'));
      return;
    }
    setIsDeleting(true);
    try {
      await deleteMyAccount(deletePassword);
      AuthService.deleteToken();
      toast.success(t('delete-account-success'));
      router.push('/');
    } catch (err) {
      console.error('Delete account error:', err);
      toast.error(err.message || t('delete-account-failed'));
    } finally {
      setIsDeleting(false);
      setShowDeleteDialog(false);
      setDeletePassword('');
    }
  };

  const handleSendContact = async () => {
    if (!contactSubject.trim() || !contactBody.trim()) {
      toast.error(t('fill-subject-and-message'));
      return;
    }

    setIsSendingContact(true);
    try {
      await submitReport(contactSubject.trim(), contactBody.trim());
      toast.success(t('send-success'));
      setShowContactDialog(false);
      setContactSubject('');
      setContactBody('');
    } catch (err) {
      toast.error(err.message || t('send-error'));
    } finally {
      setIsSendingContact(false);
    }
  };

  const sections = [
    {
      title: t('account'),
      items: [
        { icon: User, label: t('profile'), href: '/profile', desc: t('profileDesc') },
        { icon: Lock, label: t('change-password'), href: '/change-password', desc: t('change-password-desc') },
        { icon: Shield, label: t('account-verification'), href: '/account-verification', desc: t('account-verification-desc') },
      ]
    },
    {
      title: t('notifications'),
      items: [
        { icon: Bell, label: t('notifications'), href: '/notifications', desc: t('notification-preferences-desc') },
      ]
    },
    {
      title: t('support'),
      items: [
        { icon: HelpCircle, label: t('faq'), href: '/faq', desc: t('faq-desc') },
        { icon: MessageCircle, label: t('contactUs'), desc: t('contact-us-desc'), action: () => setShowContactDialog(true) },
        { icon: FileText, label: t('terms-and-conditions'), href: '/terms', desc: t('terms-desc') },
        { icon: Eye, label: t('privacy'), href: '/privacy', desc: t('privacy-desc') },
      ]
    },
  ];

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: { staggerChildren: 0.08 }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 pb-28" dir={i18n.language === 'ar' ? 'rtl' : 'ltr'}>
      <Toaster position="top-center" reverseOrder={false} />

      <div className="container mx-auto px-4 max-w-2xl">
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex items-center gap-3 mb-8"
        >
          <Link
            href="/profile"
            className="p-2 rounded-xl hover:bg-gray-200 transition-colors text-gray-600"
          >
            <ChevronLeft className="w-5 h-5" />
          </Link>
          <h1 className="text-2xl font-bold text-gray-900">{t('settings')}</h1>
        </motion.div>

        <motion.div
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className="space-y-6"
        >
          {sections.map((section) => (
            <motion.div
              key={section.title}
              variants={itemVariants}
              className="bg-white rounded-2xl shadow-sm overflow-hidden"
            >
              <div className="px-6 py-4 border-b border-gray-100">
                <h2 className="text-lg font-semibold text-gray-800">{section.title}</h2>
              </div>
              <div className="divide-y divide-gray-50">
                {section.items.map((item) => {
                  const Icon = item.icon;

                  const content = (
                    <>
                      <div className="w-10 h-10 rounded-xl bg-amber-50 flex items-center justify-center flex-shrink-0 group-hover:bg-amber-100 transition-colors">
                        <Icon className="w-5 h-5 text-amber-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900">{item.label}</p>
                        <p className="text-xs text-gray-500 truncate">{item.desc}</p>
                      </div>
                      <ChevronLeft className="w-4 h-4 text-gray-400" />
                    </>
                  );

                  if (item.action) {
                    return (
                      <button
                        key={item.label}
                        onClick={item.action}
                        className="w-full flex items-center gap-4 px-6 py-4 hover:bg-gray-50 transition-colors group text-right"
                      >
                        {content}
                      </button>
                    );
                  }

                  return (
                    <Link
                      key={item.label}
                      href={item.href}
                      className="flex items-center gap-4 px-6 py-4 hover:bg-gray-50 transition-colors group"
                    >
                      {content}
                    </Link>
                  );
                })}
              </div>
            </motion.div>
          ))}

          <motion.div variants={itemVariants} className="space-y-4">
            <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-100">
                <h2 className="text-lg font-semibold text-gray-800">{t('security')}</h2>
              </div>
              <div className="p-6">
                <button
                  onClick={() => setShowDeleteDialog(true)}
                  className="w-full flex items-center gap-3 px-4 py-3 rounded-xl border border-red-200 text-red-600 hover:bg-red-50 transition-colors"
                >
                  <Trash2 className="w-5 h-5" />
                  <span className="text-sm font-medium">{t('deleteAccount')}</span>
                </button>
                <p className="text-xs text-gray-500 mt-2 pr-12">
                  {t('delete-account-warning')}
                </p>
              </div>
            </div>

            <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
              <div className="p-6">
                <button
                  onClick={handleSignOut}
                  className="w-full flex items-center gap-3 px-4 py-3 rounded-xl border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
                >
                  <LogOut className="w-5 h-5" />
                  <span className="text-sm font-medium">{t('signOut')}</span>
                </button>
              </div>
            </div>
          </motion.div>
        </motion.div>
      </div>

      {showDeleteDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white rounded-2xl shadow-xl max-w-md w-full p-6"
          >
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                <AlertTriangle className="w-5 h-5 text-red-600" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900">{t('deleteDialogTitle')}</h3>
                <p className="text-sm text-gray-500">{t('deleteDialogWarning')}</p>
              </div>
              <button
                onClick={() => { setShowDeleteDialog(false); setDeletePassword(''); }}
                className="mr-auto p-1 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>

            <p className="text-sm text-gray-600 mb-4">
              {t('delete-account-confirm-desc')}
            </p>

            <input
              type="password"
              value={deletePassword}
              onChange={(e) => setDeletePassword(e.target.value)}
              placeholder={t('enter-password-prompt')}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl mb-4 focus:ring-2 focus:ring-red-500 focus:border-transparent outline-none"
            />

            <div className="flex gap-3">
              <button
                onClick={() => { setShowDeleteDialog(false); setDeletePassword(''); }}
                className="flex-1 px-4 py-3 rounded-xl border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors text-sm font-medium"
              >
                {t('cancel')}
              </button>
              <button
                onClick={handleDeleteAccount}
                disabled={isDeleting}
                className="flex-1 px-4 py-3 rounded-xl bg-red-600 text-white hover:bg-red-700 transition-colors text-sm font-medium disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {isDeleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                {isDeleting ? t('deleting') : t('confirm-delete')}
              </button>
            </div>
          </motion.div>
        </div>
      )}

      {showContactDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white rounded-2xl shadow-xl max-w-md w-full p-6"
          >
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center">
                <MessageCircle className="w-5 h-5 text-amber-600" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900">{t('contactUs')}</h3>
                <p className="text-sm text-gray-500">{t('contact-reply-prompt')}</p>
              </div>
              <button
                onClick={() => {
                  setShowContactDialog(false);
                  setContactSubject('');
                  setContactBody('');
                }}
                className="mr-auto p-1 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>

            <input
              type="text"
              value={contactSubject}
              onChange={(e) => setContactSubject(e.target.value)}
              placeholder={t('subject')}
              maxLength={300}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl mb-4 focus:ring-2 focus:ring-amber-500 focus:border-transparent outline-none"
            />

            <textarea
              value={contactBody}
              onChange={(e) => setContactBody(e.target.value)}
              placeholder={t('write-message-placeholder')}
              rows={5}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl mb-4 focus:ring-2 focus:ring-amber-500 focus:border-transparent outline-none resize-none"
            />

            <div className="flex gap-3">
              <button
                onClick={() => {
                  setShowContactDialog(false);
                  setContactSubject('');
                  setContactBody('');
                }}
                className="flex-1 px-4 py-3 rounded-xl border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors text-sm font-medium"
              >
                {t('cancel')}
              </button>
              <button
                onClick={handleSendContact}
                disabled={isSendingContact}
                className="flex-1 px-4 py-3 rounded-xl bg-amber-600 text-white hover:bg-amber-700 transition-colors text-sm font-medium disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {isSendingContact ? <Loader2 className="w-4 h-4 animate-spin" /> : <MessageCircle className="w-4 h-4" />}
                {isSendingContact ? t('sending') : t('send')}
              </button>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}
