'use client';

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Globe, Monitor, Smartphone, Download, ChevronDown, ChevronUp,
  Check, Info, Zap, Package, Settings2
} from 'lucide-react';

export type DeploymentPlatform = 'web' | 'desktop-electron' | 'desktop-tauri' | 'mobile-pwa' | 'mobile-capacitor';

interface TargetOption {
  id: DeploymentPlatform;
  label: string;
  shortLabel: string;
  icon: React.ReactNode;
  description: string;
  outputs: string[];
  recommended: boolean;
  category: 'web' | 'desktop' | 'mobile';
}

const TARGETS: TargetOption[] = [
  {
    id: 'web',
    label: 'Web Application',
    shortLabel: 'Web',
    icon: <Globe className="w-5 h-5" />,
    description: 'Deploy as a web app accessible from any browser.',
    outputs: ['Standalone Server', 'Static Export', 'Docker'],
    recommended: true,
    category: 'web',
  },
  {
    id: 'desktop-electron',
    label: 'Desktop (Electron)',
    shortLabel: 'Electron',
    icon: <Monitor className="w-5 h-5" />,
    description: 'Native desktop app for Windows, macOS, and Linux.',
    outputs: ['.exe', '.dmg', '.AppImage'],
    recommended: true,
    category: 'desktop',
  },
  {
    id: 'desktop-tauri',
    label: 'Desktop (Tauri)',
    shortLabel: 'Tauri',
    icon: <Zap className="w-5 h-5" />,
    description: 'Lightweight native app using Rust. Smaller binary size.',
    outputs: ['.msi', '.dmg', '.AppImage'],
    recommended: false,
    category: 'desktop',
  },
  {
    id: 'mobile-pwa',
    label: 'Mobile (PWA)',
    shortLabel: 'PWA',
    icon: <Smartphone className="w-5 h-5" />,
    description: 'Installable from browser. Works offline. No app store.',
    outputs: ['manifest.json', 'Service Worker'],
    recommended: true,
    category: 'mobile',
  },
  {
    id: 'mobile-capacitor',
    label: 'Mobile (Capacitor)',
    shortLabel: 'Native',
    icon: <Download className="w-5 h-5" />,
    description: 'Native iOS & Android apps via App Store / Google Play.',
    outputs: ['.ipa', '.apk', '.aab'],
    recommended: false,
    category: 'mobile',
  },
];

interface DeploymentTargetSelectorProps {
  selected: DeploymentPlatform[];
  onChange: (targets: DeploymentPlatform[]) => void;
}

export default function DeploymentTargetSelector({ selected, onChange }: DeploymentTargetSelectorProps) {
  const [expanded, setExpanded] = useState(false);
  const [showDetails, setShowDetails] = useState<string | null>(null);

  const toggle = (id: DeploymentPlatform) => {
    if (id === 'web') return; // Web is always selected
    const next = selected.includes(id)
      ? selected.filter(s => s !== id)
      : [...selected, id];
    onChange(next);
  };

  const categories = [
    { key: 'web', label: 'Web', icon: <Globe className="w-4 h-4" /> },
    { key: 'desktop', label: 'Desktop', icon: <Monitor className="w-4 h-4" /> },
    { key: 'mobile', label: 'Mobile', icon: <Smartphone className="w-4 h-4" /> },
  ];

  const selectedCount = selected.length;
  const selectedLabels = TARGETS.filter(t => selected.includes(t.id)).map(t => t.shortLabel);

  return (
    <div className="space-y-3">
      <button
        type="button"
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center justify-between px-4 py-3 rounded-lg border border-white/10 bg-white/5 hover:bg-white/10 transition-colors"
      >
        <div className="flex items-center gap-3">
          <Package className="w-5 h-5 text-brand" />
          <div className="text-left">
            <div className="text-sm font-medium text-gray-200">Deployment Targets</div>
            <div className="text-xs text-gray-400">
              {selectedLabels.join(' + ')} ({selectedCount} platform{selectedCount !== 1 ? 's' : ''})
            </div>
          </div>
        </div>
        {expanded ? <ChevronUp className="w-4 h-4 text-gray-400" /> : <ChevronDown className="w-4 h-4 text-gray-400" />}
      </button>

      <AnimatePresence>
        {expanded && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <div className="space-y-4 py-2">
              {categories.map(cat => (
                <div key={cat.key}>
                  <div className="flex items-center gap-2 mb-2 px-1">
                    <span className="text-gray-400">{cat.icon}</span>
                    <span className="text-xs font-medium text-gray-400 uppercase tracking-wider">{cat.label}</span>
                  </div>
                  <div className="grid grid-cols-1 gap-2">
                    {TARGETS.filter(t => t.category === cat.key).map(target => {
                      const isSelected = selected.includes(target.id);
                      const isWeb = target.id === 'web';
                      
                      return (
                        <div key={target.id} className="relative">
                          <button
                            type="button"
                            onClick={() => toggle(target.id)}
                            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg border transition-all text-left ${
                              isSelected
                                ? 'border-brand-deep/50 bg-brand-deep/10'
                                : 'border-white/5 bg-white/[0.02] hover:bg-white/5'
                            } ${isWeb ? 'cursor-default' : 'cursor-pointer'}`}
                          >
                            <div className={`p-1.5 rounded-md ${
                              isSelected ? 'bg-brand-deep/20 text-brand' : 'bg-white/5 text-gray-500'
                            }`}>
                              {target.icon}
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2">
                                <span className={`text-sm font-medium ${
                                  isSelected ? 'text-gray-100' : 'text-gray-400'
                                }`}>{target.label}</span>
                                {target.recommended && (
                                  <span className="text-[10px] px-1.5 py-0.5 rounded bg-green-500/20 text-green-400 font-medium">
                                    Recommended
                                  </span>
                                )}
                                {isWeb && (
                                  <span className="text-[10px] px-1.5 py-0.5 rounded bg-brand-secondary/20 text-brand-secondary-light font-medium">
                                    Always On
                                  </span>
                                )}
                              </div>
                              <p className="text-xs text-gray-500 truncate">{target.description}</p>
                            </div>
                            <div className={`w-5 h-5 rounded-md border flex items-center justify-center ${
                              isSelected
                                ? 'border-brand-deep bg-brand-deep'
                                : 'border-white/20 bg-transparent'
                            }`}>
                              {isSelected && <Check className="w-3 h-3 text-white" />}
                            </div>
                          </button>

                          {/* Expandable details */}
                          <AnimatePresence>
                            {showDetails === target.id && (
                              <motion.div
                                initial={{ opacity: 0, height: 0 }}
                                animate={{ opacity: 1, height: 'auto' }}
                                exit={{ opacity: 0, height: 0 }}
                                className="overflow-hidden"
                              >
                                <div className="px-3 py-2 mt-1 rounded-lg bg-white/[0.02] border border-white/5">
                                  <div className="text-xs text-gray-400 mb-1">Output Formats:</div>
                                  <div className="flex flex-wrap gap-1">
                                    {target.outputs.map(o => (
                                      <span key={o} className="text-[10px] px-2 py-0.5 rounded bg-white/5 text-gray-300">{o}</span>
                                    ))}
                                  </div>
                                </div>
                              </motion.div>
                            )}
                          </AnimatePresence>

                          <button
                            type="button"
                            onClick={(e) => {
                              e.stopPropagation();
                              setShowDetails(showDetails === target.id ? null : target.id);
                            }}
                            className="absolute top-3 right-10 p-1 text-gray-500 hover:text-gray-300 transition-colors"
                          >
                            <Info className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}

              {/* Quick select buttons */}
              <div className="flex gap-2 pt-1">
                <button
                  type="button"
                  onClick={() => onChange(['web', 'desktop-electron', 'mobile-pwa'])}
                  className="flex-1 text-xs py-1.5 rounded-md border border-white/10 text-gray-400 hover:text-gray-200 hover:border-white/20 transition-colors"
                >
                  <Settings2 className="w-3 h-3 inline mr-1" />
                  Recommended
                </button>
                <button
                  type="button"
                  onClick={() => onChange(['web', 'desktop-electron', 'desktop-tauri', 'mobile-pwa', 'mobile-capacitor'])}
                  className="flex-1 text-xs py-1.5 rounded-md border border-white/10 text-gray-400 hover:text-gray-200 hover:border-white/20 transition-colors"
                >
                  <Package className="w-3 h-3 inline mr-1" />
                  All Platforms
                </button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
