import { CheckCircle2 } from 'lucide-react';
import { toast } from 'sonner';


import { useEffect, useState } from 'react';

import { router, useForm } from '@inertiajs/react';

import DiffPreview from '@/Components/Ai/DiffPreview';
import { Alert, AlertDescription, AlertTitle } from '@/Components/ui/alert';
import { Button } from '@/Components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Skeleton } from '@/Components/ui/skeleton';
import { useMilestone } from '@/hooks/useMilestone';
import { trackProductEvent } from '@/lib/analytics';
import { DRAFT_PUBLISHED } from '@/lib/event-catalog';
import { formatNumber } from '@/lib/format';

interface PublishDraftModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  siteId: number;
  draftId: number;
  recommendationId?: number;
  wpPostId: string;
  wpModifiedAt: string | null;
  originalContent: string;
  newContent: string;
  pageUrl?: string;
}

interface ConflictCheckResponse {
  has_conflict: boolean;
  wp_modified_at: string | null;
}

export default function PublishDraftModal({
  open,
  onOpenChange,
  siteId,
  draftId,
  recommendationId,
  wpPostId,
  wpModifiedAt,
  originalContent,
  newContent,
  pageUrl = '',
}: PublishDraftModalProps) {
  const [conflictData, setConflictData] = useState<ConflictCheckResponse | null>(null);
  const [checkingConflict, setCheckingConflict] = useState(false);

  const { celebrate: celebratePublish } = useMilestone('first_draft_published');

  const originalCharCount = originalContent.replace(/<[^>]*>/g, '').length;
  const newCharCount = newContent.replace(/<[^>]*>/g, '').length;
  const charDelta = newCharCount - originalCharCount;
  const charDeltaPercent =
    originalCharCount > 0 ? ((charDelta / originalCharCount) * 100).toFixed(1) : 0;

  const { data, setData, post, processing, errors } = useForm({
    publish_type: 'draft' as 'draft' | 'publish',
    wp_modified_at: wpModifiedAt ?? '',
  });

  // Fetch conflict check when modal opens
  useEffect(() => {
    if (open) {
      setCheckingConflict(true);
      fetch(route('ai-drafts.conflict-check', [siteId, draftId]))
        .then((response) => response.json())
        .then((data: ConflictCheckResponse) => {
          setConflictData(data);
          // Update form data with latest timestamp
          if (data.wp_modified_at) {
            setData('wp_modified_at', data.wp_modified_at);
          }
        })
        .catch(() => {
          // Ignore errors, just don't show conflict warning
          setConflictData({ has_conflict: false, wp_modified_at: wpModifiedAt });
        })
        .finally(() => {
          setCheckingConflict(false);
        });
    } else {
      // Reset state when modal closes
      setConflictData(null);
    }
  }, [open, siteId, draftId, wpModifiedAt, setData]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    post(route('ai-drafts.publish', [siteId, draftId]), {
      onSuccess: () => {
        trackProductEvent(DRAFT_PUBLISHED, {
          site_id: siteId,
          draft_id: draftId,
          publish_type: data.publish_type,
        });
        celebratePublish(
          'First draft published to WordPress!',
          'Your AI-generated content is now live. Track its impact in the ROI dashboard.',
        );
        onOpenChange(false);
        if (recommendationId) {
          toast.success('Draft published.', {
            icon: <CheckCircle2 className="h-5 w-5 text-green-500" />,
            description: 'Mark this recommendation as Applied to start tracking ROI.',
            duration: 10000,
            action: {
              label: 'Mark as Applied',
              onClick: () =>
                router.patch(route('recommendations.update-status', [siteId, recommendationId]), {
                  lifecycle_status: 'applied',
                }),
            },
          });
        } else {
          toast.success('Draft published.', {
            icon: <CheckCircle2 className="h-5 w-5 text-green-500" />,
            description: 'Your AI-generated content is now live.',
            duration: 6000,
          });
        }
      },
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Publish to WordPress</DialogTitle>
          <DialogDescription>
            Review and publish your AI-generated content to WordPress post #{wpPostId}.
          </DialogDescription>
        </DialogHeader>

        <Alert className="border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20">
          <AlertTitle className="text-amber-800 dark:text-amber-200">Data Loss Warning</AlertTitle>
          <AlertDescription className="text-amber-700 dark:text-amber-300 mt-2">
            <p className="mb-2">
              This will overwrite the existing content on <strong>{pageUrl || 'this page'}</strong>.
              A snapshot has been saved for rollback.
            </p>
            <p className="text-sm">
              Character count change: <strong>{formatNumber(originalCharCount)}</strong> →{' '}
              <strong>{formatNumber(newCharCount)}</strong> ({charDelta > 0 ? '+' : ''}
              {formatNumber(charDelta)} chars, {charDeltaPercent}%)
            </p>
          </AlertDescription>
        </Alert>

        {conflictData?.has_conflict && (
          <Alert variant="destructive">
            <AlertTitle>WordPress Content Modified</AlertTitle>
            <AlertDescription>
              The WordPress content has been modified since the last sync. Publishing now will
              overwrite those changes. Please sync your content first to avoid data loss.
            </AlertDescription>
          </Alert>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="publish_type">Publish Type</Label>
            <Select
              value={data.publish_type}
              onValueChange={(val) => setData('publish_type', val as 'draft' | 'publish')}
              disabled={processing}
            >
              <SelectTrigger id="publish_type" aria-invalid={!!errors.publish_type}>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="draft">Save as WordPress Draft (for review)</SelectItem>
                <SelectItem value="publish">Publish Immediately (live)</SelectItem>
              </SelectContent>
            </Select>
            {errors.publish_type && (
              <p id="publish_type-error" className="text-sm text-destructive">
                {errors.publish_type}
              </p>
            )}
          </div>

          <div className="space-y-2">
            <h3 className="text-sm font-medium">Content Preview</h3>
            {checkingConflict ? (
              <div className="space-y-2 py-4">
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-5/6" />
                <Skeleton className="h-4 w-4/6" />
                <Skeleton className="h-32 w-full mt-2" />
              </div>
            ) : (
              <DiffPreview originalContent={originalContent} newContent={newContent} />
            )}
          </div>

          {data.publish_type === 'publish' && (
            <Alert>
              <AlertDescription>
                <strong>Note:</strong> This will immediately publish the content to your live
                WordPress site. Make sure you have reviewed the changes carefully.
              </AlertDescription>
            </Alert>
          )}

          {errors.wp_modified_at && (
            <p className="text-sm text-destructive">{errors.wp_modified_at}</p>
          )}

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={processing}
            >
              Cancel
            </Button>
            <LoadingButton loading={processing} disabled={checkingConflict}>
              {data.publish_type === 'draft' ? 'Save as Draft' : 'Publish Now'}
            </LoadingButton>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
