'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { PenSquare, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { FolderList, FolderInfo } from '@/components/email/folder-list'

export default function EmailLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const [folders, setFolders] = useState<FolderInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  async function loadFolders() {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch('/api/email/folders')
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || 'Failed to load folders')
      }
      const data = await res.json()
      setFolders(data)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load folders')
    } finally {
      setLoading(false)
    }
  }

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

  return (
    <div className="flex h-[calc(100vh-7rem)] lg:h-[calc(100vh-2rem)] -m-6 lg:-m-8">
      {/* Folder sidebar */}
      <div className="hidden md:flex w-56 flex-col border-r bg-background shrink-0">
        <div className="flex items-center justify-between p-3 border-b">
          <Link href="/email/compose">
            <Button size="sm" className="w-full">
              <PenSquare className="mr-2 h-4 w-4" />
              Compose
            </Button>
          </Link>
          <Button
            variant="ghost"
            size="icon"
            className="ml-2 shrink-0"
            onClick={loadFolders}
            title="Refresh folders"
          >
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>
        <FolderList folders={folders} loading={loading} error={error} />
      </div>

      {/* Main content */}
      <div className="flex-1 min-w-0 overflow-auto">
        {children}
      </div>
    </div>
  )
}
