import { useEffect, useState } from 'react';

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

import SnapshotDiff from '@/Components/ContentHistory/SnapshotDiff';
import DataCard from '@/Components/Shared/DataCard';
import { Alert, AlertDescription } 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 { Textarea } from '@/Components/ui/textarea';
import { formatDateTime, formatNumber } from '@/lib/format';

interface ContentSnapshot {
  id: number;
  title: string;
  content: string;
  meta_description: string | null;
  wp_modified_at: string;
  created_at: string;
}

interface GscMetrics {
  clicks: number;
  impressions: number;
  ctr: number;
  position: number;
}

interface RollbackConfirmModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  siteId: number;
  snapshotId: number;
  currentSnapshot: ContentSnapshot;
  targetSnapshot: ContentSnapshot;
  currentMetrics?: GscMetrics | null;
}

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

export default function RollbackConfirmModal({
  open,
  onOpenChange,
  siteId,
  snapshotId,
  currentSnapshot,
  targetSnapshot,
  currentMetrics,
}: RollbackConfirmModalProps) {
  const [conflictData, setConflictData] = useState<ConflictCheckResponse | null>(null);
  const [checkingConflict, setCheckingConflict] = useState(false);

  const { data, setData, post, processing, errors, reset } = useForm({
    reason: '',
  });

  // Fetch conflict check when modal opens
  useEffect(() => {
    if (open) {
      setCheckingConflict(true);
      fetch(route('snapshots.conflict-check', [siteId, snapshotId]))
        .then((response) => response.json())
        .then((data: ConflictCheckResponse) => {
          setConflictData(data);
        })
        .catch(() => {
          // Ignore errors, just don't show conflict warning
          setConflictData({
            has_conflict: false,
            wp_modified_at: currentSnapshot.wp_modified_at,
            snapshot_modified_at: targetSnapshot.wp_modified_at,
          });
        })
        .finally(() => {
          setCheckingConflict(false);
        });
    } else {
      // Reset state when modal closes
      setConflictData(null);
      reset();
    }
  }, [
    open,
    siteId,
    snapshotId,
    currentSnapshot.wp_modified_at,
    targetSnapshot.wp_modified_at,
    reset,
  ]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    post(route('snapshots.rollback', [siteId, snapshotId]), {
      onSuccess: () => {
        onOpenChange(false);
      },
    });
  };

  const formatPercent = (n: number): string => {
    return `${(n * 100).toFixed(1)}%`;
  };

  const formatDecimal = (n: number): string => {
    return n.toFixed(1);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Confirm Content Rollback</DialogTitle>
          <DialogDescription>
            Review the changes and provide a reason for rolling back to the previous version.
          </DialogDescription>
        </DialogHeader>

        {conflictData?.has_conflict && (
          <Alert variant="destructive">
            <AlertDescription>
              <strong>Warning:</strong> The WordPress content has been modified since this snapshot
              was taken. Rolling back will overwrite those changes. Please sync your content first
              to avoid data loss.
            </AlertDescription>
          </Alert>
        )}

        <form onSubmit={handleSubmit} className="space-y-6">
          {currentMetrics && (
            <div className="space-y-2">
              <h3 className="text-sm font-medium">Current Performance (GSC Metrics)</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <DataCard title="Clicks" value={formatNumber(currentMetrics.clicks)} />
                <DataCard title="Impressions" value={formatNumber(currentMetrics.impressions)} />
                <DataCard title="Avg CTR" value={formatPercent(currentMetrics.ctr)} />
                <DataCard title="Avg Position" value={formatDecimal(currentMetrics.position)} />
              </div>
            </div>
          )}

          <div className="space-y-2">
            <h3 className="text-sm font-medium">Content Changes</h3>
            {checkingConflict ? (
              <div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
                Checking for conflicts...
              </div>
            ) : (
              <SnapshotDiff beforeSnapshot={targetSnapshot} afterSnapshot={currentSnapshot} />
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="reason">Reason for Rollback *</Label>
            <Textarea
              id="reason"
              value={data.reason}
              onChange={(e) => setData('reason', e.target.value)}
              placeholder="e.g., Content update hurt traffic, contains errors, not performing as expected..."
              rows={3}
              disabled={processing}
              className={errors.reason ? 'border-destructive' : ''}
            />
            {errors.reason && <p className="text-sm text-destructive">{errors.reason}</p>}
            <p className="text-xs text-muted-foreground">
              Provide a clear explanation for why you're rolling back this content. This will be
              logged for audit purposes.
            </p>
          </div>

          <Alert>
            <AlertDescription>
              <strong>Note:</strong> This will revert the WordPress post to the state captured on{' '}
              {formatDateTime(targetSnapshot.created_at)}. The rollback will be processed via the
              WordPress API and may take a few moments to complete.
            </AlertDescription>
          </Alert>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={processing}
            >
              Cancel
            </Button>
            <LoadingButton
              loading={processing}
              disabled={checkingConflict || !data.reason.trim()}
              variant="destructive"
            >
              Confirm Rollback
            </LoadingButton>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
