/* ====================================================
 * Admin - Quản lý Liên hệ
 * Xem tin nhắn từ khách hàng + Chỉnh sửa thông tin liên hệ
 * ==================================================== */

'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  HiOutlineMail, HiOutlinePhone, HiOutlineLocationMarker, HiOutlineClock,
  HiOutlineCheck, HiOutlineX, HiOutlineRefresh, HiOutlinePencil, HiOutlineSave,
  HiOutlineInboxIn, HiOutlineLogout, HiOutlineLogin, HiOutlineEye, HiOutlineEyeOff,
  HiOutlineChevronDown, HiOutlineChevronUp, HiOutlineBadgeCheck, HiOutlineExclamationCircle,
} from 'react-icons/hi';
import { Contact, SiteSetting } from '@/types/api';

// ---- Types ----
interface LoginForm { username: string; password: string; }

// ---- Helper ----
const API = (path: string) => `/api-proxy${path}`;

async function apiFetch<T>(path: string, options?: RequestInit, token?: string): Promise<T> {
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
  const res = await fetch(API(path), { ...options, headers: { ...headers, ...options?.headers } });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err?.detail || `HTTP ${res.status}`);
  }
  if (res.status === 204) return {} as T;
  return res.json();
}

// ---- Sub-components ----

function LoginPanel({ onLogin }: { onLogin: (token: string) => void }) {
  const [form, setForm] = useState<LoginForm>({ username: '', password: '' });
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const data = await apiFetch<{ access: string; refresh: string }>('/auth/login/', {
        method: 'POST',
        body: JSON.stringify({ username: form.username, password: form.password }),
      });
      localStorage.setItem('access_token', data.access);
      localStorage.setItem('refresh_token', data.refresh);
      onLogin(data.access);
    } catch (err: any) {
      setError('Thông tin đăng nhập không đúng. Vui lòng thử lại.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-900 via-primary-800 to-secondary-700 flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0, y: 24 }}
        animate={{ opacity: 1, y: 0 }}
        className="w-full max-w-md bg-white/10 backdrop-blur-xl rounded-3xl p-8 shadow-2xl border border-white/20"
      >
        <div className="text-center mb-8">
          <div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <HiOutlineLogin className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-2xl font-bold text-white">Đăng nhập Admin</h1>
          <p className="text-white/60 text-sm mt-1">Quản lý liên hệ khách hàng</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-white/80 mb-1.5">Tài khoản</label>
            <input
              id="admin-username"
              type="text"
              value={form.username}
              onChange={e => setForm(p => ({ ...p, username: e.target.value }))}
              placeholder="Username"
              required
              className="w-full px-4 py-3 rounded-xl bg-white/10 border border-white/20 text-white placeholder-white/40 focus:outline-none focus:border-white/50 focus:ring-2 focus:ring-white/20 transition-all"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-white/80 mb-1.5">Mật khẩu</label>
            <div className="relative">
              <input
                id="admin-password"
                type={showPw ? 'text' : 'password'}
                value={form.password}
                onChange={e => setForm(p => ({ ...p, password: e.target.value }))}
                placeholder="••••••••"
                required
                className="w-full px-4 py-3 pr-12 rounded-xl bg-white/10 border border-white/20 text-white placeholder-white/40 focus:outline-none focus:border-white/50 focus:ring-2 focus:ring-white/20 transition-all"
              />
              <button type="button" onClick={() => setShowPw(!showPw)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-white/50 hover:text-white">
                {showPw ? <HiOutlineEyeOff className="w-5 h-5" /> : <HiOutlineEye className="w-5 h-5" />}
              </button>
            </div>
          </div>

          {error && (
            <div className="flex items-center gap-2 text-red-300 text-sm bg-red-500/10 border border-red-400/20 rounded-lg px-3 py-2">
              <HiOutlineExclamationCircle className="w-4 h-4 shrink-0" />
              {error}
            </div>
          )}

          <button
            id="admin-login-btn"
            type="submit"
            disabled={loading}
            className="w-full py-3.5 bg-white text-primary-700 font-bold rounded-xl hover:bg-white/90 disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-300 hover:shadow-lg"
          >
            {loading ? 'Đang đăng nhập...' : 'Đăng nhập'}
          </button>
        </form>
      </motion.div>
    </div>
  );
}

// Inbox item card
function ContactCard({ contact, onToggle }: { contact: Contact; onToggle: (id: number, val: boolean) => void }) {
  const [expanded, setExpanded] = useState(false);
  const [loading, setLoading] = useState(false);

  const subjectColors: Record<string, string> = {
    product: 'bg-blue-100 text-blue-700',
    partnership: 'bg-green-100 text-green-700',
    recruitment: 'bg-yellow-100 text-yellow-700',
    other: 'bg-gray-100 text-gray-600',
  };

  const handleToggle = async () => {
    setLoading(true);
    await onToggle(contact.id, !contact.is_resolved);
    setLoading(false);
  };

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      className={`rounded-2xl border transition-all ${contact.is_resolved
        ? 'bg-gray-50 border-gray-200'
        : 'bg-white border-primary-100 shadow-sm'
      }`}
    >
      <div className="p-5">
        <div className="flex items-start justify-between gap-3">
          <div className="flex-1 min-w-0">
            <div className="flex flex-wrap items-center gap-2 mb-1">
              <span className="font-semibold text-dark-800">{contact.full_name}</span>
              <span className={`text-xs font-medium px-2.5 py-0.5 rounded-full ${subjectColors[contact.subject] || subjectColors.other}`}>
                {contact.subject_display}
              </span>
              {contact.is_resolved && (
                <span className="text-xs font-medium px-2.5 py-0.5 rounded-full bg-green-100 text-green-700 flex items-center gap-1">
                  <HiOutlineBadgeCheck className="w-3.5 h-3.5" /> Đã xử lý
                </span>
              )}
            </div>
            <div className="flex flex-wrap gap-3 text-sm text-dark-400 mb-2">
              <span className="flex items-center gap-1"><HiOutlineMail className="w-4 h-4" /> {contact.email}</span>
              {contact.phone && <span className="flex items-center gap-1"><HiOutlinePhone className="w-4 h-4" /> {contact.phone}</span>}
              <span className="flex items-center gap-1"><HiOutlineClock className="w-4 h-4" />
                {new Date(contact.created_at).toLocaleString('vi-VN')}
              </span>
            </div>
          </div>

          <div className="flex items-center gap-2 shrink-0">
            <button
              id={`resolve-btn-${contact.id}`}
              onClick={handleToggle}
              disabled={loading}
              title={contact.is_resolved ? 'Đánh dấu chưa xử lý' : 'Đánh dấu đã xử lý'}
              className={`w-8 h-8 rounded-lg flex items-center justify-center transition-all ${contact.is_resolved
                ? 'bg-gray-200 text-gray-500 hover:bg-yellow-100 hover:text-yellow-600'
                : 'bg-green-50 text-green-600 hover:bg-green-100'
              }`}
            >
              {loading ? <HiOutlineRefresh className="w-4 h-4 animate-spin" /> : <HiOutlineCheck className="w-4 h-4" />}
            </button>
            <button
              onClick={() => setExpanded(!expanded)}
              className="w-8 h-8 rounded-lg bg-surface-100 text-dark-400 hover:bg-primary-50 hover:text-primary-600 flex items-center justify-center transition-all"
            >
              {expanded ? <HiOutlineChevronUp className="w-4 h-4" /> : <HiOutlineChevronDown className="w-4 h-4" />}
            </button>
          </div>
        </div>

        <AnimatePresence>
          {expanded && (
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: 'auto', opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              className="overflow-hidden"
            >
              <div className="pt-3 border-t border-surface-200 mt-2">
                <p className="text-sm text-dark-500 leading-relaxed whitespace-pre-wrap">{contact.content}</p>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </motion.div>
  );
}

// Contact info editor
function ContactInfoEditor({ token }: { token: string }) {
  const [info, setInfo] = useState<Partial<SiteSetting>>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [settingId, setSettingId] = useState<number | null>(null);

  useEffect(() => {
    apiFetch<SiteSetting>('/core/settings/', {}, token)
      .then(data => {
        setSettingId(data.id);
        setInfo({
          address: data.address,
          phone: data.phone,
          hotline: data.hotline,
          email: data.email,
          working_hours: data.working_hours,
          map_embed_url: data.map_embed_url,
        });
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [token]);

  const handleChange = (field: keyof SiteSetting, value: string) => {
    setInfo(prev => ({ ...prev, [field]: value }));
    setSaveStatus('idle');
  };

  const handleSave = async () => {
    setSaving(true);
    setSaveStatus('idle');
    try {
      await apiFetch('/core/settings/', {
        method: 'PATCH',
        body: JSON.stringify(info),
      }, token);
      setSaveStatus('success');
      setTimeout(() => setSaveStatus('idle'), 3000);
    } catch (err) {
      setSaveStatus('error');
    } finally {
      setSaving(false);
    }
  };

  if (loading) return (
    <div className="flex items-center justify-center py-20 text-dark-400">
      <HiOutlineRefresh className="w-6 h-6 animate-spin mr-2" /> Đang tải...
    </div>
  );

  const fields: { key: keyof SiteSetting; label: string; icon: React.ReactNode; type?: string; hint?: string }[] = [
    { key: 'address', label: 'Địa chỉ', icon: <HiOutlineLocationMarker className="w-5 h-5" />, hint: 'Địa chỉ hiển thị trong hộp thông tin liên hệ' },
    { key: 'phone', label: 'Số điện thoại', icon: <HiOutlinePhone className="w-5 h-5" />, type: 'tel' },
    { key: 'hotline', label: 'Hotline', icon: <HiOutlinePhone className="w-5 h-5" />, type: 'tel', hint: 'Hiển thị ở header và trang liên hệ' },
    { key: 'email', label: 'Email liên hệ', icon: <HiOutlineMail className="w-5 h-5" />, type: 'email' },
    { key: 'working_hours', label: 'Giờ làm việc', icon: <HiOutlineClock className="w-5 h-5" />, hint: 'VD: Thứ 2 - Thứ 6: 8:00 - 17:30 | Thứ 7: 8:00 - 12:00' },
    { key: 'map_embed_url', label: 'URL nhúng bản đồ (Google Maps Embed)', icon: <HiOutlineLocationMarker className="w-5 h-5" />, hint: 'Lấy từ Google Maps > Chia sẻ > Nhúng bản đồ > Copy link src' },
  ];

  return (
    <div>
      <div className="grid grid-cols-1 gap-5">
        {fields.map(({ key, label, icon, type, hint }) => (
          <div key={key}>
            <label className="block text-sm font-semibold text-dark-700 mb-1.5 flex items-center gap-2">
              <span className="text-primary-500">{icon}</span>
              {label}
            </label>
            {key === 'map_embed_url' ? (
              <textarea
                id={`contact-info-${key}`}
                rows={3}
                value={(info[key] as string) || ''}
                onChange={e => handleChange(key, e.target.value)}
                className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 placeholder-dark-300 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all resize-none font-mono text-xs"
                placeholder="https://www.google.com/maps/embed?pb=..."
              />
            ) : (
              <input
                id={`contact-info-${key}`}
                type={type || 'text'}
                value={(info[key] as string) || ''}
                onChange={e => handleChange(key, e.target.value)}
                className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 placeholder-dark-300 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all"
              />
            )}
            {hint && <p className="text-xs text-dark-400 mt-1.5">{hint}</p>}
          </div>
        ))}
      </div>

      <div className="mt-6 flex items-center gap-4">
        <button
          id="save-contact-info-btn"
          onClick={handleSave}
          disabled={saving}
          className="inline-flex items-center gap-2 px-6 py-3 bg-primary-500 hover:bg-primary-600 disabled:opacity-60 disabled:cursor-not-allowed text-white font-semibold rounded-xl transition-all duration-300 hover:shadow-lg hover:shadow-primary-500/25"
        >
          {saving
            ? <><HiOutlineRefresh className="w-5 h-5 animate-spin" /> Đang lưu...</>
            : <><HiOutlineSave className="w-5 h-5" /> Lưu thay đổi</>
          }
        </button>

        <AnimatePresence>
          {saveStatus === 'success' && (
            <motion.span initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0 }}
              className="flex items-center gap-1.5 text-green-600 font-medium text-sm">
              <HiOutlineCheck className="w-5 h-5" /> Đã lưu thành công!
            </motion.span>
          )}
          {saveStatus === 'error' && (
            <motion.span initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0 }}
              className="flex items-center gap-1.5 text-red-500 font-medium text-sm">
              <HiOutlineX className="w-5 h-5" /> Lưu thất bại. Thử lại sau.
            </motion.span>
          )}
        </AnimatePresence>
      </div>

      {/* Preview */}
      {(info.address || info.hotline || info.email) && (
        <div className="mt-8 p-5 rounded-2xl border border-primary-100 bg-primary-50/50">
          <h4 className="text-sm font-bold text-primary-700 mb-3 uppercase tracking-wider">Xem trước - Thông tin liên hệ</h4>
          <div className="space-y-3">
            {info.address && (
              <div className="flex items-start gap-3 text-sm">
                <HiOutlineLocationMarker className="w-4 h-4 text-primary-500 mt-0.5 shrink-0" />
                <span className="text-dark-600">{info.address}</span>
              </div>
            )}
            {info.hotline && (
              <div className="flex items-center gap-3 text-sm">
                <HiOutlinePhone className="w-4 h-4 text-primary-500 shrink-0" />
                <span className="text-dark-600">{info.hotline}</span>
              </div>
            )}
            {info.email && (
              <div className="flex items-center gap-3 text-sm">
                <HiOutlineMail className="w-4 h-4 text-primary-500 shrink-0" />
                <span className="text-dark-600">{info.email}</span>
              </div>
            )}
            {info.working_hours && (
              <div className="flex items-center gap-3 text-sm">
                <HiOutlineClock className="w-4 h-4 text-dark-400 shrink-0" />
                <span className="text-dark-600">{info.working_hours}</span>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// ---- Main Component ----
export default function AdminContactPage() {
  const [token, setToken] = useState<string | null>(null);
  const [tab, setTab] = useState<'inbox' | 'settings'>('inbox');
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [loadingContacts, setLoadingContacts] = useState(false);
  const [filterResolved, setFilterResolved] = useState<'all' | 'unresolved' | 'resolved'>('all');

  // Restore token from localStorage on mount
  useEffect(() => {
    const t = localStorage.getItem('access_token');
    if (t) setToken(t);
  }, []);

  const fetchContacts = useCallback(async (tok: string) => {
    setLoadingContacts(true);
    try {
      const data = await apiFetch<Contact[]>('/contacts/', {}, tok);
      setContacts(data);
    } catch (err: any) {
      if (err.message?.includes('401') || err.message?.includes('403')) {
        handleLogout();
      }
    } finally {
      setLoadingContacts(false);
    }
  }, []);

  useEffect(() => {
    if (token && tab === 'inbox') {
      fetchContacts(token);
    }
  }, [token, tab, fetchContacts]);

  const handleLogin = (tok: string) => setToken(tok);

  const handleLogout = () => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    setToken(null);
    setContacts([]);
  };

  const handleToggleResolved = async (id: number, val: boolean) => {
    if (!token) return;
    try {
      const updated = await apiFetch<Contact>(`/contacts/${id}/resolve/`, {
        method: 'PATCH',
        body: JSON.stringify({ is_resolved: val }),
      }, token);
      setContacts(prev => prev.map(c => c.id === id ? { ...c, is_resolved: updated.is_resolved } : c));
    } catch (err) {
      console.error('Toggle failed:', err);
    }
  };

  if (!token) return <LoginPanel onLogin={handleLogin} />;

  const filteredContacts = contacts.filter(c => {
    if (filterResolved === 'unresolved') return !c.is_resolved;
    if (filterResolved === 'resolved') return c.is_resolved;
    return true;
  });

  const unresolvedCount = contacts.filter(c => !c.is_resolved).length;

  return (
    <div className="min-h-screen bg-surface-50">
      {/* Header */}
      <header className="bg-white border-b border-surface-200 sticky top-0 z-40 shadow-sm">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 flex items-center justify-between h-16">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center">
              <HiOutlineInboxIn className="w-5 h-5 text-white" />
            </div>
            <div>
              <h1 className="font-bold text-dark-800 leading-tight">Quản lý Liên hệ</h1>
              <p className="text-xs text-dark-400">Admin Panel</p>
            </div>
          </div>
          <button
            id="admin-logout-btn"
            onClick={handleLogout}
            className="flex items-center gap-2 px-4 py-2 text-sm text-dark-500 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
          >
            <HiOutlineLogout className="w-4 h-4" />
            <span className="hidden sm:block">Đăng xuất</span>
          </button>
        </div>
      </header>

      <main className="max-w-5xl mx-auto px-4 sm:px-6 py-8">
        {/* Tabs */}
        <div className="flex items-center gap-2 mb-8 bg-white rounded-2xl p-1.5 border border-surface-200 w-fit shadow-sm">
          <button
            id="tab-inbox"
            onClick={() => setTab('inbox')}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200 ${tab === 'inbox'
              ? 'bg-primary-500 text-white shadow-md shadow-primary-500/20'
              : 'text-dark-500 hover:text-primary-600 hover:bg-primary-50'
            }`}
          >
            <HiOutlineInboxIn className="w-4 h-4" />
            Hộp thư đến
            {unresolvedCount > 0 && (
              <span className={`px-2 py-0.5 rounded-full text-xs font-bold ${tab === 'inbox' ? 'bg-white/25 text-white' : 'bg-red-500 text-white'}`}>
                {unresolvedCount}
              </span>
            )}
          </button>
          <button
            id="tab-settings"
            onClick={() => setTab('settings')}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200 ${tab === 'settings'
              ? 'bg-primary-500 text-white shadow-md shadow-primary-500/20'
              : 'text-dark-500 hover:text-primary-600 hover:bg-primary-50'
            }`}
          >
            <HiOutlinePencil className="w-4 h-4" />
            Thông tin liên hệ
          </button>
        </div>

        {/* Tab: Inbox */}
        {tab === 'inbox' && (
          <div>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
              <div>
                <h2 className="text-xl font-bold text-dark-800">Tin nhắn từ khách hàng</h2>
                <p className="text-sm text-dark-400 mt-0.5">
                  Tổng {contacts.length} tin nhắn • {unresolvedCount} chưa xử lý
                </p>
              </div>
              <div className="flex items-center gap-2">
                {/* Filter */}
                {(['all', 'unresolved', 'resolved'] as const).map(f => (
                  <button
                    key={f}
                    id={`filter-${f}`}
                    onClick={() => setFilterResolved(f)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all ${filterResolved === f
                      ? 'bg-primary-500 text-white'
                      : 'bg-white text-dark-500 border border-surface-200 hover:border-primary-300'
                    }`}
                  >
                    {f === 'all' ? 'Tất cả' : f === 'unresolved' ? 'Chưa xử lý' : 'Đã xử lý'}
                  </button>
                ))}
                <button
                  id="refresh-contacts-btn"
                  onClick={() => token && fetchContacts(token)}
                  disabled={loadingContacts}
                  className="w-8 h-8 flex items-center justify-center rounded-lg bg-white border border-surface-200 text-dark-400 hover:text-primary-600 hover:border-primary-300 transition-all"
                >
                  <HiOutlineRefresh className={`w-4 h-4 ${loadingContacts ? 'animate-spin' : ''}`} />
                </button>
              </div>
            </div>

            {loadingContacts ? (
              <div className="flex items-center justify-center py-20 text-dark-400">
                <HiOutlineRefresh className="w-6 h-6 animate-spin mr-2" /> Đang tải...
              </div>
            ) : filteredContacts.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-20 text-dark-400">
                <HiOutlineInboxIn className="w-12 h-12 mb-3 opacity-30" />
                <p className="font-medium">Không có tin nhắn nào</p>
              </div>
            ) : (
              <div className="space-y-3">
                <AnimatePresence>
                  {filteredContacts.map(contact => (
                    <ContactCard
                      key={contact.id}
                      contact={contact}
                      onToggle={handleToggleResolved}
                    />
                  ))}
                </AnimatePresence>
              </div>
            )}
          </div>
        )}

        {/* Tab: Settings */}
        {tab === 'settings' && (
          <div>
            <div className="mb-6">
              <h2 className="text-xl font-bold text-dark-800">Thông tin liên hệ hiển thị</h2>
              <p className="text-sm text-dark-400 mt-0.5">
                Chỉnh sửa thông tin liên hệ hiển thị ở trang Liên hệ và toàn bộ website
              </p>
            </div>
            <div className="bg-white rounded-2xl border border-surface-200 shadow-sm p-6">
              <ContactInfoEditor token={token} />
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
