'use client';

import React, { useRef, useState } from 'react';
import { Tooltip } from '@tidbcloud/uikit';
import { updateWorkspace, transferWorkspaceOwner } from '@/lib/workspaces';
import { fetchWithAuth } from '@/lib/auth';
import SettingsModal from '@/components/SettingsModal';
import { useIsMobile } from '@/lib/useIsMobile';
import { useTranslation } from '@/lib/i18n';

const API = process.env.NEXT_PUBLIC_API_URL ?? '';

function CheckIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
    </svg>
  );
}

function ExportIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
      <polyline points="7 10 12 15 17 10"/>
      <line x1="12" y1="15" x2="12" y2="3"/>
    </svg>
  );
}

function SettingsIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3"/>
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
    </svg>
  );
}

function TransferIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M16 3h5v5"/>
      <line x1="21" y1="3" x2="14" y2="10"/>
      <path d="M8 21H3v-5"/>
      <line x1="3" y1="21" x2="10" y2="14"/>
    </svg>
  );
}

function InvestibookIcon({ size = 20 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">

      <defs>
        <linearGradient id="hdr-ib-bg" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#5c5fbc"/>
          <stop offset="100%" stopColor="#7c7fdc"/>
        </linearGradient>
      </defs>
      <rect width="32" height="32" rx="7" fill="url(#hdr-ib-bg)"/>
      <rect x="5" y="3" width="22" height="26" rx="3" fill="white" fillOpacity="0.18"/>
      <rect x="5" y="3" width="22" height="26" rx="3" stroke="white" strokeWidth="1.5"/>
      <rect x="8" y="7" width="7" height="5" rx="1" fill="white" fillOpacity="0.7"/>
      <rect x="17" y="8" width="7" height="1.5" rx="0.75" fill="white" fillOpacity="0.5"/>
      <rect x="17" y="11" width="5" height="1.5" rx="0.75" fill="white" fillOpacity="0.5"/>
      <rect x="8" y="16" width="16" height="1.5" rx="0.75" fill="white" fillOpacity="0.4"/>
      <rect x="8" y="19.5" width="13" height="1.5" rx="0.75" fill="white" fillOpacity="0.4"/>
      <rect x="8" y="23" width="14" height="1.5" rx="0.75" fill="white" fillOpacity="0.4"/>
    </svg>
  );
}

interface WorkspaceHeaderProps {
  workspace: { id: string; name: string };
  isOwner?: boolean;
  onWorkspaceNameChange: (name: string) => void;
  onTransferred?: () => void;
  onBack: () => void;
}

export default function WorkspaceHeader({
  workspace,
  isOwner = true,
  onWorkspaceNameChange,
  onTransferred,
  onBack,
}: WorkspaceHeaderProps) {
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [titleDraft, setTitleDraft] = useState('');
  const titleInputRef = useRef<HTMLInputElement>(null);
  const [copiedLink, setCopiedLink] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [settingsSection, setSettingsSection] = useState<'agent' | 'api-keys' | 'skills' | 'exports'>('agent');
  const [exportLoading, setExportLoading] = useState(false);
  const [transferOpen, setTransferOpen] = useState(false);
  const [transferEmail, setTransferEmail] = useState('');
  const [transferLoading, setTransferLoading] = useState(false);
  const [transferError, setTransferError] = useState('');
  const isMobile = useIsMobile();
  const { t } = useTranslation();

  const handleExport = async () => {
    if (!isOwner || exportLoading) return;
    setExportLoading(true);
    try {
      await fetchWithAuth(`${API}/api/workspace/${encodeURIComponent(workspace.id)}/export`, {
        method: 'POST',
      });
    } catch (e) {
      console.error('Failed to start export:', e);
    } finally {
      setExportLoading(false);
    }
    setSettingsSection('exports');
    setSettingsOpen(true);
  };

  const startEditingTitle = () => {
    if (!isOwner) return;
    setTitleDraft(workspace.name);
    setIsEditingTitle(true);
    setTimeout(() => titleInputRef.current?.select(), 0);
  };

  const commitTitle = () => {
    const name = titleDraft.trim() || t('home.untitled');
    updateWorkspace(workspace.id, { name });
    onWorkspaceNameChange(name);
    setIsEditingTitle(false);
  };

  const handleCopyLink = () => {
    const url = `${window.location.origin}/workspace/${workspace.id}`;
    navigator.clipboard.writeText(url).then(() => {
      setCopiedLink(true);
      setTimeout(() => setCopiedLink(false), 2000);
    });
  };

  const handleTransfer = async () => {
    const email = transferEmail.trim().toLowerCase();
    if (!email) return;
    setTransferLoading(true);
    setTransferError('');
    try {
      await transferWorkspaceOwner(workspace.id, email);
      setTransferOpen(false);
      setTransferEmail('');
      onTransferred?.();
    } catch (e: any) {
      setTransferError(e.message || t('workspaceHeader.transferFailed'));
    } finally {
      setTransferLoading(false);
    }
  };

  return (
    <>
      <div style={{
        height: '52px',
        display: 'flex',
        alignItems: 'center',
        padding: isMobile ? '0 16px' : '0 40px',
        borderBottom: 'none',
        backgroundColor: 'transparent',
        gap: '10px',
        flexShrink: 0,
      }}>
        {/* Brand — click to go back */}
        <div
          onClick={onBack}
          style={{ display: 'flex', alignItems: 'center', gap: '6px', flexShrink: 0, cursor: 'pointer', borderRadius: '6px', padding: '3px 6px', margin: '-3px -6px' }}
          onMouseEnter={(e: React.MouseEvent) => { (e.currentTarget as HTMLElement).style.background = '#f0f0fb'; }}
          onMouseLeave={(e: React.MouseEvent) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
        >
          <InvestibookIcon size={24} />
          {!isMobile && (
            <span style={{ fontSize: '15px', fontWeight: 700, color: '#1a1a2e', letterSpacing: '-0.3px' }}>
              Investibook
            </span>
          )}
        </div>

        {/* Separator — desktop only */}
        {!isMobile && (
          <span style={{ color: '#d1d5db', fontSize: '18px', lineHeight: 1, flexShrink: 0, userSelect: 'none' }}>/</span>
        )}

        {/* Workspace title */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {isEditingTitle ? (
            <input
              ref={titleInputRef}
              value={titleDraft}
              onChange={e => setTitleDraft(e.target.value)}
              onBlur={commitTitle}
              onKeyDown={e => {
                if (e.key === 'Enter') commitTitle();
                if (e.key === 'Escape') setIsEditingTitle(false);
              }}
              style={{
                fontSize: '14px',
                fontWeight: 600,
                border: 'none',
                borderBottom: '2px solid #5c5fbc',
                outline: 'none',
                background: 'transparent',
                width: '100%',
                padding: '2px 0',
                color: '#111827',
              }}
            />
          ) : (
            <span
              onClick={startEditingTitle}
              title={isOwner ? t('workspaceHeader.editTitleHint') : undefined}
              style={{
                fontSize: '14px',
                fontWeight: 600,
                cursor: isOwner ? 'text' : 'default',
                color: '#111827',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                display: 'block',
              }}
            >
              {workspace.name}
            </span>
          )}
        </div>

        {/* Right side actions */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
          <Tooltip label={copiedLink ? t('workspaceHeader.copiedLink') : t('workspaceHeader.copyLink')} position="bottom" withArrow>
            <button
              onClick={handleCopyLink}
              aria-label={t('workspaceHeader.copyLink')}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '6px',
                padding: isMobile ? '7px 10px' : '7px 16px',
                border: '1px solid transparent',
                borderRadius: '24px',
                background: 'transparent',
                color: copiedLink ? '#059669' : '#5f6368',
                fontSize: '14px',
                fontWeight: 500,
                cursor: 'pointer',
                lineHeight: 1,
              }}
            >
              {copiedLink ? <CheckIcon /> : <CopyIcon />}
              {!isMobile && <span>{copiedLink ? t('workspaceHeader.copiedLink') : t('workspaceHeader.copyLink')}</span>}
            </button>
          </Tooltip>

          {/* Transfer — owners only */}
          {isOwner && (
            <Tooltip label={t('workspaceHeader.transferTooltip')} position="bottom" withArrow>
              <button
                onClick={() => { setTransferError(''); setTransferEmail(''); setTransferOpen(true); }}
                aria-label={t('workspaceHeader.transferTooltip')}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: isMobile ? '7px 10px' : '7px 16px',
                  border: '1px solid transparent',
                  borderRadius: '24px',
                  background: 'transparent',
                  color: '#5f6368',
                  fontSize: '14px',
                  fontWeight: 500,
                  cursor: 'pointer',
                  lineHeight: 1,
                }}
              >
                <TransferIcon />
                {!isMobile && <span>{t('workspaceHeader.transfer')}</span>}
              </button>
            </Tooltip>
          )}

          {/* Export — owners only */}
          {isOwner && (
            <Tooltip label={t('workspaceHeader.exportTooltip')} position="bottom" withArrow>
              <button
                onClick={handleExport}
                disabled={exportLoading}
                aria-label={t('workspaceHeader.exportTooltip')}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: isMobile ? '7px 10px' : '7px 16px',
                  border: '1px solid transparent',
                  borderRadius: '24px',
                  background: 'transparent',
                  color: exportLoading ? '#9ca3af' : '#5f6368',
                  fontSize: '14px',
                  fontWeight: 500,
                  cursor: exportLoading ? 'default' : 'pointer',
                  lineHeight: 1,
                }}
              >
                <ExportIcon />
                {!isMobile && <span>{exportLoading ? t('workspaceHeader.exporting') : t('workspaceHeader.export')}</span>}
              </button>
            </Tooltip>
          )}

          {/* Settings */}
          <button
            onClick={() => { setSettingsSection('agent'); setSettingsOpen(true); }}
            aria-label={t('workspaceHeader.settings')}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: isMobile ? '7px 10px' : '7px 16px',
              border: '1px solid transparent',
              borderRadius: '24px',
              background: 'transparent',
              color: '#5f6368',
              fontSize: '14px',
              fontWeight: 500,
              cursor: 'pointer',
              lineHeight: 1,
            }}
          >
            <SettingsIcon />
            {!isMobile && <span>{t('workspaceHeader.settings')}</span>}
          </button>
        </div>
      </div>

      {/* Transfer ownership modal */}
      {transferOpen && (
        <div
          onClick={() => setTransferOpen(false)}
          style={{
            position: 'fixed',
            inset: 0,
            background: 'rgba(0,0,0,0.35)',
            zIndex: 1000,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              background: '#fff',
              borderRadius: '12px',
              padding: '24px',
              width: '400px',
              maxWidth: '90vw',
              boxShadow: '0 8px 32px rgba(0,0,0,0.18)',
            }}
          >
            <div style={{ fontSize: '16px', fontWeight: 600, marginBottom: '8px', color: '#111827' }}>
              {t('workspaceHeader.transferTitle')}
            </div>
            <div style={{ fontSize: '13px', color: '#6b7280', marginBottom: '16px' }}>
              {t('workspaceHeader.transferDescription')}
            </div>
            <input
              type="email"
              placeholder={t('workspaceHeader.transferEmailPlaceholder')}
              value={transferEmail}
              onChange={(e) => setTransferEmail(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') handleTransfer(); }}
              autoFocus
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d1d5db',
                borderRadius: '8px',
                fontSize: '14px',
                outline: 'none',
                boxSizing: 'border-box',
              }}
            />
            {transferError && (
              <div style={{ color: '#ef4444', fontSize: '13px', marginTop: '8px' }}>
                {transferError}
              </div>
            )}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px', marginTop: '16px' }}>
              <button
                onClick={() => setTransferOpen(false)}
                style={{
                  padding: '8px 16px',
                  borderRadius: '8px',
                  border: '1px solid #d1d5db',
                  background: '#fff',
                  color: '#374151',
                  fontSize: '14px',
                  cursor: 'pointer',
                }}
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleTransfer}
                disabled={transferLoading || !transferEmail.trim()}
                style={{
                  padding: '8px 16px',
                  borderRadius: '8px',
                  border: 'none',
                  background: transferLoading || !transferEmail.trim() ? '#9ca3af' : '#5c5fbc',
                  color: '#fff',
                  fontSize: '14px',
                  fontWeight: 500,
                  cursor: transferLoading || !transferEmail.trim() ? 'default' : 'pointer',
                }}
              >
                {transferLoading ? t('workspaceHeader.transferring') : t('workspaceHeader.transferAction')}
              </button>
            </div>
          </div>
        </div>
      )}

      <SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} workspaceId={workspace.id} initialSection={settingsSection} />
    </>
  );
}
