import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import api from '../services/api'
import { CustomFieldList } from '../components/CustomFieldList'
import { useToast } from '../contexts/ToastContext'
import { Skeleton } from '../components/Skeleton'

interface Project {
  id: string
  title: string
  description: string | null
  space_id: string
  owner_id: string
  security_level: string
}

export default function ProjectSettings() {
  const { projectId } = useParams()
  const navigate = useNavigate()
  const { showToast } = useToast()
  const [project, setProject] = useState<Project | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<'general' | 'custom-fields'>('custom-fields')

  useEffect(() => {
    loadProject()
  }, [projectId])

  const loadProject = async () => {
    try {
      const response = await api.get(`/projects/${projectId}`)
      setProject(response.data)
    } catch (err) {
      console.error('Failed to load project:', err)
      showToast('Failed to load project settings', 'error')
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div style={styles.container}>
        <div style={styles.header}>
          <Skeleton variant="text" width={200} height={32} />
          <Skeleton variant="rect" width={120} height={40} />
        </div>
        <div style={styles.layout}>
          <div style={styles.sidebar}>
            <Skeleton variant="rect" width="100%" height={44} style={{ marginBottom: '8px' }} />
            <Skeleton variant="rect" width="100%" height={44} />
          </div>
          <div style={styles.content}>
            <Skeleton variant="rect" width="100%" height={300} />
          </div>
        </div>
      </div>
    )
  }

  if (!project) {
    return <div style={styles.error}>Project not found</div>
  }

  return (
    <div style={styles.container}>
      <div style={styles.breadcrumb}>
        <span onClick={() => navigate('/spaces')} style={styles.breadcrumbLink}>
          Spaces
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span
          onClick={() => navigate(`/spaces/${project.space_id}`)}
          style={styles.breadcrumbLink}
        >
          Projects
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span
          onClick={() => navigate(`/projects/${project.id}`)}
          style={styles.breadcrumbLink}
        >
          {project.title}
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span>Settings</span>
      </div>

      <div style={styles.header}>
        <h1 style={styles.title}>Project Settings</h1>
        <button
          onClick={() => navigate(`/projects/${project.id}`)}
          style={styles.backButton}
        >
          Back to Tasks
        </button>
      </div>

      <div style={styles.layout}>
        {/* Sidebar Navigation */}
        <div style={styles.sidebar}>
          <nav style={styles.nav}>
            <button
              onClick={() => setActiveTab('general')}
              style={{
                ...styles.navItem,
                ...(activeTab === 'general' ? styles.navItemActive : {}),
              }}
            >
              General
            </button>
            <button
              onClick={() => setActiveTab('custom-fields')}
              style={{
                ...styles.navItem,
                ...(activeTab === 'custom-fields' ? styles.navItemActive : {}),
              }}
            >
              Custom Fields
            </button>
          </nav>
        </div>

        {/* Content Area */}
        <div style={styles.content}>
          {activeTab === 'general' && (
            <div style={styles.section}>
              <h2 style={styles.sectionTitle}>General Settings</h2>
              <div style={styles.infoCard}>
                <div style={styles.infoRow}>
                  <span style={styles.infoLabel}>Project Name</span>
                  <span style={styles.infoValue}>{project.title}</span>
                </div>
                <div style={styles.infoRow}>
                  <span style={styles.infoLabel}>Description</span>
                  <span style={styles.infoValue}>
                    {project.description || 'No description'}
                  </span>
                </div>
                <div style={styles.infoRow}>
                  <span style={styles.infoLabel}>Security Level</span>
                  <span style={styles.infoValue}>{project.security_level}</span>
                </div>
              </div>
              <p style={styles.helpText}>
                To edit project details, contact the project owner.
              </p>
            </div>
          )}

          {activeTab === 'custom-fields' && (
            <CustomFieldList projectId={projectId!} />
          )}
        </div>
      </div>
    </div>
  )
}

const styles: Record<string, React.CSSProperties> = {
  container: {
    padding: '24px',
    maxWidth: '1200px',
    margin: '0 auto',
  },
  breadcrumb: {
    marginBottom: '16px',
    fontSize: '14px',
    color: '#666',
  },
  breadcrumbLink: {
    color: '#0066cc',
    cursor: 'pointer',
  },
  breadcrumbSeparator: {
    margin: '0 8px',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '24px',
  },
  title: {
    fontSize: '24px',
    fontWeight: 600,
    margin: 0,
  },
  backButton: {
    padding: '10px 20px',
    backgroundColor: '#f5f5f5',
    border: '1px solid #ddd',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  layout: {
    display: 'flex',
    gap: '24px',
  },
  sidebar: {
    width: '200px',
    flexShrink: 0,
  },
  nav: {
    display: 'flex',
    flexDirection: 'column',
    gap: '4px',
  },
  navItem: {
    padding: '12px 16px',
    backgroundColor: 'transparent',
    border: 'none',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    textAlign: 'left',
    color: '#333',
    transition: 'background-color 0.2s',
  },
  navItemActive: {
    backgroundColor: '#e3f2fd',
    color: '#0066cc',
    fontWeight: 500,
  },
  content: {
    flex: 1,
    minWidth: 0,
  },
  section: {
    backgroundColor: 'white',
    borderRadius: '8px',
    padding: '24px',
    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
  },
  sectionTitle: {
    fontSize: '18px',
    fontWeight: 600,
    margin: '0 0 20px 0',
  },
  infoCard: {
    backgroundColor: '#fafafa',
    borderRadius: '8px',
    padding: '16px',
    marginBottom: '16px',
  },
  infoRow: {
    display: 'flex',
    padding: '12px 0',
    borderBottom: '1px solid #eee',
  },
  infoLabel: {
    width: '150px',
    fontSize: '14px',
    fontWeight: 500,
    color: '#666',
  },
  infoValue: {
    flex: 1,
    fontSize: '14px',
    color: '#333',
  },
  helpText: {
    fontSize: '13px',
    color: '#888',
    fontStyle: 'italic',
  },
  loading: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '200px',
    color: '#666',
  },
  error: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '200px',
    color: '#f44336',
  },
}
