import { useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Upload, Check, Loader2, MessageSquare, AlertCircle } from 'lucide-react';
import { AppApi } from '../../../../core/infrastructure/appApi';
import { useLang } from '../../../../core/infrastructure/i18n';
import type { User as UserType, FriendWithId } from '../../../../core/domain/types';
import { useAuthStore } from '../../../auth/application/authStore';
import { useChatStore } from '../../../chats/application/chatStore';

interface TelegramImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  friends: FriendWithId[];
}

export default function TelegramImportModal({ isOpen, onClose, friends }: TelegramImportModalProps) {
  const { t } = useLang();
  const { user } = useAuthStore();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [step, setStep] = useState<1 | 2 | 3>(1); // 1: upload, 2: map, 3: loading/done
  const [file, setFile] = useState<File | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [names, setNames] = useState<string[]>([]);
  const [mapping, setMapping] = useState<Record<string, string>>({});
  const [groupName, setGroupName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [importedState, setImportedState] = useState<{ count: number; text: string } | null>(null);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (!selectedFile) return;

    if (!selectedFile.name.endsWith('.zip')) {
      setError('Пожалуйста, выберите ZIP-архив экспорта Telegram.');
      return;
    }

    setFile(selectedFile);
    setError(null);
    setLoading(true);

    try {
      const data = await AppApi.analyzeTelegramImport(selectedFile) as any;
      setToken(data.token);
      setNames(data.names);
      
      // Auto-map if possible
      const initialMap: Record<string, string> = {};
      data.names.forEach((name: string) => {
        initialMap[name] = '';
      });
      setMapping(initialMap);
      setStep(2);
    } catch (err: any) {
      console.error(err);
      setError(err.message || 'Ошибка анализа файла');
    } finally {
      setLoading(false);
    }
  };

  const handleExecute = async () => {
    if (!token) return;
    setLoading(true);
    setError(null);

    try {
      const res = await AppApi.executeTelegramImport({ token, mapping, groupName }) as any;
      setImportedState({ count: 0, text: 'Импорт запущен в фоновом режиме' });
      setStep(3);

      // Обновляем список чатов и выбираем новый
      await useChatStore.getState().loadChats();
      if (res.chatId) {
        useChatStore.getState().setActiveChat(res.chatId);
      }
    } catch (err: any) {
      console.error(err);
      setError(err.message || 'Ошибка импорта');
    } finally {
      setLoading(false);
    }
  };

  const reset = () => {
    setStep(1);
    setFile(null);
    setToken(null);
    setNames([]);
    setMapping({});
    setGroupName('');
    setError(null);
    setImportedState(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="absolute inset-0 bg-black/40 backdrop-blur-md"
            onClick={step === 3 && importedState ? handleClose : undefined}
          />
          <motion.div
            initial={{ opacity: 0, scale: 0.9, y: 40 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 40 }}
            className="relative w-full max-w-[480px] bg-[#121212]/95 backdrop-blur-3xl border border-white/10 shadow-[0_32px_64px_rgba(0,0,0,0.8)] rounded-[2.5rem] overflow-hidden flex flex-col max-h-[90vh] slide-on-ice"
          >
            {/* Header */}
            <div className="h-14 px-8 flex items-center justify-between shrink-0 mt-2">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-2xl bg-linear-to-br from-[#0088cc] to-[#00aaff] flex items-center justify-center shadow-inner border border-white/10">
                   <MessageSquare size={18} className="text-white" />
                </div>
                <h3 className="text-[17px] font-black uppercase tracking-tight text-white/90">{t('importTelegram')}</h3>
              </div>
              <button
                onClick={handleClose}
                className="w-10 h-10 flex items-center justify-center text-zinc-500 hover:text-white bg-white/5 hover:bg-white/10 rounded-2xl transition-all active:scale-[0.85]"
              >
                <X size={20} />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
              {error && (
                <div className="mb-6 p-5 rounded-3xl bg-error/10 border border-error/20 flex gap-4 text-error animate-in fade-in slide-in-from-top-2">
                  <AlertCircle size={22} className="shrink-0" />
                  <div className="flex flex-col gap-1">
                    <span className="text-[10px] font-black uppercase tracking-widest opacity-60">{t('error')}</span>
                    <p className="text-[13px] leading-relaxed font-medium">{error}</p>
                   </div>
                </div>
              )}

              {step === 1 && (
                <div className="text-center py-6 space-y-8 animate-in fade-in zoom-in-95 duration-500">
                  <div 
                    onClick={() => fileInputRef.current?.click()}
                    className="w-24 h-24 mx-auto bg-surface-container-highest/20 rounded-[2rem] flex items-center justify-center border border-white/5 shadow-2xl cursor-pointer hover:bg-surface-container-highest/30 active:scale-95 transition-all group"
                  >
                    <Upload size={36} className="text-knot-400 group-hover:scale-110 transition-transform" />
                  </div>
                  <div className="space-y-3">
                    <h4 className="text-xl font-black text-white/90 font-headline uppercase tracking-tight">{t('importSelectArchive')}</h4>
                    <div className="text-[13px] text-zinc-500 leading-relaxed font-medium mx-auto">
                      {t('importSelectArchiveDesc')}<br/>
                      <span className="opacity-60 text-[11px] font-black uppercase tracking-widest mt-2 block">{t('importLimit')}</span>
                    </div>
                  </div>
                  
                  <input
                    type="file"
                    ref={fileInputRef}
                    onChange={handleFileChange}
                    accept=".zip"
                    className="hidden"
                  />
                  
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    disabled={loading}
                    className="knot-button-primary w-full h-14 rounded-2xl flex items-center justify-center gap-3 disabled:opacity-50 disabled:scale-100 transition-all font-black uppercase text-[12px] tracking-widest"
                  >
                    {loading ? (
                      <Loader2 size={20} className="animate-spin" />
                    ) : (
                      <>
                        <Upload size={18} />
                        {t('importSelectFile')}
                      </>
                    )}
                  </button>
                </div>
               )}

              {step === 2 && (
                <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
                  <div className="space-y-2">
                    <h4 className="text-xl font-black text-white/90 font-headline uppercase tracking-tight">{t('importParticipants')}</h4>
                    <p className="text-[13px] text-zinc-500 font-medium">
                      {t('importParticipantsDesc')}
                    </p>
                  </div>

                  <div className="space-y-3">
                    {names.map((name) => (
                      <div key={name} className="flex flex-col gap-2 p-5 rounded-3xl border border-white/5 bg-surface-container-highest/10 hover:bg-surface-container-highest/20 transition-all">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-[10px] font-black uppercase tracking-widest text-zinc-500">{t('importInArchive')}</span>
                          <span className="text-sm font-black text-white/90">{name}</span>
                        </div>
                        <select
                          value={mapping[name] || ''}
                          onChange={(e) => setMapping({ ...mapping, [name]: e.target.value })}
                          className="w-full h-12 px-4 bg-black/40 text-sm text-white/90 rounded-2xl border border-white/5 focus:border-knot-400 outline-none transition-all font-medium appearance-none select-glass"
                        >
                          <option value="">{t('importSelectContact')}</option>
                          <option value={user?.id}>{user?.displayName || user?.username} ({t('you')})</option>
                           {friends.map(f => (
                            <option key={f.id} value={f.id}>
                              {f.displayName || f.username}
                            </option>
                          ))}
                        </select>
                      </div>
                    ))}
                  </div>

                   {names.length > 2 && (
                    <div className="space-y-3 pt-2">
                      <div className="flex items-center gap-2 mb-1 px-1">
                         <span className="text-[10px] font-black uppercase tracking-widest text-zinc-500">{t('importGroupName')}</span>
                      </div>
                      <input
                        type="text"
                        placeholder={t('importGroupNameHint')}
                        value={groupName}
                         onChange={(e) => setGroupName(e.target.value)}
                        className="w-full h-14 px-5 bg-black/40 text-sm text-white/90 rounded-2xl border border-white/5 focus:border-knot-400 outline-none transition-all placeholder:text-zinc-600 font-medium"
                      />
                    </div>
                  )}

                  <div className="flex flex-col gap-3">
                    <button
                      onClick={handleExecute}
                      disabled={loading || names.some(n => !mapping[n]) || (names.length > 2 && !groupName.trim())}
                      className="knot-button-primary w-full h-14 rounded-2xl flex items-center justify-center gap-3 disabled:opacity-30 disabled:scale-100 transition-all font-black uppercase text-[12px] tracking-widest"
                    >
                      {loading ? <Loader2 size={20} className="animate-spin" /> : <Check size={20} />}
                      {t('importStart')}
                    </button>
                    <button
                      onClick={reset}
                      disabled={loading}
                      className="w-full h-14 flex items-center justify-center text-[10px] font-black uppercase tracking-widest text-zinc-500 hover:text-white transition-all"
                    >
                      {t('importRestart')}
                    </button>
                  </div>
                </div>
              )}

              {step === 3 && importedState && (
                <div className="text-center py-12 space-y-10 animate-in fade-in zoom-in-95 duration-500">
                  <div className="w-24 h-24 mx-auto bg-green-500/10 text-green-400 rounded-[2rem] flex items-center justify-center border border-green-500/20 shadow-[0_0_40px_rgba(34,197,94,0.1)]">
                    <Check size={48} />
                   </div>
                  <div className="space-y-4">
                    <h4 className="text-2xl font-black text-white/90 font-headline uppercase tracking-tight">{t('importSuccess')}</h4>
                    <div className="text-sm text-zinc-500 font-medium leading-relaxed">
                      {t('importCompletedDesc')}<br/>
                      <span className="text-knot-400 font-black mt-2 block">{t('importStarted')}</span>
                    </div>
                  </div>
                  <button
                    onClick={handleClose}
                    className="knot-button-primary w-full h-14 rounded-2xl font-black uppercase text-[12px] tracking-widest transition-all"
                  >
                    {t('backToChats')}
                  </button>
                </div>
              )}
            </div>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
}
