'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, Plus, Edit, Trash2, Eye, Globe, FileText, Layout } from 'lucide-react';
import { Page } from '@/lib/data-store';

export default function PagesManagePage() {
  const [pages, setPages] = useState<Page[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchPages();
  }, []);

  const fetchPages = async () => {
    try {
      const response = await fetch('/api/admin/pages');
      const data = await response.json();
      if (data.success) {
        setPages(data.data || []);
      }
    } catch (error) {
      console.error('Error fetching pages:', error);
    } finally {
      setLoading(false);
    }
  };

  const deletePage = async (id: string) => {
    if (!confirm('Are you sure you want to delete this page?')) return;
    
    try {
      const response = await fetch(`/api/admin/pages/${id}`, {
        method: 'DELETE',
      });
      const data = await response.json();
      if (data.success) {
        setPages(pages.filter(page => page.id !== id));
      }
    } catch (error) {
      console.error('Error deleting page:', error);
    }
  };

  const getPageIcon = (pageType: string) => {
    switch (pageType) {
      case 'landing': return Globe;
      case 'service': return Layout;
      case 'about': return FileText;
      default: return FileText;
    }
  };

  const getPageBadge = (pageType: string) => {
    switch (pageType) {
      case 'landing': return { color: 'bg-green-500', text: 'Landing' };
      case 'service': return { color: 'bg-blue-500', text: 'Service' };
      case 'about': return { color: 'bg-purple-500', text: 'About' };
      default: return { color: 'bg-gray-500', text: 'Standard' };
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <FileText className="h-12 w-12 text-blue-600 mx-auto mb-4 animate-pulse" />
          <p className="text-gray-600">Loading pages...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center gap-4">
              <Button variant="ghost" size="sm" asChild>
                <Link href="/admin/dashboard">
                  <ArrowLeft className="h-4 w-4 mr-2" />
                  Back to Dashboard
                </Link>
              </Button>
              <div className="border-l border-gray-200 h-6"></div>
              <div className="flex items-center gap-3">
                <FileText className="h-6 w-6 text-blue-600" />
                <h1 className="text-xl font-semibold text-gray-900">Page Management</h1>
              </div>
            </div>
            <Button className="bg-blue-600 hover:bg-blue-700" asChild>
              <Link href="/admin/pages/new">
                <Plus className="h-4 w-4 mr-2" />
                Add New Page
              </Link>
            </Button>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Summary */}
        <div className="mb-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Website Pages</h2>
          <p className="text-gray-600">
            Manage all pages on your website. Add new pages, edit existing content, or delete pages you no longer need.
          </p>
        </div>

        {/* Pages List */}
        {pages.length === 0 ? (
          <Card className="text-center py-12">
            <CardContent>
              <FileText className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-xl font-semibold text-gray-900 mb-2">No Pages Created Yet</h3>
              <p className="text-gray-600 mb-6">
                Start building your website by creating your first custom page.
              </p>
              <Button className="bg-blue-600 hover:bg-blue-700" asChild>
                <Link href="/admin/pages/new">
                  <Plus className="h-4 w-4 mr-2" />
                  Create Your First Page
                </Link>
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {pages.map((page) => {
              const IconComponent = getPageIcon(page.pageType);
              const badge = getPageBadge(page.pageType);
              
              return (
                <Card key={page.id} className="hover:shadow-md transition-shadow">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="bg-blue-100 w-10 h-10 rounded-lg flex items-center justify-center">
                          <IconComponent className="h-5 w-5 text-blue-600" />
                        </div>
                        <div>
                          <Badge className={`${badge.color} text-white text-xs mb-1`}>
                            {badge.text}
                          </Badge>
                        </div>
                      </div>
                      <div className="flex items-center gap-1">
                        {page.isActive && (
                          <Badge variant="outline" className="text-green-600 border-green-600">
                            Live
                          </Badge>
                        )}
                        {page.showInMenu && (
                          <Badge variant="outline" className="text-blue-600 border-blue-600">
                            Menu
                          </Badge>
                        )}
                      </div>
                    </div>
                    <CardTitle className="text-lg">{page.title}</CardTitle>
                    <CardDescription>
                      /{page.slug}
                    </CardDescription>
                  </CardHeader>
                  
                  <CardContent>
                    <div className="space-y-3">
                      <div className="text-sm text-gray-600 line-clamp-2">
                        {page.metaDescription || 'No description provided'}
                      </div>
                      
                      <div className="text-xs text-gray-500">
                        Created: {new Date(page.createdAt).toLocaleDateString()}
                      </div>
                      
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" className="flex-1" asChild>
                          <Link href={`/${page.slug}`} target="_blank">
                            <Eye className="h-3 w-3 mr-1" />
                            View
                          </Link>
                        </Button>
                        
                        <Button size="sm" variant="outline" className="flex-1" asChild>
                          <Link href={`/admin/pages/edit/${page.id}`}>
                            <Edit className="h-3 w-3 mr-1" />
                            Edit
                          </Link>
                        </Button>
                        
                        <Button 
                          size="sm" 
                          variant="outline" 
                          className="text-red-600 hover:text-red-700"
                          onClick={() => deletePage(page.id)}
                        >
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}

        {/* Help Section */}
        <div className="mt-12 bg-blue-50 rounded-lg p-6">
          <div className="flex items-start gap-4">
            <div className="bg-blue-100 p-3 rounded-lg">
              <Layout className="h-6 w-6 text-blue-600" />
            </div>
            <div className="flex-1">
              <h4 className="text-lg font-semibold text-gray-900 mb-2">
                About Page Management
              </h4>
              <p className="text-gray-600 mb-4">
                Create custom pages for your website with rich content, SEO optimization, and menu integration. 
                Each page can be customized with different layouts and purposes.
              </p>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div>
                  <h5 className="font-semibold text-gray-900 mb-2">Page Types:</h5>
                  <ul className="space-y-1 text-gray-600">
                    <li>• <strong>Standard:</strong> Regular content pages</li>
                    <li>• <strong>Landing:</strong> Marketing/campaign pages</li>
                    <li>• <strong>Service:</strong> Service description pages</li>
                    <li>• <strong>About:</strong> Company information pages</li>
                  </ul>
                </div>
                <div>
                  <h5 className="font-semibold text-gray-900 mb-2">Features:</h5>
                  <ul className="space-y-1 text-gray-600">
                    <li>• Rich text content editor</li>
                    <li>• SEO meta tags and descriptions</li>
                    <li>• Custom URL slugs</li>
                    <li>• Menu integration options</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}