import { useState, useEffect, useRef, useContext } from 'react'
import { Trash2, Upload, FileEdit, MessageSquare } from 'lucide-react'
import { useLanguage } from '../i18n/LanguageContext'
import { api, getBrandColor } from '../utils/api'
import CommentsSection from './CommentsSection'
import Modal from './Modal'
import TabbedModal from './TabbedModal'
import { AppContext } from '../App'

export default function ProjectEditPanel({ project, onClose, onSave, onDelete, brands, teamMembers }) {
  const { teams } = useContext(AppContext)
  const { t, lang } = useLanguage()
  const thumbnailInputRef = useRef(null)
  const [form, setForm] = useState({})
  const [dirty, setDirty] = useState(false)
  const [saving, setSaving] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [thumbnailUploading, setThumbnailUploading] = useState(false)
  const [activeTab, setActiveTab] = useState('details')

  const projectId = project?._id || project?.id
  if (!project) return null

  useEffect(() => {
    if (project) {
      setForm({
        name: project.name || '',
        description: project.description || '',
        brand_id: project.brandId || project.brand_id || '',
        owner_id: project.ownerId || project.owner_id || '',
        team_id: project.team_id || '',
        status: project.status || 'active',
        start_date: project.startDate || project.start_date ? new Date(project.startDate || project.start_date).toISOString().slice(0, 10) : '',
        due_date: project.dueDate ? new Date(project.dueDate).toISOString().slice(0, 10) : '',
      })
      setDirty(false)
    }
  }, [project])

  const statusOptions = [
    { value: 'active', label: 'Active' },
    { value: 'paused', label: 'Paused' },
    { value: 'completed', label: 'Completed' },
    { value: 'cancelled', label: 'Cancelled' },
  ]

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

  const handleSave = async () => {
    setSaving(true)
    try {
      await onSave(projectId, {
        name: form.name,
        description: form.description,
        brand_id: form.brand_id ? Number(form.brand_id) : null,
        owner_id: form.owner_id ? Number(form.owner_id) : null,
        team_id: form.team_id ? Number(form.team_id) : null,
        status: form.status,
        start_date: form.start_date || null,
        due_date: form.due_date || null,
      })
      setDirty(false)
    } finally {
      setSaving(false)
    }
  }

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

  const handleThumbnailUpload = async (file) => {
    if (!file) return
    setThumbnailUploading(true)
    try {
      const fd = new FormData()
      fd.append('file', file)
      await api.upload(`/projects/${projectId}/thumbnail`, fd)
      // Parent will reload
      onSave(projectId, form)
    } catch (err) {
      console.error('Thumbnail upload failed:', err)
    } finally {
      setThumbnailUploading(false)
    }
  }

  const handleThumbnailRemove = async () => {
    try {
      await api.delete(`/projects/${projectId}/thumbnail`)
      onSave(projectId, form)
    } catch (err) {
      console.error('Thumbnail remove failed:', err)
    }
  }

  const brandName = (() => {
    if (form.brand_id) {
      const b = brands?.find(b => String(b._id || b.id) === String(form.brand_id))
      return b ? (lang === 'ar' && b.name_ar ? b.name_ar : b.name) : null
    }
    return project.brand_name || project.brandName || null
  })()

  const tabs = [
    { key: 'details', label: t('projects.details'), icon: FileEdit },
    { key: 'discussion', label: t('projects.discussion'), icon: MessageSquare },
  ]

  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('projects.name')}
          />
          <div className="flex items-center gap-2 mt-2">
            <span className={`text-[11px] px-2 py-0.5 rounded-full font-medium ${
              form.status === 'active' ? 'bg-emerald-100 text-emerald-700' :
              form.status === 'paused' ? 'bg-amber-100 text-amber-700' :
              form.status === 'completed' ? 'bg-blue-100 text-blue-700' :
              form.status === 'cancelled' ? 'bg-red-100 text-red-700' :
              'bg-gray-100 text-gray-600'
            }`}>
              {statusOptions.find(s => s.value === form.status)?.label}
            </span>
            {brandName && (
              <span className={`text-[10px] px-1.5 py-0.5 rounded ${getBrandColor(brandName).bg} ${getBrandColor(brandName).text}`}>
                {brandName}
              </span>
            )}
          </div>
        </>}
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        footer={<>
          <div className="flex items-center gap-2">
            {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('common.delete')}
              >
                <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' : ''}`}
              >
                {t('tasks.saveChanges')}
              </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('projects.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"
                placeholder="Project description..."
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('projects.brand')}</label>
                <select
                  value={form.brand_id}
                  onChange={e => update('brand_id', 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"
                >
                  <option value="">Select brand</option>
                  {(brands || []).map(b => <option key={b._id || b.id} value={b._id || b.id}>{b.icon} {lang === 'ar' && b.name_ar ? b.name_ar : b.name}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('projects.status')}</label>
                <select
                  value={form.status}
                  onChange={e => update('status', 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"
                >
                  {statusOptions.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
                </select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('projects.owner')}</label>
                <select
                  value={form.owner_id}
                  onChange={e => update('owner_id', 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"
                >
                  <option value="">{t('common.unassigned')}</option>
                  {(teamMembers || []).map(m => <option key={m._id || m.id} value={m._id || m.id}>{m.name}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-text-tertiary mb-1">{t('common.team')}</label>
                <select
                  value={form.team_id}
                  onChange={e => update('team_id', 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"
                >
                  <option value="">{t('common.noTeam')}</option>
                  {(teams || []).map(t => <option key={t.id || t._id} value={t.id || t._id}>{t.name}</option>)}
                </select>
              </div>
            </div>

            <div>
              <label className="block text-xs font-medium text-text-tertiary mb-1">{t('projects.startDate')}</label>
              <input
                type="date"
                value={form.start_date}
                onChange={e => update('start_date', 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"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-text-tertiary mb-1">{t('projects.dueDate')}</label>
              <input
                type="date"
                value={form.due_date}
                onChange={e => update('due_date', 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"
              />
            </div>

            {/* Thumbnail */}
            <div>
              <label className="block text-xs font-medium text-text-tertiary mb-1">{t('projects.thumbnail')}</label>
              {(project.thumbnail_url || project.thumbnailUrl) ? (
                <div className="relative group rounded-lg overflow-hidden border border-border">
                  <img src={project.thumbnail_url || project.thumbnailUrl} alt="" className="w-full h-24 object-cover" />
                  <div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center gap-2 opacity-0 group-hover:opacity-100">
                    <button
                      onClick={() => thumbnailInputRef.current?.click()}
                      className="px-3 py-1.5 text-xs bg-white/90 hover:bg-white rounded-lg font-medium text-text-primary transition-colors"
                    >
                      {t('projects.changeThumbnail')}
                    </button>
                    <button
                      onClick={handleThumbnailRemove}
                      className="px-3 py-1.5 text-xs bg-red-500/90 hover:bg-red-500 rounded-lg font-medium text-white transition-colors"
                    >
                      {t('projects.removeThumbnail')}
                    </button>
                  </div>
                </div>
              ) : (
                <button
                  onClick={() => thumbnailInputRef.current?.click()}
                  disabled={thumbnailUploading}
                  className="w-full border-2 border-dashed border-border rounded-lg p-3 text-center hover:border-brand-primary/40 transition-colors"
                >
                  <Upload className={`w-5 h-5 text-text-tertiary mx-auto mb-1 ${thumbnailUploading ? 'animate-pulse' : ''}`} />
                  <p className="text-xs text-text-secondary">
                    {thumbnailUploading ? 'Uploading...' : t('projects.uploadThumbnail')}
                  </p>
                </button>
              )}
              <input
                ref={thumbnailInputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={e => { handleThumbnailUpload(e.target.files[0]); e.target.value = '' }}
              />
            </div>
          </div>
        )}

        {activeTab === 'discussion' && (
          <div className="p-6 space-y-3">
            <CommentsSection entityType="project" entityId={projectId} />
          </div>
        )}
      </TabbedModal>

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