import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { AppShell } from '../components/layout/AppShell'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { Modal } from '../components/ui/Modal'
import { Badge } from '../components/ui/Badge'
import { useI18n } from '../i18n/useI18n'
import { api } from '../api/client'

interface Project {
  id: string
  name: string
  description: string
  status: string
  member_count: number
  my_role: string
  created_at: string
}

function formatDate(iso: string): string {
  const d = new Date(iso)
  return d.toLocaleDateString('ko-KR', { year: 'numeric', month: 'short', day: 'numeric' })
}

export function Dashboard() {
  const { t } = useI18n()
  const navigate = useNavigate()

  const [projects, setProjects] = useState<Project[]>([])
  const [loading, setLoading] = useState(true)
  const [modalOpen, setModalOpen] = useState(false)
  const [creating, setCreating] = useState(false)
  const [newName, setNewName] = useState('')
  const [newDesc, setNewDesc] = useState('')
  const [createError, setCreateError] = useState<string | null>(null)

  const fetchProjects = async () => {
    setLoading(true)
    try {
      const resp = await api<{items: Project[]}>('/api/v1/projects/')
      setProjects(resp.items)
    } catch {
      setProjects([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { fetchProjects() }, [])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    setCreateError(null)
    setCreating(true)
    try {
      await api('/api/v1/projects/', {
        method: 'POST',
        body: JSON.stringify({ name: newName, description: newDesc }),
      })
      setModalOpen(false)
      setNewName('')
      setNewDesc('')
      await fetchProjects()
    } catch (err: any) {
      setCreateError(err?.message ?? '오류가 발생했습니다')
    } finally {
      setCreating(false)
    }
  }

  const statusLabel = (status: string) => {
    const map: Record<string, string> = {
      active: t('project.status.active'),
      archived: t('project.status.archived'),
      deleted: t('project.status.deleted'),
    }
    return map[status] ?? status
  }

  const roleLabel = (role: string) => {
    const map: Record<string, string> = {
      owner: t('project.role.owner'),
      member: t('project.role.member'),
      admin: t('project.role.admin'),
    }
    return map[role] ?? role
  }

  return (
    <AppShell title={t('dashboard.title')}>
      <div className="page">
        {/* Header row */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ fontFamily: 'var(--font-serif)', fontSize: '20px', fontWeight: 600 }}>
            {t('dashboard.title')}
          </h2>
          <Button variant="primary" onClick={() => setModalOpen(true)}>
            + {t('project.create')}
          </Button>
        </div>

        {/* Content */}
        {loading ? (
          <div className="empty-state">{t('common.loading')}</div>
        ) : projects.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 20px' }}>
            <div style={{ color: 'var(--text-muted)', marginBottom: '16px', fontSize: '15px' }}>
              {t('dashboard.no_projects')}
            </div>
            <Button variant="secondary" onClick={() => setModalOpen(true)}>
              {t('dashboard.create_first')}
            </Button>
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
            gap: '16px',
          }}>
            {projects.map((project) => (
              <div
                key={project.id}
                onClick={() => navigate(`/projects/${project.id}`)}
                style={{
                  background: 'var(--bg-card)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--radius-lg)',
                  padding: '20px',
                  cursor: 'pointer',
                  transition: 'border-color 0.15s, transform 0.1s',
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLDivElement).style.borderColor = 'rgba(99,134,255,0.4)'
                  ;(e.currentTarget as HTMLDivElement).style.transform = 'translateY(-1px)'
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLDivElement).style.borderColor = 'var(--border)'
                  ;(e.currentTarget as HTMLDivElement).style.transform = 'translateY(0)'
                }}
              >
                {/* Top row: name + status badge */}
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '8px', marginBottom: '8px' }}>
                  <h3 style={{ fontSize: '15px', fontWeight: 600, fontFamily: 'var(--font-serif)' }}>
                    {project.name}
                  </h3>
                  <Badge label={statusLabel(project.status)} status={project.status} />
                </div>

                {/* Description */}
                {project.description && (
                  <p style={{
                    fontSize: '13px',
                    color: 'var(--text-muted)',
                    marginBottom: '16px',
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                  }}>
                    {project.description}
                  </p>
                )}

                {/* Footer row */}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: '12px' }}>
                  <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    <span style={{ fontSize: '12px', color: 'var(--text-dim)' }}>
                      {project.member_count} {t('dashboard.member_count')}
                    </span>
                    <Badge label={roleLabel(project.my_role)} status={project.my_role} />
                  </div>
                  <span style={{ fontSize: '11px', color: 'var(--text-dim)' }}>
                    {formatDate(project.created_at)}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Create project modal */}
      <Modal
        open={modalOpen}
        title={t('project.create_modal_title')}
        onClose={() => { setModalOpen(false); setCreateError(null) }}
      >
        <form onSubmit={handleCreate} className="form-stack">
          <Input
            id="new-project-name"
            label={t('project.name')}
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            required
            autoFocus
          />
          <div className="field">
            <label htmlFor="new-project-desc" style={{ fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
              {t('project.description')}
            </label>
            <textarea
              id="new-project-desc"
              value={newDesc}
              onChange={(e) => setNewDesc(e.target.value)}
              rows={3}
            />
          </div>

          {createError && (
            <div style={{ color: 'var(--red)', fontSize: '13px' }}>{createError}</div>
          )}

          <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '8px' }}>
            <Button type="button" variant="ghost" onClick={() => { setModalOpen(false); setCreateError(null) }}>
              {t('btn.cancel')}
            </Button>
            <Button type="submit" variant="primary" disabled={creating}>
              {creating ? t('common.loading') : t('btn.create')}
            </Button>
          </div>
        </form>
      </Modal>
    </AppShell>
  )
}
