/**
 * Step 4: AI Sitemap Review
 * Review and edit AI-generated sitemap
 */
import { useState, useEffect, useCallback } from 'react';
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { 
  PageBlueprint,
  updatePageBlueprint,
  regeneratePageBlueprint,
} from '../../../../services/api';
import { siteBuilderApi } from '../../../../services/siteBuilder.api';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import ButtonWithTooltip from '../../../../components/ui/button/ButtonWithTooltip';
import Button from '../../../../components/ui/button/Button';
import Alert from '../../../../components/ui/alert/Alert';
import Input from '../../../../components/form/input/InputField';
import { useToast } from '../../../../components/ui/toast/ToastContainer';

interface SitemapReviewStepProps {
  blueprintId: number;
}

export default function SitemapReviewStep({ blueprintId }: SitemapReviewStepProps) {
  const { context, completeStep, blockingIssues, refreshContext } = useBuilderWorkflowStore();
  const toast = useToast();
  const [pages, setPages] = useState<PageBlueprint[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editForm, setEditForm] = useState<{ title: string; slug: string; type: string } | null>(null);
  const [regeneratingId, setRegeneratingId] = useState<number | null>(null);
  const sitemapBlocking = blockingIssues.find(issue => issue.step === 'sitemap');

  useEffect(() => {
    loadPages();
  }, [blueprintId]);

  const loadPages = async () => {
    try {
      setLoading(true);
      const pagesList = await siteBuilderApi.listPages(blueprintId);
      setPages(pagesList.sort((a, b) => a.order - b.order));
    } catch (error: any) {
      toast.error(`Failed to load pages: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (page: PageBlueprint) => {
    setEditingId(page.id);
    setEditForm({
      title: page.title,
      slug: page.slug,
      type: page.type,
    });
  };

  const handleSaveEdit = async (pageId: number) => {
    if (!editForm) return;
    
    try {
      await updatePageBlueprint(pageId, {
        title: editForm.title,
        slug: editForm.slug,
        type: editForm.type,
      });
      toast.success('Page updated successfully');
      setEditingId(null);
      setEditForm(null);
      await loadPages();
      await refreshContext();
    } catch (error: any) {
      toast.error(`Failed to update page: ${error.message}`);
    }
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setEditForm(null);
  };

  const handleRegenerate = async (pageId: number) => {
    try {
      setRegeneratingId(pageId);
      await regeneratePageBlueprint(pageId);
      toast.success('Page regeneration started');
      await loadPages();
      await refreshContext();
    } catch (error: any) {
      toast.error(`Failed to regenerate page: ${error.message}`);
    } finally {
      setRegeneratingId(null);
    }
  };

  const getStatusBadge = (status: string) => {
    const variants: Record<string, string> = {
      draft: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200',
      pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
      generating: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
      ready: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
      published: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
    };
    return variants[status] || variants.draft;
  };

  const getTypeBadge = (type: string) => {
    const variants: Record<string, string> = {
      homepage: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
      landing: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
      blog: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
      product: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',
      category: 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200',
      about: 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200',
    };
    return variants[type] || 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';
  };

  return (
    <Card className="p-6">
      <CardTitle>AI Sitemap Review</CardTitle>
      <CardDescription>
        Review and adjust the AI-generated site structure. Edit page details or regenerate pages as needed.
      </CardDescription>

      {sitemapBlocking && (
        <Alert variant="error" className="mt-4">
          {sitemapBlocking.message}
        </Alert>
      )}

      {context?.sitemap_summary && (
        <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
          <div className="grid grid-cols-3 gap-4 text-sm">
            <div>
              <span className="text-gray-600 dark:text-gray-400">Total Pages:</span>
              <span className="ml-2 font-semibold">{context.sitemap_summary.pages_total || 0}</span>
            </div>
            <div>
              <span className="text-gray-600 dark:text-gray-400">By Status:</span>
              <div className="mt-1 flex flex-wrap gap-2">
                {Object.entries(context.sitemap_summary.pages_by_status || {}).map(([status, count]) => (
                  <span key={status} className="text-xs px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded">
                    {status}: {count}
                  </span>
                ))}
              </div>
            </div>
            <div>
              <span className="text-gray-600 dark:text-gray-400">By Type:</span>
              <div className="mt-1 flex flex-wrap gap-2">
                {Object.entries(context.sitemap_summary.pages_by_type || {}).map(([type, count]) => (
                  <span key={type} className="text-xs px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded">
                    {type}: {count}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {loading ? (
        <div className="mt-6 text-center py-8 text-gray-500">Loading pages...</div>
      ) : pages.length === 0 ? (
        <Alert variant="info" className="mt-6">
          No pages found. Generate a sitemap first.
        </Alert>
      ) : (
        <div className="mt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {pages.map((page) => (
              <div
                key={page.id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow"
              >
                {editingId === page.id ? (
                  <div className="space-y-3">
                    <Input
                      label="Title"
                      value={editForm?.title || ''}
                      onChange={(e) => setEditForm({ ...editForm!, title: e.target.value })}
                      placeholder="Page title"
                    />
                    <Input
                      label="Slug"
                      value={editForm?.slug || ''}
                      onChange={(e) => setEditForm({ ...editForm!, slug: e.target.value })}
                      placeholder="page-slug"
                    />
                    <Input
                      label="Type"
                      value={editForm?.type || ''}
                      onChange={(e) => setEditForm({ ...editForm!, type: e.target.value })}
                      placeholder="homepage, landing, blog, etc."
                    />
                    <div className="flex gap-2">
                      <Button
                        onClick={() => handleSaveEdit(page.id)}
                        variant="primary"
                        size="sm"
                      >
                        Save
                      </Button>
                      <Button
                        onClick={handleCancelEdit}
                        variant="secondary"
                        size="sm"
                      >
                        Cancel
                      </Button>
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="flex items-start justify-between mb-2">
                      <h4 className="font-semibold text-lg">{page.title}</h4>
                      <div className="flex gap-1">
                        <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(page.status)}`}>
                          {page.status}
                        </span>
                        <span className={`text-xs px-2 py-1 rounded ${getTypeBadge(page.type)}`}>
                          {page.type}
                        </span>
                      </div>
                    </div>
                    <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
                      /{page.slug}
                    </p>
                    <div className="flex gap-2">
                      <Button
                        onClick={() => handleEdit(page)}
                        variant="secondary"
                        size="sm"
                      >
                        Edit
                      </Button>
                      <Button
                        onClick={() => handleRegenerate(page.id)}
                        variant="secondary"
                        size="sm"
                        disabled={regeneratingId === page.id}
                      >
                        {regeneratingId === page.id ? 'Regenerating...' : 'Regenerate'}
                      </Button>
                    </div>
                  </>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="mt-6 flex justify-end">
        <ButtonWithTooltip
          onClick={() => completeStep('sitemap')}
          disabled={!!sitemapBlocking}
          variant="primary"
          tooltip={sitemapBlocking?.message}
        >
          Continue
        </ButtonWithTooltip>
      </div>
    </Card>
  );
}
