'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import {
  Settings2,
  Database,
  Globe,
  Type,
  Plus,
  Trash2,
  ChevronDown,
  ChevronUp,
  ArrowLeft,
  Zap,
  Edit3,
  Check,
  X,
} from 'lucide-react';
import {
  ExpertModeSpec,
  ExpertEntity,
  ExpertEndpoint,
  ExpertField,
  NamingConventions,
  TargetLanguage,
  TargetDatabase,
  getLanguageOption,
  getDatabaseOption,
} from '@/lib/dark-factory/types/generation-options';

interface ExpertModePanelProps {
  spec: ExpertModeSpec;
  language: TargetLanguage;
  database: TargetDatabase;
  onSpecChange: (spec: ExpertModeSpec) => void;
  onConfirm: () => void;
  onBack: () => void;
  isGenerating: boolean;
}

export function ExpertModePanel({
  spec,
  language,
  database,
  onSpecChange,
  onConfirm,
  onBack,
  isGenerating,
}: ExpertModePanelProps) {
  const [expandedEntity, setExpandedEntity] = useState<number | null>(0);
  const [expandedEndpoints, setExpandedEndpoints] = useState(false);
  const [expandedNaming, setExpandedNaming] = useState(false);

  const langOpt = getLanguageOption(language);
  const dbOpt = getDatabaseOption(database);

  const updateEntity = (idx: number, updates: Partial<ExpertEntity>) => {
    const newEntities = [...spec.entities];
    newEntities[idx] = { ...newEntities[idx], ...updates };
    onSpecChange({ ...spec, entities: newEntities });
  };

  const addEntity = () => {
    const newEntity: ExpertEntity = {
      name: 'NewEntity',
      description: '',
      fields: [
        { name: 'id', type: 'String', required: true, description: 'Primary key' },
        { name: 'createdAt', type: 'DateTime', required: true, description: 'Created timestamp' },
        { name: 'updatedAt', type: 'DateTime', required: true, description: 'Updated timestamp' },
      ],
      relations: [],
    };
    onSpecChange({ ...spec, entities: [...spec.entities, newEntity] });
    setExpandedEntity(spec.entities.length);
  };

  const removeEntity = (idx: number) => {
    const newEntities = spec.entities.filter((_, i) => i !== idx);
    onSpecChange({ ...spec, entities: newEntities });
    if (expandedEntity === idx) setExpandedEntity(null);
  };

  const addFieldToEntity = (entityIdx: number) => {
    const entity = spec.entities[entityIdx];
    const newField: ExpertField = { name: 'newField', type: 'String', required: false, description: '' };
    updateEntity(entityIdx, { fields: [...entity.fields, newField] });
  };

  const updateField = (entityIdx: number, fieldIdx: number, updates: Partial<ExpertField>) => {
    const entity = spec.entities[entityIdx];
    const newFields = [...entity.fields];
    newFields[fieldIdx] = { ...newFields[fieldIdx], ...updates };
    updateEntity(entityIdx, { fields: newFields });
  };

  const removeField = (entityIdx: number, fieldIdx: number) => {
    const entity = spec.entities[entityIdx];
    const newFields = entity.fields.filter((_, i) => i !== fieldIdx);
    updateEntity(entityIdx, { fields: newFields });
  };

  const updateEndpoint = (idx: number, updates: Partial<ExpertEndpoint>) => {
    const newEndpoints = [...spec.endpoints];
    newEndpoints[idx] = { ...newEndpoints[idx], ...updates };
    onSpecChange({ ...spec, endpoints: newEndpoints });
  };

  const addEndpoint = () => {
    const newEndpoint: ExpertEndpoint = {
      path: '/api/new-endpoint',
      method: 'GET',
      description: '',
      businessLogic: [],
    };
    onSpecChange({ ...spec, endpoints: [...spec.endpoints, newEndpoint] });
    setExpandedEndpoints(true);
  };

  const removeEndpoint = (idx: number) => {
    onSpecChange({ ...spec, endpoints: spec.endpoints.filter((_, i) => i !== idx) });
  };

  const updateNaming = (updates: Partial<NamingConventions>) => {
    onSpecChange({ ...spec, namingConventions: { ...spec.namingConventions, ...updates } });
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="space-y-6"
    >
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Settings2 className="w-6 h-6 text-orange-400" />
          <div>
            <h2 className="text-xl font-semibold text-white">Expert Mode</h2>
            <p className="text-sm text-gray-400">Review and customize before generation</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className="px-2 py-1 text-xs rounded-md bg-brand-deep/10 text-brand border border-brand-deep/20">
            {langOpt.icon} {langOpt.shortLabel}
          </span>
          <span className="px-2 py-1 text-xs rounded-md bg-brand-secondary/10 text-brand-secondary-light border border-brand-secondary/20">
            {dbOpt.icon} {dbOpt.shortLabel}
          </span>
        </div>
      </div>

      {/* Summary */}
      <div className="p-4 rounded-xl bg-white/5 border border-white/10">
        <label className="block text-sm font-medium text-gray-300 mb-2">Architecture Summary</label>
        <input
          type="text"
          value={spec.summary}
          onChange={(e) => onSpecChange({ ...spec, summary: e.target.value })}
          className="w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:border-brand-deep/50"
        />
      </div>

      {/* === ENTITIES (ERD-style) === */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Database className="w-5 h-5 text-brand" />
            <h3 className="text-lg font-semibold text-white">Entities / Models</h3>
            <span className="text-xs text-gray-500 bg-white/5 px-2 py-0.5 rounded-full">{spec.entities.length}</span>
          </div>
          <button
            type="button"
            onClick={addEntity}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg bg-brand-deep/10 text-brand hover:bg-brand-deep/20 border border-brand-deep/20 transition-colors"
          >
            <Plus className="w-3.5 h-3.5" />
            Add Entity
          </button>
        </div>

        {spec.entities.map((entity, entityIdx) => (
          <div key={entityIdx} className="rounded-xl border border-white/10 overflow-hidden bg-white/[0.02]">
            {/* Entity Header */}
            <button
              type="button"
              onClick={() => setExpandedEntity(expandedEntity === entityIdx ? null : entityIdx)}
              className="w-full flex items-center justify-between px-4 py-3 hover:bg-white/5 transition-colors"
            >
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-brand-deep/20 to-brand-secondary/20 flex items-center justify-center text-xs font-bold text-brand-light">
                  {entity.name.charAt(0)}
                </div>
                <div className="text-left">
                  <div className="text-sm font-medium text-white">{entity.name}</div>
                  <div className="text-xs text-gray-500">
                    {entity.fields.length} fields · {entity.relations.length} relations
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={(e) => { e.stopPropagation(); removeEntity(entityIdx); }}
                  className="p-1.5 rounded-lg hover:bg-red-500/10 text-gray-500 hover:text-red-400 transition-colors"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
                {expandedEntity === entityIdx ? (
                  <ChevronUp className="w-4 h-4 text-gray-500" />
                ) : (
                  <ChevronDown className="w-4 h-4 text-gray-500" />
                )}
              </div>
            </button>

            {/* Entity Body */}
            {expandedEntity === entityIdx && (
              <div className="px-4 pb-4 space-y-3 border-t border-white/5">
                {/* Entity Name & Description */}
                <div className="grid grid-cols-2 gap-3 pt-3">
                  <div>
                    <label className="text-xs text-gray-500 mb-1 block">Name</label>
                    <input
                      type="text"
                      value={entity.name}
                      onChange={(e) => updateEntity(entityIdx, { name: e.target.value })}
                      className="w-full px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:border-brand-deep/50"
                    />
                  </div>
                  <div>
                    <label className="text-xs text-gray-500 mb-1 block">Description</label>
                    <input
                      type="text"
                      value={entity.description}
                      onChange={(e) => updateEntity(entityIdx, { description: e.target.value })}
                      className="w-full px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:border-brand-deep/50"
                    />
                  </div>
                </div>

                {/* Fields Table */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-xs font-medium text-gray-400">Fields</span>
                    <button
                      type="button"
                      onClick={() => addFieldToEntity(entityIdx)}
                      className="flex items-center gap-1 text-xs text-brand hover:text-brand-light"
                    >
                      <Plus className="w-3 h-3" /> Add Field
                    </button>
                  </div>
                  <div className="space-y-1">
                    {entity.fields.map((field, fieldIdx) => (
                      <div key={fieldIdx} className="flex items-center gap-2 group">
                        <input
                          type="text"
                          value={field.name}
                          onChange={(e) => updateField(entityIdx, fieldIdx, { name: e.target.value })}
                          className="flex-1 px-2 py-1 rounded bg-white/5 border border-white/5 text-white text-xs focus:outline-none focus:border-brand-deep/50 font-mono"
                          placeholder="fieldName"
                        />
                        <select
                          value={field.type}
                          onChange={(e) => updateField(entityIdx, fieldIdx, { type: e.target.value })}
                          className="w-28 px-2 py-1 rounded bg-white/5 border border-white/5 text-gray-300 text-xs focus:outline-none focus:border-brand-deep/50 appearance-none"
                        >
                          {['String', 'Int', 'Float', 'Decimal', 'Boolean', 'DateTime', 'Json'].map(t => (
                            <option key={t} value={t} className="bg-brand-bg-elevated text-white">{t}</option>
                          ))}
                        </select>
                        <label className="flex items-center gap-1 text-xs text-gray-500">
                          <input
                            type="checkbox"
                            checked={field.required}
                            onChange={(e) => updateField(entityIdx, fieldIdx, { required: e.target.checked })}
                            className="rounded border-gray-600 bg-white/5 text-brand-deep focus:ring-brand-deep/30"
                          />
                          Req
                        </label>
                        <button
                          type="button"
                          onClick={() => removeField(entityIdx, fieldIdx)}
                          className="p-1 rounded hover:bg-red-500/10 text-gray-600 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* === ENDPOINTS === */}
      <div className="space-y-3">
        <button
          type="button"
          onClick={() => setExpandedEndpoints(!expandedEndpoints)}
          className="w-full flex items-center justify-between"
        >
          <div className="flex items-center gap-2">
            <Globe className="w-5 h-5 text-green-400" />
            <h3 className="text-lg font-semibold text-white">API Endpoints</h3>
            <span className="text-xs text-gray-500 bg-white/5 px-2 py-0.5 rounded-full">{spec.endpoints.length}</span>
          </div>
          {expandedEndpoints ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}
        </button>

        {expandedEndpoints && (
          <div className="space-y-2">
            {spec.endpoints.map((ep, idx) => (
              <div key={idx} className="flex items-center gap-2 group">
                <select
                  value={ep.method}
                  onChange={(e) => updateEndpoint(idx, { method: e.target.value })}
                  className="w-20 px-2 py-1.5 rounded-lg bg-white/5 border border-white/10 text-xs font-mono text-gray-300 focus:outline-none appearance-none"
                >
                  {['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].map(m => (
                    <option key={m} value={m} className="bg-brand-bg-elevated text-white">{m}</option>
                  ))}
                </select>
                <input
                  type="text"
                  value={ep.path}
                  onChange={(e) => updateEndpoint(idx, { path: e.target.value })}
                  className="flex-1 px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-white text-xs font-mono focus:outline-none focus:border-green-500/50"
                />
                <input
                  type="text"
                  value={ep.description}
                  onChange={(e) => updateEndpoint(idx, { description: e.target.value })}
                  className="flex-1 px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-gray-300 text-xs focus:outline-none focus:border-green-500/50"
                  placeholder="Description"
                />
                <button
                  type="button"
                  onClick={() => removeEndpoint(idx)}
                  className="p-1.5 rounded-lg hover:bg-red-500/10 text-gray-600 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
            <button
              type="button"
              onClick={addEndpoint}
              className="flex items-center gap-1.5 text-sm text-green-400 hover:text-green-300"
            >
              <Plus className="w-3.5 h-3.5" /> Add Endpoint
            </button>
          </div>
        )}
      </div>

      {/* === NAMING CONVENTIONS === */}
      <div className="space-y-3">
        <button
          type="button"
          onClick={() => setExpandedNaming(!expandedNaming)}
          className="w-full flex items-center justify-between"
        >
          <div className="flex items-center gap-2">
            <Type className="w-5 h-5 text-yellow-400" />
            <h3 className="text-lg font-semibold text-white">Naming Conventions</h3>
          </div>
          {expandedNaming ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}
        </button>

        {expandedNaming && (
          <div className="grid grid-cols-2 gap-3">
            {[
              { key: 'modelCase' as const, label: 'Model Names', options: ['PascalCase', 'camelCase', 'snake_case'] },
              { key: 'fieldCase' as const, label: 'Field Names', options: ['camelCase', 'snake_case', 'PascalCase'] },
              { key: 'endpointCase' as const, label: 'Endpoints', options: ['kebab-case', 'snake_case', 'camelCase'] },
              { key: 'fileNaming' as const, label: 'File Naming', options: ['kebab-case', 'PascalCase', 'snake_case'] },
            ].map(({ key, label, options }) => (
              <div key={key}>
                <label className="text-xs text-gray-500 mb-1 block">{label}</label>
                <select
                  value={spec.namingConventions[key]}
                  onChange={(e) => updateNaming({ [key]: e.target.value })}
                  className="w-full px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-gray-300 text-sm focus:outline-none focus:border-yellow-500/50 appearance-none"
                >
                  {options.map(opt => (
                    <option key={opt} value={opt} className="bg-brand-bg-elevated text-white">{opt}</option>
                  ))}
                </select>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Action Buttons */}
      <div className="flex items-center gap-3 pt-4 border-t border-white/10">
        <button
          type="button"
          onClick={onBack}
          disabled={isGenerating}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-colors disabled:opacity-50"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Prompt
        </button>
        <button
          type="button"
          onClick={onConfirm}
          disabled={isGenerating || spec.entities.length === 0}
          className="flex-1 flex items-center justify-center gap-2 px-6 py-2.5 rounded-xl font-semibold text-white bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg shadow-orange-500/25"
        >
          <Zap className="w-5 h-5" />
          {isGenerating ? 'Generating...' : 'Confirm & Generate'}
        </button>
      </div>
    </motion.div>
  );
}
