import React, { useState, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from './ui/dialog';
import { Button } from './ui/button';
import { Card } from './ui/card';
import { Label } from './ui/label';
import { Checkbox } from './ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from './ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from './ui/table';
import {
  Upload,
  FileSpreadsheet,
  Users,
  CreditCard,
  Receipt,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Loader2,
  ChevronLeft,
  ChevronRight,
  Download,
  RotateCcw,
  Mail,
  MailX,
  Info,
} from 'lucide-react';
import { toast } from 'sonner';
import api from '../utils/api';

const STEPS = [
  { id: 'upload', title: 'Upload Files', icon: Upload },
  { id: 'preview', title: 'Preview Data', icon: FileSpreadsheet },
  { id: 'options', title: 'Import Options', icon: Users },
  { id: 'execute', title: 'Execute Import', icon: CheckCircle2 },
];

const STATUS_COLORS = {
  active: 'bg-green-100 text-green-800',
  pre_validated: 'bg-blue-100 text-blue-800',
  payment_pending: 'bg-yellow-100 text-yellow-800',
  pending_validation: 'bg-purple-100 text-purple-800',
  inactive: 'bg-gray-100 text-gray-800',
  expired: 'bg-red-100 text-red-800',
};

const ROLE_COLORS = {
  superadmin: 'bg-red-100 text-red-800',
  admin: 'bg-orange-100 text-orange-800',
  finance: 'bg-blue-100 text-blue-800',
  member: 'bg-green-100 text-green-800',
  guest: 'bg-gray-100 text-gray-800',
};

/**
 * ComprehensiveImportWizard - Multi-file WordPress import wizard
 *
 * Supports importing:
 * - WordPress Users CSV (required)
 * - PMS Members CSV (optional) - subscription data
 * - PMS Payments CSV (optional) - payment history
 */
const ComprehensiveImportWizard = ({ open, onOpenChange, onSuccess }) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [importJobId, setImportJobId] = useState(null);

  // File upload state
  const [usersFile, setUsersFile] = useState(null);
  const [membersFile, setMembersFile] = useState(null);
  const [paymentsFile, setPaymentsFile] = useState(null);

  // Preview state
  const [uploadSummary, setUploadSummary] = useState(null);
  const [previewData, setPreviewData] = useState([]);
  const [previewPage, setPreviewPage] = useState(1);
  const [previewTotalPages, setPreviewTotalPages] = useState(1);
  const [filterErrors, setFilterErrors] = useState(false);
  const [filterWarnings, setFilterWarnings] = useState(false);

  // Override state
  const [overrides, setOverrides] = useState({});

  // Import options
  const [options, setOptions] = useState({
    skip_notifications: true,
    send_welcome_emails: false,
    send_password_emails: false,
    import_subscriptions: true,
    import_payment_history: true,
    skip_errors: true,
  });

  // Results state
  const [importResults, setImportResults] = useState(null);

  // Reset wizard state
  const resetWizard = useCallback(() => {
    setCurrentStep(0);
    setLoading(false);
    setImportJobId(null);
    setUsersFile(null);
    setMembersFile(null);
    setPaymentsFile(null);
    setUploadSummary(null);
    setPreviewData([]);
    setPreviewPage(1);
    setPreviewTotalPages(1);
    setFilterErrors(false);
    setFilterWarnings(false);
    setOverrides({});
    setOptions({
      skip_notifications: true,
      send_welcome_emails: false,
      send_password_emails: false,
      import_subscriptions: true,
      import_payment_history: true,
      skip_errors: true,
    });
    setImportResults(null);
  }, []);

  // Handle dialog close
  const handleClose = () => {
    if (loading) return;
    resetWizard();
    onOpenChange(false);
  };

  // Step 1: Upload files
  const handleUpload = async () => {
    if (!usersFile) {
      toast.error('Please select a WordPress Users CSV file');
      return;
    }

    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('users_file', usersFile);
      if (membersFile) {
        formData.append('members_file', membersFile);
      }
      if (paymentsFile) {
        formData.append('payments_file', paymentsFile);
      }

      const response = await api.post('/admin/import/comprehensive/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        timeout: 120000, // 2 minutes for large file uploads + R2 storage
      });

      setImportJobId(response.data.import_job_id);
      setUploadSummary(response.data);

      // Fetch preview data
      await fetchPreview(response.data.import_job_id, 1);

      toast.success('Files uploaded and analyzed successfully');
      setCurrentStep(1);
    } catch (error) {
      console.error('[ComprehensiveImport] Upload failed:', error);
      const message = error.response?.data?.detail ||
                      error.message ||
                      'Failed to upload files';
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  // Fetch preview data
  const fetchPreview = async (jobId, page) => {
    try {
      const response = await api.get(`/admin/import/comprehensive/${jobId}/preview`, {
        params: {
          page,
          page_size: 20,
          filter_errors: filterErrors,
          filter_warnings: filterWarnings,
        },
      });

      setPreviewData(response.data.rows);
      setPreviewPage(response.data.page);
      setPreviewTotalPages(response.data.total_pages);
    } catch (error) {
      toast.error('Failed to load preview data');
    }
  };

  // Handle page change
  const handlePageChange = async (newPage) => {
    if (newPage < 1 || newPage > previewTotalPages) return;
    setLoading(true);
    await fetchPreview(importJobId, newPage);
    setLoading(false);
  };

  // Handle filter change
  const handleFilterChange = async () => {
    if (!importJobId) return;
    setLoading(true);
    await fetchPreview(importJobId, 1);
    setLoading(false);
  };

  // Handle override change
  const handleOverride = (rowNum, field, value) => {
    setOverrides((prev) => ({
      ...prev,
      [rowNum]: {
        ...prev[rowNum],
        [field]: value,
      },
    }));
  };

  // Execute import
  const handleExecute = async () => {
    if (!importJobId) return;

    setLoading(true);
    try {
      const response = await api.post(`/admin/import/comprehensive/${importJobId}/execute`, {
        overrides,
        options,
      });

      setImportResults(response.data);
      toast.success(
        `Import completed: ${response.data.successful_rows} users imported`
      );
      setCurrentStep(3);
    } catch (error) {
      const message = error.response?.data?.detail || 'Import failed';
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  // Render step content
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return renderUploadStep();
      case 1:
        return renderPreviewStep();
      case 2:
        return renderOptionsStep();
      case 3:
        return renderResultsStep();
      default:
        return null;
    }
  };

  // Step 1: Upload
  const renderUploadStep = () => (
    <div className="space-y-6">
      <div className="text-center mb-6">
        <p
          className="text-brand-purple/70"
          style={{ fontFamily: "'Nunito Sans', sans-serif" }}
        >
          Upload your WordPress export CSV files. The Users file is required,
          while Members and Payments files are optional but recommended for
          complete data migration.
        </p>
      </div>

      {/* Users File (Required) */}
      <Card className="p-4 border-2 border-dashed border-brand-purple/30 hover:border-brand-purple/60 transition-colors">
        <div className="flex items-start gap-4">
          <div className="p-3 rounded-full bg-brand-purple/10">
            <Users className="h-6 w-6 text-brand-purple" />
          </div>
          <div className="flex-1">
            <Label
              className="text-brand-purple font-semibold"
              style={{ fontFamily: "'Inter', sans-serif" }}
            >
              WordPress Users CSV{' '}
              <span className="text-red-500">*Required</span>
            </Label>
            <p
              className="text-sm text-brand-purple/70 mb-3"
              style={{ fontFamily: "'Nunito Sans', sans-serif" }}
            >
              User profiles, contact info, directory settings, newsletter
              preferences
            </p>
            <input
              type="file"
              accept=".csv"
              onChange={(e) => setUsersFile(e.target.files[0])}
              className="block w-full text-sm text-brand-purple file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-brand-purple file:text-white hover:file:bg-[var(--purple-ink)] cursor-pointer"
            />
            {usersFile && (
              <p className="text-sm text-green-600 mt-2 flex items-center gap-1">
                <CheckCircle2 className="h-4 w-4" />
                {usersFile.name}
              </p>
            )}
          </div>
        </div>
      </Card>

      {/* Members File (Optional) */}
      <Card className="p-4 border-2 border-dashed border-[var(--lavender-500)] hover:border-brand-purple/60 transition-colors">
        <div className="flex items-start gap-4">
          <div className="p-3 rounded-full bg-[var(--lavender-300)]">
            <CreditCard className="h-6 w-6 text-brand-purple" />
          </div>
          <div className="flex-1">
            <Label
              className="text-brand-purple font-semibold"
              style={{ fontFamily: "'Inter', sans-serif" }}
            >
              PMS Members CSV{' '}
              <span className="text-brand-purple/50">Optional</span>
            </Label>
            <p
              className="text-sm text-brand-purple/70 mb-3"
              style={{ fontFamily: "'Nunito Sans', sans-serif" }}
            >
              Subscription plans, start/end dates, membership status
            </p>
            <input
              type="file"
              accept=".csv"
              onChange={(e) => setMembersFile(e.target.files[0])}
              className="block w-full text-sm text-brand-purple file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-[var(--lavender-500)] file:text-brand-purple hover:file:bg-[var(--lavender-300)] cursor-pointer"
            />
            {membersFile && (
              <p className="text-sm text-green-600 mt-2 flex items-center gap-1">
                <CheckCircle2 className="h-4 w-4" />
                {membersFile.name}
              </p>
            )}
          </div>
        </div>
      </Card>

      {/* Payments File (Optional) */}
      <Card className="p-4 border-2 border-dashed border-[var(--lavender-500)] hover:border-brand-purple/60 transition-colors">
        <div className="flex items-start gap-4">
          <div className="p-3 rounded-full bg-[var(--lavender-300)]">
            <Receipt className="h-6 w-6 text-brand-purple" />
          </div>
          <div className="flex-1">
            <Label
              className="text-brand-purple font-semibold"
              style={{ fontFamily: "'Inter', sans-serif" }}
            >
              PMS Payments CSV{' '}
              <span className="text-brand-purple/50">Optional</span>
            </Label>
            <p
              className="text-sm text-brand-purple/70 mb-3"
              style={{ fontFamily: "'Nunito Sans', sans-serif" }}
            >
              Payment history, transaction records, amounts paid
            </p>
            <input
              type="file"
              accept=".csv"
              onChange={(e) => setPaymentsFile(e.target.files[0])}
              className="block w-full text-sm text-brand-purple file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-[var(--lavender-500)] file:text-brand-purple hover:file:bg-[var(--lavender-300)] cursor-pointer"
            />
            {paymentsFile && (
              <p className="text-sm text-green-600 mt-2 flex items-center gap-1">
                <CheckCircle2 className="h-4 w-4" />
                {paymentsFile.name}
              </p>
            )}
          </div>
        </div>
      </Card>
    </div>
  );

  // Step 2: Preview
  const renderPreviewStep = () => (
    <div className="space-y-4">
      {/* Summary Cards */}
      {uploadSummary && (
        <div className="grid grid-cols-3 gap-4 mb-4">
          <Card className="p-4 bg-[var(--lavender-500)]">
            <div className="flex items-center gap-2 mb-2">
              <Users className="h-5 w-5 text-brand-purple" />
              <span
                className="font-semibold text-brand-purple"
                style={{ fontFamily: "'Inter', sans-serif" }}
              >
                Users
              </span>
            </div>
            <div className="text-2xl font-bold text-brand-purple">
              {uploadSummary.users?.valid || 0}
              <span className="text-sm font-normal text-brand-purple/70">
                {' '}
                / {uploadSummary.users?.total || 0}
              </span>
            </div>
            <p className="text-xs text-brand-purple/70">
              {uploadSummary.users?.warnings || 0} warnings,{' '}
              {uploadSummary.users?.errors || 0} errors
            </p>
          </Card>

          <Card className="p-4 bg-[var(--lavender-500)]">
            <div className="flex items-center gap-2 mb-2">
              <CreditCard className="h-5 w-5 text-brand-purple" />
              <span
                className="font-semibold text-brand-purple"
                style={{ fontFamily: "'Inter', sans-serif" }}
              >
                Subscriptions
              </span>
            </div>
            <div className="text-2xl font-bold text-brand-purple">
              {uploadSummary.members?.matched || 0}
              <span className="text-sm font-normal text-brand-purple/70">
                {' '}
                / {uploadSummary.members?.total || 0}
              </span>
            </div>
            <p className="text-xs text-brand-purple/70">
              {uploadSummary.members?.unmatched || 0} unmatched
            </p>
          </Card>

          <Card className="p-4 bg-[var(--lavender-500)]">
            <div className="flex items-center gap-2 mb-2">
              <Receipt className="h-5 w-5 text-brand-purple" />
              <span
                className="font-semibold text-brand-purple"
                style={{ fontFamily: "'Inter', sans-serif" }}
              >
                Payments
              </span>
            </div>
            <div className="text-2xl font-bold text-brand-purple">
              {uploadSummary.payments?.matched || 0}
            </div>
            <p className="text-xs text-brand-purple/70">
              $
              {(
                (uploadSummary.payments?.total_amount_cents || 0) / 100
              ).toLocaleString()}{' '}
              total
            </p>
          </Card>
        </div>
      )}

      {/* Filters */}
      <div className="flex items-center gap-4 mb-4">
        <div className="flex items-center gap-2">
          <Checkbox
            id="filter-errors"
            checked={filterErrors}
            onCheckedChange={(checked) => {
              setFilterErrors(checked);
              setTimeout(handleFilterChange, 0);
            }}
          />
          <Label
            htmlFor="filter-errors"
            className="text-sm text-brand-purple cursor-pointer"
          >
            Show only errors
          </Label>
        </div>
        <div className="flex items-center gap-2">
          <Checkbox
            id="filter-warnings"
            checked={filterWarnings}
            onCheckedChange={(checked) => {
              setFilterWarnings(checked);
              setTimeout(handleFilterChange, 0);
            }}
          />
          <Label
            htmlFor="filter-warnings"
            className="text-sm text-brand-purple cursor-pointer"
          >
            Show only warnings
          </Label>
        </div>
      </div>

      {/* Preview Table */}
      <div className="border rounded-xl overflow-hidden max-h-[400px] overflow-y-auto">
        <Table>
          <TableHeader className="bg-[var(--lavender-500)] sticky top-0">
            <TableRow>
              <TableHead className="text-brand-purple font-semibold">
                Row
              </TableHead>
              <TableHead className="text-brand-purple font-semibold">
                Email
              </TableHead>
              <TableHead className="text-brand-purple font-semibold">
                Name
              </TableHead>
              <TableHead className="text-brand-purple font-semibold">
                Role
              </TableHead>
              <TableHead className="text-brand-purple font-semibold">
                Status
              </TableHead>
              <TableHead className="text-brand-purple font-semibold">
                Subscription
              </TableHead>
              <TableHead className="text-brand-purple font-semibold">
                Issues
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {previewData.map((row) => (
              <TableRow
                key={row.row_number}
                className={
                  row.errors?.length > 0
                    ? 'bg-red-50'
                    : row.warnings?.length > 0
                    ? 'bg-yellow-50'
                    : ''
                }
              >
                <TableCell className="font-mono text-sm">
                  {row.row_number}
                </TableCell>
                <TableCell className="text-sm">{row.email}</TableCell>
                <TableCell className="text-sm">
                  {row.first_name} {row.last_name}
                </TableCell>
                <TableCell>
                  <Select
                    value={overrides[row.row_number]?.role || row.suggested_role}
                    onValueChange={(value) =>
                      handleOverride(row.row_number, 'role', value)
                    }
                  >
                    <SelectTrigger className="w-28 h-7 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="superadmin">Superadmin</SelectItem>
                      <SelectItem value="admin">Admin</SelectItem>
                      <SelectItem value="finance">Finance</SelectItem>
                      <SelectItem value="member">Member</SelectItem>
                      <SelectItem value="guest">Guest</SelectItem>
                    </SelectContent>
                  </Select>
                </TableCell>
                <TableCell>
                  <Select
                    value={
                      overrides[row.row_number]?.status || row.suggested_status
                    }
                    onValueChange={(value) =>
                      handleOverride(row.row_number, 'status', value)
                    }
                  >
                    <SelectTrigger className="w-32 h-7 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="pre_validated">Pre-validated</SelectItem>
                      <SelectItem value="payment_pending">Payment Pending</SelectItem>
                      <SelectItem value="pending_validation">
                        Pending Validation
                      </SelectItem>
                      <SelectItem value="inactive">Inactive</SelectItem>
                    </SelectContent>
                  </Select>
                </TableCell>
                <TableCell>
                  {row.has_subscription ? (
                    <span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">
                      Yes
                    </span>
                  ) : (
                    <span className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-full">
                      No
                    </span>
                  )}
                </TableCell>
                <TableCell>
                  <div className="flex items-center gap-1">
                    {row.errors?.length > 0 && (
                      <span
                        className="text-red-500 cursor-help"
                        title={row.errors.join(', ')}
                      >
                        <XCircle className="h-4 w-4" />
                      </span>
                    )}
                    {row.warnings?.length > 0 && (
                      <span
                        className="text-yellow-500 cursor-help"
                        title={row.warnings.join(', ')}
                      >
                        <AlertTriangle className="h-4 w-4" />
                      </span>
                    )}
                    {!row.errors?.length && !row.warnings?.length && (
                      <CheckCircle2 className="h-4 w-4 text-green-500" />
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-brand-purple/70">
          Page {previewPage} of {previewTotalPages}
        </p>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(previewPage - 1)}
            disabled={previewPage <= 1 || loading}
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => handlePageChange(previewPage + 1)}
            disabled={previewPage >= previewTotalPages || loading}
          >
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  );

  // Step 3: Options
  const renderOptionsStep = () => (
    <div className="space-y-6">
      {/* Notification Options */}
      <Card className="p-6">
        <h3
          className="font-semibold text-brand-purple mb-4 flex items-center gap-2"
          style={{ fontFamily: "'Inter', sans-serif" }}
        >
          <Mail className="h-5 w-5" />
          Email Notifications
        </h3>

        <div className="space-y-4">
          <div className="flex items-start gap-3 p-4 bg-yellow-50 border border-yellow-200 rounded-xl">
            <Checkbox
              id="skip-notifications"
              checked={options.skip_notifications}
              onCheckedChange={(checked) =>
                setOptions((prev) => ({
                  ...prev,
                  skip_notifications: checked,
                  send_welcome_emails: checked ? false : prev.send_welcome_emails,
                  send_password_emails: checked
                    ? false
                    : prev.send_password_emails,
                }))
              }
            />
            <div>
              <Label
                htmlFor="skip-notifications"
                className="font-semibold text-yellow-800 cursor-pointer"
              >
                <MailX className="h-4 w-4 inline mr-1" />
                Skip all email notifications (Recommended)
              </Label>
              <p className="text-sm text-yellow-700 mt-1">
                No emails will be sent to imported users. You can send a bulk
                password reset later from the admin panel.
              </p>
            </div>
          </div>

          {!options.skip_notifications && (
            <>
              <div className="flex items-center gap-3 p-3 border rounded-lg">
                <Checkbox
                  id="send-welcome"
                  checked={options.send_welcome_emails}
                  onCheckedChange={(checked) =>
                    setOptions((prev) => ({
                      ...prev,
                      send_welcome_emails: checked,
                    }))
                  }
                />
                <Label htmlFor="send-welcome" className="cursor-pointer">
                  Send welcome emails to imported users
                </Label>
              </div>

              <div className="flex items-center gap-3 p-3 border rounded-lg">
                <Checkbox
                  id="send-password"
                  checked={options.send_password_emails}
                  onCheckedChange={(checked) =>
                    setOptions((prev) => ({
                      ...prev,
                      send_password_emails: checked,
                    }))
                  }
                />
                <Label htmlFor="send-password" className="cursor-pointer">
                  Send password reset emails to imported users
                </Label>
              </div>
            </>
          )}
        </div>
      </Card>

      {/* Data Import Options */}
      <Card className="p-6">
        <h3
          className="font-semibold text-brand-purple mb-4 flex items-center gap-2"
          style={{ fontFamily: "'Inter', sans-serif" }}
        >
          <FileSpreadsheet className="h-5 w-5" />
          Data Import Options
        </h3>

        <div className="space-y-4">
          <div className="flex items-center gap-3 p-3 border rounded-lg">
            <Checkbox
              id="import-subscriptions"
              checked={options.import_subscriptions}
              onCheckedChange={(checked) =>
                setOptions((prev) => ({
                  ...prev,
                  import_subscriptions: checked,
                }))
              }
            />
            <div>
              <Label htmlFor="import-subscriptions" className="cursor-pointer">
                Import subscription records
              </Label>
              <p className="text-sm text-brand-purple/70">
                Create subscription records from Members CSV data
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3 p-3 border rounded-lg">
            <Checkbox
              id="import-payments"
              checked={options.import_payment_history}
              onCheckedChange={(checked) =>
                setOptions((prev) => ({
                  ...prev,
                  import_payment_history: checked,
                }))
              }
            />
            <div>
              <Label htmlFor="import-payments" className="cursor-pointer">
                Import payment history
              </Label>
              <p className="text-sm text-brand-purple/70">
                Include payment history from Payments CSV in subscription notes
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3 p-3 border rounded-lg">
            <Checkbox
              id="skip-errors"
              checked={options.skip_errors}
              onCheckedChange={(checked) =>
                setOptions((prev) => ({
                  ...prev,
                  skip_errors: checked,
                }))
              }
            />
            <div>
              <Label htmlFor="skip-errors" className="cursor-pointer">
                Continue on errors
              </Label>
              <p className="text-sm text-brand-purple/70">
                Skip rows with errors and continue importing valid rows
              </p>
            </div>
          </div>
        </div>
      </Card>

      {/* Summary */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <div className="flex items-start gap-2">
          <Info className="h-5 w-5 text-blue-600 mt-0.5" />
          <div>
            <p className="font-semibold text-blue-800">Import Summary</p>
            <p className="text-sm text-blue-700">
              Ready to import {uploadSummary?.users?.valid || 0} users
              {options.import_subscriptions &&
                uploadSummary?.members?.matched > 0 &&
                ` with ${uploadSummary.members.matched} subscriptions`}
              . All imported users will have{' '}
              <code className="bg-blue-100 px-1 rounded">
                force_password_change
              </code>{' '}
              enabled.
            </p>
          </div>
        </div>
      </Card>
    </div>
  );

  // Step 4: Results
  const renderResultsStep = () => (
    <div className="space-y-6">
      {importResults && (
        <>
          {/* Success Banner */}
          <div
            className={`p-6 rounded-xl text-center ${
              importResults.failed_rows === 0
                ? 'bg-green-50 border border-green-200'
                : 'bg-yellow-50 border border-yellow-200'
            }`}
          >
            {importResults.failed_rows === 0 ? (
              <CheckCircle2 className="h-12 w-12 text-green-500 mx-auto mb-3" />
            ) : (
              <AlertTriangle className="h-12 w-12 text-yellow-500 mx-auto mb-3" />
            )}
            <h3
              className={`text-xl font-bold ${
                importResults.failed_rows === 0
                  ? 'text-green-800'
                  : 'text-yellow-800'
              }`}
              style={{ fontFamily: "'Inter', sans-serif" }}
            >
              {importResults.failed_rows === 0
                ? 'Import Completed Successfully!'
                : 'Import Completed with Some Errors'}
            </h3>
          </div>

          {/* Results Grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <Card className="p-4 text-center">
              <p className="text-3xl font-bold text-green-600">
                {importResults.successful_rows}
              </p>
              <p className="text-sm text-brand-purple/70">Users Imported</p>
            </Card>
            <Card className="p-4 text-center">
              <p className="text-3xl font-bold text-red-600">
                {importResults.failed_rows}
              </p>
              <p className="text-sm text-brand-purple/70">Failed</p>
            </Card>
            <Card className="p-4 text-center">
              <p className="text-3xl font-bold text-blue-600">
                {importResults.created_subscriptions}
              </p>
              <p className="text-sm text-brand-purple/70">Subscriptions</p>
            </Card>
            <Card className="p-4 text-center">
              <p className="text-3xl font-bold text-purple-600">
                {importResults.emails_sent}
              </p>
              <p className="text-sm text-brand-purple/70">Emails Sent</p>
            </Card>
          </div>

          {/* Error List */}
          {importResults.errors?.length > 0 && (
            <Card className="p-4">
              <h4
                className="font-semibold text-red-600 mb-3"
                style={{ fontFamily: "'Inter', sans-serif" }}
              >
                Import Errors ({importResults.errors.length})
              </h4>
              <div className="max-h-48 overflow-y-auto space-y-2">
                {importResults.errors.slice(0, 20).map((error, idx) => (
                  <div
                    key={idx}
                    className="text-sm p-2 bg-red-50 rounded border border-red-100"
                  >
                    <span className="font-mono text-red-800">
                      Row {error.row}:
                    </span>{' '}
                    <span className="text-red-600">{error.error}</span>
                    {error.email && (
                      <span className="text-red-500 ml-2">({error.email})</span>
                    )}
                  </div>
                ))}
                {importResults.errors.length > 20 && (
                  <p className="text-sm text-red-500 text-center">
                    ...and {importResults.errors.length - 20} more errors
                  </p>
                )}
              </div>
            </Card>
          )}

          {/* Next Steps */}
          <Card className="p-4 bg-[var(--lavender-500)]">
            <h4
              className="font-semibold text-brand-purple mb-2"
              style={{ fontFamily: "'Inter', sans-serif" }}
            >
              Next Steps
            </h4>
            <ul className="text-sm text-brand-purple/80 space-y-1 list-disc list-inside">
              <li>
                Review imported users in the Members management page
              </li>
              {options.skip_notifications && (
                <li>
                  Send bulk password reset emails when ready
                </li>
              )}
              <li>
                Use the Import Jobs page to rollback if needed
              </li>
            </ul>
          </Card>
        </>
      )}
    </div>
  );

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle
            className="text-xl text-brand-purple"
            style={{ fontFamily: "'Inter', sans-serif" }}
          >
            WordPress Import Wizard
          </DialogTitle>
          <DialogDescription>
            Import users, subscriptions, and payment history from WordPress
          </DialogDescription>
        </DialogHeader>

        {/* Step Indicator */}
        <div className="flex items-center justify-between mb-6 px-4">
          {STEPS.map((step, idx) => {
            const StepIcon = step.icon;
            const isActive = idx === currentStep;
            const isCompleted = idx < currentStep;

            return (
              <React.Fragment key={step.id}>
                <div className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center ${
                      isCompleted
                        ? 'bg-green-500 text-white'
                        : isActive
                        ? 'bg-brand-purple text-white'
                        : 'bg-[var(--lavender-300)] text-brand-purple/50'
                    }`}
                  >
                    {isCompleted ? (
                      <CheckCircle2 className="h-5 w-5" />
                    ) : (
                      <StepIcon className="h-5 w-5" />
                    )}
                  </div>
                  <span
                    className={`text-xs mt-1 ${
                      isActive
                        ? 'text-brand-purple font-semibold'
                        : 'text-brand-purple/50'
                    }`}
                  >
                    {step.title}
                  </span>
                </div>
                {idx < STEPS.length - 1 && (
                  <div
                    className={`flex-1 h-0.5 mx-2 ${
                      idx < currentStep
                        ? 'bg-green-500'
                        : 'bg-[var(--lavender-300)]'
                    }`}
                  />
                )}
              </React.Fragment>
            );
          })}
        </div>

        {/* Step Content */}
        <div className="min-h-[300px]">{renderStepContent()}</div>

        <DialogFooter className="mt-6">
          {/* Back Button */}
          {currentStep > 0 && currentStep < 3 && (
            <Button
              type="button"
              variant="outline"
              onClick={() => setCurrentStep((prev) => prev - 1)}
              disabled={loading}
              className="mr-auto"
            >
              <ChevronLeft className="h-4 w-4 mr-1" />
              Back
            </Button>
          )}

          {/* Cancel Button */}
          {currentStep < 3 && (
            <Button
              type="button"
              variant="outline"
              onClick={handleClose}
              disabled={loading}
            >
              Cancel
            </Button>
          )}

          {/* Action Buttons */}
          {currentStep === 0 && (
            <Button
              type="button"
              onClick={handleUpload}
              disabled={loading || !usersFile}
              className="bg-brand-purple text-white hover:bg-[var(--purple-ink)]"
            >
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Analyzing...
                </>
              ) : (
                <>
                  Upload & Analyze
                  <ChevronRight className="h-4 w-4 ml-1" />
                </>
              )}
            </Button>
          )}

          {currentStep === 1 && (
            <Button
              type="button"
              onClick={() => setCurrentStep(2)}
              disabled={loading}
              className="bg-brand-purple text-white hover:bg-[var(--purple-ink)]"
            >
              Continue to Options
              <ChevronRight className="h-4 w-4 ml-1" />
            </Button>
          )}

          {currentStep === 2 && (
            <Button
              type="button"
              onClick={handleExecute}
              disabled={loading}
              className="bg-brand-purple text-white hover:bg-[var(--purple-ink)]"
            >
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Importing...
                </>
              ) : (
                <>
                  Execute Import
                  <CheckCircle2 className="h-4 w-4 ml-1" />
                </>
              )}
            </Button>
          )}

          {currentStep === 3 && (
            <Button
              type="button"
              onClick={() => {
                handleClose();
                onSuccess?.();
              }}
              className="bg-brand-purple text-white hover:bg-[var(--purple-ink)]"
            >
              Done
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default ComprehensiveImportWizard;
