/**
 * LinkEditorContent Component
 *
 * Main content area for the link editor. Handles data fetching,
 * drag-and-drop, and save operations. Style-guide compliant.
 */

'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import Link from 'next/link';
import { Plus, Clock } from 'lucide-react';
import { SortableLinkItem } from './SortableLinkItem';
import { LinkEditModal } from './LinkEditModal';
import { LinkPreview } from './LinkPreview';

export interface LinkItem {
  id: string;
  label: string;
  linkType: 'page' | 'external' | 'pdf';
  pageId: string | null;
  pageSlug: string | null;
  pageTitle: string | null;
  externalUrl: string | null;
  openInNewTab: boolean;
  sortOrder: number;
}

interface PageOption {
  id: string;
  slug: string;
  title: string;
}

interface LinkEditorContentProps {
  onAccessDenied: () => void;
}

export default function LinkEditorContent({ onAccessDenied }: LinkEditorContentProps) {
  const [links, setLinks] = useState<LinkItem[]>([]);
  const [pages, setPages] = useState<PageOption[]>([]);
  const [dealerId, setDealerId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editingLink, setEditingLink] = useState<LinkItem | null>(null);
  const [lastSaved, setLastSaved] = useState<Date | null>(null);

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: { distance: 5 },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  // Fetch links, pages, and dealer info on mount
  useEffect(() => {
    async function fetchData() {
      try {
        const [linksRes, pagesRes, dealerRes] = await Promise.all([
          fetch('/api/cms/links'),
          fetch('/api/cms/pages?type=page'),
          fetch('/api/dealer'),
        ]);

        if (linksRes.status === 403) {
          onAccessDenied();
          return;
        }

        if (!linksRes.ok) {
          throw new Error('Failed to fetch links');
        }

        const linksData = await linksRes.json();
        setLinks(linksData.links || []);

        if (pagesRes.ok) {
          const pagesData = await pagesRes.json();
          setPages(pagesData.pages || []);
        }

        if (dealerRes.ok) {
          const dealerData = await dealerRes.json();
          setDealerId(dealerData.id);
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load data');
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [onAccessDenied]);

  // Handle drag end
  const handleDragEnd = useCallback((event: DragEndEvent) => {
    const { active, over } = event;

    if (over && active.id !== over.id) {
      setLinks((items) => {
        const oldIndex = items.findIndex((i) => i.id === active.id);
        const newIndex = items.findIndex((i) => i.id === over.id);
        const newItems = arrayMove(items, oldIndex, newIndex);
        // Update sortOrder
        return newItems.map((item, index) => ({ ...item, sortOrder: index }));
      });
    }
  }, []);

  // Move link up/down (accessibility)
  const moveLink = useCallback((id: string, direction: 'up' | 'down') => {
    setLinks((items) => {
      const index = items.findIndex((i) => i.id === id);
      if (index === -1) return items;

      const newIndex = direction === 'up' ? index - 1 : index + 1;
      if (newIndex < 0 || newIndex >= items.length) return items;

      const newItems = arrayMove(items, index, newIndex);
      return newItems.map((item, idx) => ({ ...item, sortOrder: idx }));
    });
  }, []);

  // Add new link
  const handleAddLink = useCallback(() => {
    if (links.length >= 10) {
      setError('Maximum 10 links allowed');
      return;
    }

    const newLink: LinkItem = {
      id: `link-${crypto.randomUUID()}`,
      label: 'New Link',
      linkType: 'external',
      pageId: null,
      pageSlug: null,
      pageTitle: null,
      externalUrl: '',
      openInNewTab: true,
      sortOrder: links.length,
    };

    setLinks((prev) => [...prev, newLink]);
    setEditingLink(newLink);
  }, [links.length]);

  // Delete link
  const handleDeleteLink = useCallback((id: string) => {
    setLinks((items) => {
      const newItems = items.filter((i) => i.id !== id);
      return newItems.map((item, index) => ({ ...item, sortOrder: index }));
    });
  }, []);

  // Save edited link
  const handleSaveEdit = useCallback((updatedLink: LinkItem) => {
    setLinks((items) => items.map((item) => (item.id === updatedLink.id ? updatedLink : item)));
    setEditingLink(null);
  }, []);

  // Publish links and site
  const handlePublish = useCallback(async () => {
    if (saving) return; // Guard against double-clicks
    setSaving(true);
    setError(null);

    try {
      // Step 1: Save links
      const response = await fetch('/api/cms/links', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ links, publish: true }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || 'Failed to save links');
      }

      // Step 2: Publish the dealer site
      if (!dealerId) {
        throw new Error('Dealer ID not found. Please refresh and try again.');
      }

      const publishResponse = await fetch(`/api/dealers/${dealerId}/publish`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });

      if (!publishResponse.ok) {
        const publishData = await publishResponse.json();
        throw new Error(publishData.error || 'Failed to publish site');
      }

      setLastSaved(new Date());
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to publish');
    } finally {
      setSaving(false);
    }
  }, [links, dealerId, saving]);

  // Column distribution for display
  const distribution = useMemo(() => {
    const total = links.length;
    const left = Math.ceil(total / 2);
    const right = total - left;
    return `${left} | ${right}`;
  }, [links.length]);

  if (loading) {
    return (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: '400px',
        }}
      >
        <div
          style={{
            width: '32px',
            height: '32px',
            border: '2px solid rgba(56, 189, 248, 0.3)',
            borderTopColor: '#38bdf8',
            borderRadius: '50%',
            animation: 'spin 1s linear infinite',
          }}
        />
      </div>
    );
  }

  return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '32px' }}>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: '32px',
        }}
      >
        <div>
          <Link
            href="/dashboard"
            style={{ color: '#38bdf8', textDecoration: 'none', fontSize: '0.875rem' }}
          >
            ← Back to Dashboard
          </Link>
          <h1
            style={{
              fontSize: '32px',
              fontWeight: 700,
              color: '#f8fafc',
              margin: 0,
              marginTop: '8px',
              letterSpacing: '-0.64px',
            }}
          >
            Quick Links
          </h1>
          <p
            style={{
              color: 'rgba(148, 163, 184, 0.85)',
              marginTop: '8px',
              fontSize: '16px',
            }}
          >
            Manage links displayed on your dealer page
          </p>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          {lastSaved && (
            <span
              style={{
                fontSize: '13px',
                color: 'rgba(148, 163, 184, 0.7)',
                display: 'flex',
                alignItems: 'center',
                gap: '6px',
              }}
            >
              <Clock size={14} />
              Saved {lastSaved.toLocaleTimeString()}
            </span>
          )}
          <button
            onClick={handlePublish}
            disabled={saving}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              padding: '12px 24px',
              background: saving ? 'rgba(71, 85, 105, 0.4)' : '#38bdf8',
              border: 'none',
              borderRadius: '8px',
              color: saving ? 'rgba(226, 232, 240, 0.65)' : '#0f172a',
              fontSize: '16px',
              fontWeight: 600,
              cursor: saving ? 'not-allowed' : 'pointer',
              transition: 'transform 0.2s ease, box-shadow 0.2s ease',
              boxShadow: saving ? 'none' : '0 8px 20px -12px rgba(56, 189, 248, 0.6)',
            }}
            onMouseEnter={(e) => {
              if (!saving) {
                e.currentTarget.style.transform = 'translateY(-2px)';
                e.currentTarget.style.boxShadow = '0 16px 40px -15px rgba(56, 189, 248, 0.95)';
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = 'translateY(0)';
              e.currentTarget.style.boxShadow = saving
                ? 'none'
                : '0 8px 20px -12px rgba(56, 189, 248, 0.6)';
            }}
          >
            {saving ? 'Publishing...' : 'Publish'}
          </button>
        </div>
      </div>

      {/* Error Alert */}
      {error && (
        <div
          style={{
            marginBottom: '24px',
            padding: '16px',
            background: 'rgba(248, 113, 113, 0.1)',
            border: '1px solid rgba(248, 113, 113, 0.35)',
            borderLeft: '4px solid #f87171',
            borderRadius: '12px',
            color: '#fee2e2',
            fontSize: '14px',
          }}
        >
          {error}
        </div>
      )}

      {/* Main content: Editor + Preview */}
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: '1fr',
          gap: '24px',
        }}
      >
        {/* Desktop: side-by-side layout */}
        <style>
          {`
            @media (min-width: 1024px) {
              .link-editor-grid {
                grid-template-columns: 3fr 2fr !important;
              }
            }
            @keyframes spin {
              to { transform: rotate(360deg); }
            }
          `}
        </style>
        <div
          className="link-editor-grid"
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr',
            gap: '24px',
          }}
        >
          {/* Editor Card */}
          <div
            style={{
              background: 'rgba(30, 41, 59, 0.6)',
              border: '1px solid rgba(148, 163, 184, 0.2)',
              borderRadius: '20px',
              padding: '24px',
            }}
          >
            {/* Editor Header */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                marginBottom: '20px',
              }}
            >
              <h2
                style={{
                  fontSize: '18px',
                  fontWeight: 600,
                  color: '#f8fafc',
                  margin: 0,
                }}
              >
                Your Links
              </h2>
              <span
                style={{
                  fontSize: '13px',
                  color: 'rgba(148, 163, 184, 0.7)',
                }}
              >
                {links.length}/10 links • Distribution: [{distribution}]
              </span>
            </div>

            {/* Links List */}
            <DndContext
              sensors={sensors}
              collisionDetection={closestCenter}
              onDragEnd={handleDragEnd}
            >
              <SortableContext
                items={links.map((l) => l.id)}
                strategy={verticalListSortingStrategy}
              >
                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  {links.length === 0 ? (
                    <div
                      style={{
                        textAlign: 'center',
                        padding: '48px 24px',
                        color: 'rgba(148, 163, 184, 0.7)',
                      }}
                    >
                      <p style={{ fontSize: '16px', margin: 0 }}>No links yet</p>
                      <p style={{ fontSize: '14px', marginTop: '8px' }}>
                        Click &quot;Add Link&quot; to get started
                      </p>
                    </div>
                  ) : (
                    links.map((link) => (
                      <SortableLinkItem
                        key={link.id}
                        link={link}
                        onEdit={() => setEditingLink(link)}
                        onDelete={() => handleDeleteLink(link.id)}
                        onMoveUp={() => moveLink(link.id, 'up')}
                        onMoveDown={() => moveLink(link.id, 'down')}
                        isFirst={link.sortOrder === 0}
                        isLast={link.sortOrder === links.length - 1}
                      />
                    ))
                  )}
                </div>
              </SortableContext>
            </DndContext>

            {/* Add Button */}
            <div
              style={{
                marginTop: '24px',
                paddingTop: '24px',
                borderTop: '1px solid rgba(148, 163, 184, 0.15)',
              }}
            >
              <button
                onClick={handleAddLink}
                disabled={links.length >= 10}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  padding: '12px 20px',
                  background: links.length >= 10 ? 'rgba(71, 85, 105, 0.3)' : 'transparent',
                  border:
                    links.length >= 10 ? '1px solid rgba(71, 85, 105, 0.3)' : '1px solid #38bdf8',
                  borderRadius: '8px',
                  color: links.length >= 10 ? 'rgba(148, 163, 184, 0.5)' : '#38bdf8',
                  fontSize: '15px',
                  fontWeight: 600,
                  cursor: links.length >= 10 ? 'not-allowed' : 'pointer',
                  transition: 'background 0.2s ease',
                }}
                onMouseEnter={(e) => {
                  if (links.length < 10) {
                    e.currentTarget.style.background = 'rgba(56, 189, 248, 0.1)';
                  }
                }}
                onMouseLeave={(e) => {
                  if (links.length < 10) {
                    e.currentTarget.style.background = 'transparent';
                  }
                }}
              >
                <Plus size={18} />
                Add Link
              </button>
            </div>
          </div>

          {/* Preview */}
          <LinkPreview links={links} />
        </div>
      </div>

      {/* Edit Modal */}
      {editingLink && (
        <LinkEditModal
          link={editingLink}
          pages={pages}
          onSave={handleSaveEdit}
          onCancel={() => setEditingLink(null)}
        />
      )}
    </div>
  );
}
