import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { formatBytes } from '@/lib/format'
import {
  Folder,
  Share2,
  Globe,
  Search,
  Plus,
  MoreVertical,
  CheckCircle2,
  HardDrive,
  Database,
  Clock,
  Link as LinkIcon,
  Copy,
  FileText,
  Settings,
  Users,
  Activity,
  Filter
} from 'lucide-react'

// Mock data - will be replaced with API calls
const MOCK_BUCKETS = [
  {
    id: '1',
    name: 'backup-archive-01',
    type: 'immutable',
    usage: 4.2 * 1024 * 1024 * 1024 * 1024, // 4.2 TB in bytes
    usagePercent: 75,
    objects: 14200,
    accessPolicy: 'private',
    created: '2023-10-24',
    color: 'blue',
  },
  {
    id: '2',
    name: 'daily-snapshots',
    type: 'standard',
    usage: 120 * 1024 * 1024 * 1024, // 120 GB
    usagePercent: 15,
    objects: 400,
    accessPolicy: 'private',
    created: '2023-11-01',
    color: 'purple',
  },
  {
    id: '3',
    name: 'public-assets',
    type: 'standard',
    usage: 500 * 1024 * 1024 * 1024, // 500 GB
    usagePercent: 30,
    objects: 12050,
    accessPolicy: 'public-read',
    created: '2023-12-15',
    color: 'orange',
  },
  {
    id: '4',
    name: 'logs-retention',
    type: 'archive',
    usage: 2.1 * 1024 * 1024 * 1024 * 1024, // 2.1 TB
    usagePercent: 55,
    objects: 850221,
    accessPolicy: 'private',
    created: '2024-01-10',
    color: 'blue',
  },
]

const S3_ENDPOINT = 'https://s3.appliance.local:9000'

export default function ObjectStorage() {
  const [activeTab, setActiveTab] = useState<'buckets' | 'users' | 'monitoring' | 'settings'>('buckets')
  const [searchQuery, setSearchQuery] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 10

  // Mock queries - replace with real API calls
  const { data: buckets = MOCK_BUCKETS } = useQuery({
    queryKey: ['object-storage-buckets'],
    queryFn: async () => MOCK_BUCKETS,
  })

  // Filter buckets by search query
  const filteredBuckets = buckets.filter(bucket =>
    bucket.name.toLowerCase().includes(searchQuery.toLowerCase())
  )

  // Pagination
  const totalPages = Math.ceil(filteredBuckets.length / itemsPerPage)
  const paginatedBuckets = filteredBuckets.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  )

  // Calculate totals
  const totalUsage = buckets.reduce((sum, b) => sum + b.usage, 0)
  const totalObjects = buckets.reduce((sum, b) => sum + b.objects, 0)

  // Copy endpoint to clipboard
  const copyEndpoint = () => {
    navigator.clipboard.writeText(S3_ENDPOINT)
    // You could add a toast notification here
  }

  // Get bucket icon
  const getBucketIcon = (bucket: typeof MOCK_BUCKETS[0]) => {
    if (bucket.accessPolicy === 'public-read') {
      return <Globe className="text-orange-500" size={20} />
    }
    if (bucket.type === 'immutable') {
      return <Folder className="text-blue-500" size={20} />
    }
    return <Share2 className="text-purple-500" size={20} />
  }

  // Get bucket color class
  const getBucketColorClass = (color: string) => {
    const colors: Record<string, string> = {
      blue: 'bg-blue-500/10 text-blue-500',
      purple: 'bg-purple-500/10 text-purple-500',
      orange: 'bg-orange-500/10 text-orange-500',
    }
    return colors[color] || colors.blue
  }

  // Get progress bar color
  const getProgressColor = (color: string) => {
    const colors: Record<string, string> = {
      blue: 'bg-primary',
      purple: 'bg-purple-500',
      orange: 'bg-orange-500',
    }
    return colors[color] || colors.blue
  }

  // Get access policy badge
  const getAccessPolicyBadge = (policy: string) => {
    if (policy === 'public-read') {
      return (
        <span className="inline-flex items-center rounded-full bg-orange-500/10 px-2.5 py-0.5 text-xs font-medium text-orange-500 border border-orange-500/20">
          Public Read
        </span>
      )
    }
    return (
      <span className="inline-flex items-center rounded-full bg-green-500/10 px-2.5 py-0.5 text-xs font-medium text-green-500 border border-green-500/20">
        Private
      </span>
    )
  }

  // Format date
  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
  }

  return (
    <div className="flex-1 overflow-hidden flex flex-col bg-background-dark">
      {/* Main Content */}
      <main className="flex-1 flex flex-col overflow-y-auto relative scroll-smooth">
        <div className="flex flex-col max-w-[1200px] w-full mx-auto p-6 md:p-8 lg:p-12 gap-8">
          {/* Page Heading */}
          <div className="flex flex-wrap justify-between items-start gap-4">
            <div className="flex flex-col gap-2">
              <h1 className="text-white tracking-tight text-[32px] font-bold leading-tight">
                Object Storage Service
              </h1>
              <p className="text-text-secondary text-sm font-normal max-w-xl">
                Manage S3-compatible buckets, configure access policies, and monitor real-time object storage performance.
              </p>
            </div>
            <div className="flex gap-3">
              <button className="flex h-10 items-center justify-center rounded-lg border border-border-dark px-4 text-white text-sm font-medium hover:bg-[#233648] transition-colors">
                <FileText className="mr-2" size={20} />
                Documentation
              </button>
              <button className="flex h-10 items-center justify-center rounded-lg bg-[#233648] px-4 text-white text-sm font-medium hover:bg-[#2b4055] transition-colors border border-border-dark">
                <Settings className="mr-2" size={20} />
                Config
              </button>
            </div>
          </div>

          {/* Stats Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Service Status */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Service Status</p>
                <CheckCircle2 className="text-[#0bda5b]" size={20} />
              </div>
              <p className="text-white tracking-tight text-2xl font-bold">Running</p>
              <p className="text-text-secondary text-xs">Port 9000 (TLS Enabled)</p>
            </div>

            {/* Total Usage */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Total Usage</p>
                <HardDrive className="text-primary" size={20} />
              </div>
              <div className="flex items-baseline gap-2">
                <p className="text-white tracking-tight text-2xl font-bold">{formatBytes(totalUsage, 1)}</p>
                <p className="text-[#0bda5b] text-sm font-medium">+2.1%</p>
              </div>
              <div className="w-full bg-[#233648] rounded-full h-1.5 mt-1">
                <div className="bg-primary h-1.5 rounded-full" style={{ width: '45%' }}></div>
              </div>
            </div>

            {/* Object Count */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Object Count</p>
                <Database className="text-blue-400" size={20} />
              </div>
              <div className="flex items-baseline gap-2">
                <p className="text-white tracking-tight text-2xl font-bold">
                  {(totalObjects / 1000000).toFixed(1)}M
                </p>
                <p className="text-[#0bda5b] text-sm font-medium">+0.5%</p>
              </div>
              <p className="text-text-secondary text-xs">Total objects across all buckets</p>
            </div>

            {/* Uptime */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Uptime</p>
                <Clock className="text-orange-400" size={20} />
              </div>
              <p className="text-white tracking-tight text-2xl font-bold">24d 12h</p>
              <p className="text-text-secondary text-xs">Since last patch</p>
            </div>
          </div>

          {/* Endpoint Info */}
          <div className="flex flex-col md:flex-row items-center justify-between gap-6 rounded-lg border border-border-dark bg-[#16202a] p-6 relative overflow-hidden">
            <div className="absolute top-0 right-0 h-full w-1/3 bg-gradient-to-l from-primary/10 to-transparent pointer-events-none"></div>
            <div className="flex flex-col gap-2 z-10 max-w-2xl">
              <div className="flex items-center gap-2">
                <LinkIcon className="text-primary" size={20} />
                <h2 className="text-white text-lg font-bold">S3 Endpoint URL</h2>
              </div>
              <p className="text-text-secondary text-sm">
                Use this URL to configure your S3 clients (MinIO, AWS CLI, Veeam, etc.).
              </p>
            </div>
            <div className="flex w-full md:w-auto min-w-[320px] max-w-[500px] z-10">
              <div className="flex w-full items-stretch rounded-lg h-12 shadow-md">
                <input
                  className="flex-1 bg-[#233648] border border-border-dark border-r-0 rounded-l-lg px-4 text-white text-sm font-mono focus:ring-1 focus:ring-primary focus:border-primary outline-none"
                  readOnly
                  value={S3_ENDPOINT}
                />
                <button
                  onClick={copyEndpoint}
                  className="bg-primary hover:bg-blue-600 text-white px-4 rounded-r-lg text-sm font-bold transition-colors flex items-center gap-2"
                >
                  <Copy size={18} />
                  Copy
                </button>
              </div>
            </div>
          </div>

          {/* Tabs & Main Action Area */}
          <div className="flex flex-col gap-0">
            {/* Tabs Header */}
            <div className="border-b border-border-dark">
              <div className="flex gap-8 px-2">
                <button
                  onClick={() => setActiveTab('buckets')}
                  className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                    activeTab === 'buckets'
                      ? 'border-primary text-white'
                      : 'border-transparent text-text-secondary hover:text-white'
                  }`}
                >
                  <Folder size={20} />
                  <span className="text-sm font-bold">Buckets</span>
                </button>
                <button
                  onClick={() => setActiveTab('users')}
                  className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                    activeTab === 'users'
                      ? 'border-primary text-white'
                      : 'border-transparent text-text-secondary hover:text-white'
                  }`}
                >
                  <Users size={20} />
                  <span className="text-sm font-bold">Users & Keys</span>
                </button>
                <button
                  onClick={() => setActiveTab('monitoring')}
                  className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                    activeTab === 'monitoring'
                      ? 'border-primary text-white'
                      : 'border-transparent text-text-secondary hover:text-white'
                  }`}
                >
                  <Activity size={20} />
                  <span className="text-sm font-bold">Monitoring</span>
                </button>
                <button
                  onClick={() => setActiveTab('settings')}
                  className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                    activeTab === 'settings'
                      ? 'border-primary text-white'
                      : 'border-transparent text-text-secondary hover:text-white'
                  }`}
                >
                  <Filter size={20} />
                  <span className="text-sm font-bold">Settings</span>
                </button>
              </div>
            </div>

            {/* Toolbar */}
            <div className="py-6 flex flex-col md:flex-row justify-between items-center gap-4">
              <div className="relative w-full md:w-96">
                <Search className="absolute inset-y-0 left-0 flex items-center pl-3 text-text-secondary" size={20} />
                <input
                  className="w-full bg-[#233648] border border-border-dark text-white text-sm rounded-lg pl-10 pr-4 py-2.5 focus:ring-1 focus:ring-primary focus:border-primary outline-none placeholder:text-text-secondary"
                  placeholder="Filter buckets..."
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
              <button className="flex items-center justify-center gap-2 bg-primary hover:bg-blue-600 text-white px-5 py-2.5 rounded-lg text-sm font-bold transition-colors w-full md:w-auto shadow-lg shadow-blue-900/20">
                <Plus size={20} />
                Create Bucket
              </button>
            </div>

            {/* Tab Content */}
            {activeTab === 'buckets' && (
              <>
                {/* Data Table */}
                <div className="w-full overflow-hidden rounded-lg border border-border-dark bg-[#1c2936]">
                  <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">
                      <thead>
                        <tr className="border-b border-border-dark bg-[#16202a]">
                          <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-text-secondary">
                            Name
                          </th>
                          <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-text-secondary">
                            Usage
                          </th>
                          <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-text-secondary">
                            Objects
                          </th>
                          <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-text-secondary">
                            Access Policy
                          </th>
                          <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-text-secondary">
                            Created
                          </th>
                          <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-text-secondary text-right">
                            Actions
                          </th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-border-dark">
                        {paginatedBuckets.map((bucket) => (
                          <tr key={bucket.id} className="group hover:bg-[#233648] transition-colors">
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="flex items-center gap-3">
                                <div
                                  className={`flex h-10 w-10 items-center justify-center rounded-lg ${getBucketColorClass(
                                    bucket.color
                                  )}`}
                                >
                                  {getBucketIcon(bucket)}
                                </div>
                                <div className="flex flex-col">
                                  <p className="text-white text-sm font-bold">{bucket.name}</p>
                                  <p className="text-text-secondary text-xs">{bucket.type}</p>
                                </div>
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="flex flex-col gap-1 w-32">
                                <div className="flex justify-between text-xs">
                                  <span className="text-white font-medium">{formatBytes(bucket.usage, 1)}</span>
                                </div>
                                <div className="h-1.5 w-full bg-[#111a22] rounded-full">
                                  <div
                                    className={`h-1.5 rounded-full ${getProgressColor(bucket.color)}`}
                                    style={{ width: `${bucket.usagePercent}%` }}
                                  ></div>
                                </div>
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <p className="text-white text-sm">{bucket.objects.toLocaleString()}</p>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">{getAccessPolicyBadge(bucket.accessPolicy)}</td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <p className="text-text-secondary text-sm">{formatDate(bucket.created)}</p>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-right">
                              <button className="text-text-secondary hover:text-white transition-colors p-2 rounded hover:bg-white/5">
                                <MoreVertical size={18} />
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  {/* Pagination */}
                  <div className="flex items-center justify-between border-t border-border-dark px-6 py-3 bg-[#16202a]">
                    <p className="text-xs text-text-secondary">
                      Showing <span className="font-medium text-white">{paginatedBuckets.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}</span> to{' '}
                      <span className="font-medium text-white">
                        {Math.min(currentPage * itemsPerPage, filteredBuckets.length)}
                      </span>{' '}
                      of <span className="font-medium text-white">{filteredBuckets.length}</span> buckets
                    </p>
                    <div className="flex gap-2">
                      <button
                        onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                        disabled={currentPage === 1}
                        className="flex items-center justify-center h-8 w-8 rounded bg-[#233648] text-text-secondary hover:text-white hover:bg-[#2b4055] transition-colors disabled:opacity-50"
                      >
                        <span className="text-sm">‹</span>
                      </button>
                      <button
                        onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                        disabled={currentPage === totalPages}
                        className="flex items-center justify-center h-8 w-8 rounded bg-[#233648] text-text-secondary hover:text-white hover:bg-[#2b4055] transition-colors disabled:opacity-50"
                      >
                        <span className="text-sm">›</span>
                      </button>
                    </div>
                  </div>
                </div>
              </>
            )}

            {activeTab === 'users' && (
              <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
                <Users className="mx-auto mb-4 text-text-secondary" size={48} />
                <p className="text-text-secondary text-sm">Users & Keys management coming soon</p>
              </div>
            )}

            {activeTab === 'monitoring' && (
              <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
                <Activity className="mx-auto mb-4 text-text-secondary" size={48} />
                <p className="text-text-secondary text-sm">Monitoring dashboard coming soon</p>
              </div>
            )}

            {activeTab === 'settings' && (
              <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
                <Settings className="mx-auto mb-4 text-text-secondary" size={48} />
                <p className="text-text-secondary text-sm">Settings configuration coming soon</p>
              </div>
            )}
          </div>
        </div>
        <div className="h-12 w-full shrink-0"></div>
      </main>
    </div>
  )
}

