import { useState, useEffect } from 'react'
import { Trash2, Search, FileEdit, Users } from 'lucide-react'
import { useLanguage } from '../i18n/LanguageContext'
import { getInitials } from '../utils/api'
import Modal from './Modal'
import TabbedModal from './TabbedModal'

export default function TeamPanel({ team, onClose, onSave, onDelete, teamMembers }) {
  const { t } = useLanguage()
  const [form, setForm] = useState({ name: '', description: '', member_ids: [] })
  const [dirty, setDirty] = useState(false)
  const [saving, setSaving] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [memberSearch, setMemberSearch] = useState('')
  const [activeTab, setActiveTab] = useState('details')

  const teamId = team?.id || team?._id
  const isCreateMode = !teamId

  useEffect(() => {
    if (team) {
      setForm({
        name: team.name || '',
        description: team.description || '',
        member_ids: team.member_ids || [],
      })
      setDirty(isCreateMode)
    }
  }, [team])

  if (!team) return null

  const update = (field, value) => {
    setForm(f => ({ ...f, [field]: value }))
    setDirty(true)
  }

  const toggleMember = (userId) => {
    const ids = form.member_ids || []
    update('member_ids', ids.includes(userId)
      ? ids.filter(id => id !== userId)
      : [...ids, userId]
    )
  }

  const handleSave = async () => {
    setSaving(true)
    try {
      await onSave(isCreateMode ? null : teamId, {
        name: form.name,
        description: form.description,
        member_ids: form.member_ids,
      })
      setDirty(false)
      if (isCreateMode) onClose()
    } finally {
      setSaving(false)
    }
  }

  const confirmDelete = async () => {
    setShowDeleteConfirm(false)
    await onDelete(teamId)
    onClose()
  }

  const filteredMembers = (teamMembers || []).filter(m =>
    !memberSearch || m.name?.toLowerCase().includes(memberSearch.toLowerCase())
  )

  const memberCount = (form.member_ids || []).length

  return (
    <>
      <TabbedModal
        onClose={onClose}
        size="md"
        header={
          <>
            <input
              type="text"
              value={form.name}
              onChange={e => update('name', e.target.value)}
              className="w-full text-lg font-semibold text-text-primary bg-transparent border-0 p-0 focus:outline-none focus:ring-0"
              placeholder={t('teams.name')}
            />
            <span className="text-[11px] px-2 py-0.5 rounded-full font-medium bg-blue-100 text-blue-700">
              {memberCount} {t('teams.members')}
            </span>
          </>
        }
        tabs={[
          { key: 'details', label: t('teams.details'), icon: FileEdit },
          { key: 'members', label: t('teams.members'), icon: Users, badge: memberCount },
        ]}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        footer={
          <>
            <div className="flex items-center gap-2">
              {!isCreateMode && onDelete && (
                <button
                  onClick={() => setShowDeleteConfirm(true)}
                  className="p-2 text-text-tertiary hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                  title={t('teams.deleteTeam')}
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              )}
            </div>
            <div className="flex items-center gap-2.5">
              {dirty && (
                <button
                  onClick={handleSave}
                  disabled={!form.name || saving}
                  className={`px-4 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 disabled:cursor-not-allowed shadow-sm ${saving ? 'btn-loading' : ''}`}
                >
                  {isCreateMode ? t('teams.createTeam') : t('common.save')}
                </button>
              )}
            </div>
          </>
        }
      >
        {activeTab === 'details' && (
          <div className="p-6 space-y-3">
            <div>
              <label className="block text-xs font-medium text-text-tertiary mb-1">{t('teams.name')}</label>
              <input
                type="text"
                value={form.name}
                onChange={e => update('name', e.target.value)}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                placeholder={t('teams.name')}
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-text-tertiary mb-1">{t('teams.description')}</label>
              <textarea
                value={form.description}
                onChange={e => update('description', e.target.value)}
                rows={3}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary resize-none"
              />
            </div>
          </div>
        )}

        {activeTab === 'members' && (
          <div className="p-6">
            <div className="relative mb-3">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-text-tertiary" />
              <input
                type="text"
                value={memberSearch}
                onChange={e => setMemberSearch(e.target.value)}
                placeholder={t('teams.selectMembers')}
                className="w-full pl-9 pr-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              />
            </div>
            <div className="space-y-1 max-h-80 overflow-y-auto">
              {filteredMembers.map(m => {
                const uid = m.id || m._id
                const checked = (form.member_ids || []).includes(uid)
                return (
                  <label
                    key={uid}
                    className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer hover:bg-surface-secondary ${checked ? 'bg-blue-50' : ''}`}
                  >
                    <input
                      type="checkbox"
                      checked={checked}
                      onChange={() => toggleMember(uid)}
                      className="rounded border-border text-brand-primary focus:ring-brand-primary"
                    />
                    <div className="w-7 h-7 rounded-full bg-gradient-to-br from-indigo-400 to-purple-500 flex items-center justify-center text-white text-[10px] font-bold shrink-0">
                      {getInitials(m.name)}
                    </div>
                    <span className="text-sm font-medium text-text-primary">{m.name}</span>
                  </label>
                )
              })}
              {filteredMembers.length === 0 && (
                <p className="text-xs text-text-tertiary text-center py-4">{t('common.noResults')}</p>
              )}
            </div>
          </div>
        )}
      </TabbedModal>

      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        title={t('teams.deleteTeam')}
        isConfirm
        danger
        confirmText={t('teams.deleteTeam')}
        onConfirm={confirmDelete}
      >
        {t('teams.deleteConfirm')}
      </Modal>
    </>
  )
}
