import { Bell, ChevronDown } from 'lucide-react';
import { toast } from 'sonner';

import { useEffect, useState } from 'react';

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

import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { Checkbox } from '@/Components/ui/checkbox';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/Components/ui/collapsible';
import { ConfirmDialog } from '@/Components/ui/confirm-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 { getRouteCanonicalLabel } from '@/config/site-navigation';
import { useFlashToasts } from '@/hooks/useFlashToasts';
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { FEATURE_USED, SETTINGS_NOTIFICATIONS_VIEWED } from '@/lib/event-catalog';
import { formatDateTime } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

type DigestTypeFrequency = 'daily' | 'weekly' | 'monthly' | 'disabled';

interface NotificationSetting {
  id: number;
  site_id: number;
  digest_frequency: 'off' | 'daily' | 'weekly' | 'monthly';
  notification_types: string[];
  digest_type_frequencies: Record<string, DigestTypeFrequency> | null;
  last_digest_sent_at: string | null;
}

interface Site {
  id: number;
  name: string;
}

interface Props {
  site: Site;
  settings: NotificationSetting | null;
}

const frequencyOptions = [
  { value: 'off', label: 'Off - No email digests' },
  { value: 'daily', label: 'Daily - Every 24 hours' },
  { value: 'weekly', label: 'Weekly - Every 7 days' },
  { value: 'monthly', label: 'Monthly - Every 30 days' },
];

const typeFrequencyOptions: { value: DigestTypeFrequency; label: string }[] = [
  { value: 'daily', label: 'Daily' },
  { value: 'weekly', label: 'Weekly' },
  { value: 'monthly', label: 'Monthly' },
  { value: 'disabled', label: 'Disabled' },
];

const notificationTypeOptions = [
  {
    value: 'analysis_complete',
    label: 'Analysis Complete',
    description: 'Include analysis completion summaries in your digest emails',
  },
  {
    value: 'new_recommendations',
    label: 'New Recommendations',
    description: 'Include new SEO recommendation highlights in your digest emails',
  },
  {
    value: 'traffic_alert',
    label: 'Traffic Alerts',
    description:
      'Include traffic change alerts in your digest emails (critical drops are always sent immediately)',
  },
  {
    value: 'connection_failure',
    label: 'Connection Failures',
    description:
      'Include connection failure notices in your digest emails (critical failures are always sent immediately)',
  },
];

const lifecycleTypeOptions = [
  {
    value: 'lifecycle_onboarding',
    label: 'Onboarding Tips',
    description: 'Get setup guidance and tips during your first two weeks',
  },
  {
    value: 'lifecycle_milestones',
    label: 'Milestone Celebrations',
    description: 'Receive notifications when you hit ROI and recommendation milestones',
  },
  {
    value: 'lifecycle_reengagement',
    label: 'Re-engagement Reminders',
    description: "Get reminders about pending opportunities when you haven't visited in a while",
  },
  {
    value: 'lifecycle_quick_wins',
    label: 'Weekly Quick Wins',
    description: 'Receive weekly low-effort, high-impact recommendation highlights',
  },
  {
    value: 'lifecycle_feature_discovery',
    label: 'Feature Tips',
    description: "Learn about features you haven't tried yet",
  },
  {
    value: 'lifecycle_activation',
    label: 'Activation Tips',
    description: 'Get nudges about AI drafts, publishing, and feature discovery',
  },
  {
    value: 'lifecycle_conversion',
    label: 'Plan & Upgrade Notifications',
    description: 'Receive notifications when approaching plan limits or when ROI results are ready',
  },
  {
    value: 'lifecycle_alerts',
    label: 'Decline & Spike Alerts',
    description: 'Get notified about sustained traffic declines and unusual spikes',
  },
  {
    value: 'lifecycle_quota',
    label: 'AI Quota Alerts',
    description: 'Receive alerts about your AI draft usage approaching or reaching your plan limit',
  },
  {
    value: 'lifecycle_billing',
    label: 'Post-Upgrade Emails',
    description: 'Tips, usage insights, and check-ins sent after upgrading your plan',
  },
  {
    value: 'lifecycle_upgrade',
    label: 'Upgrade Recommendations',
    description: 'Suggestions to upgrade your plan when you are approaching usage limits',
  },
  {
    value: 'lifecycle_plg',
    label: 'Team & Collaboration Nudges',
    description: 'Reminders about inviting team members and collaborative features',
  },
  {
    value: 'lifecycle_winback',
    label: 'Win-Back Emails',
    description: 'Re-engagement emails if you cancel or your subscription lapses',
  },
];

export default function Notifications({ site, settings }: Props) {
  // Canonical flash handling: success/error saves fire a toast (replaces the
  // bespoke inline <div> that only ever rendered flash.success and silently
  // dropped flash.error). Inertia `errors` are rendered inline per-field below.
  useFlashToasts();

  // Advanced section: collapsed by default so a solo user sees four core
  // digest toggles on load — no per-type frequency dropdowns, no multi-site
  // controls (R6UXA-006 / persona v1). Expanding reveals per-type frequency
  // selectors, 'apply to all sites', and lifecycle email preferences.
  const [advancedOpen, setAdvancedOpen] = useState(false);

  // R3UXA-010: cross-site apply confirm dialog
  const { sites, features } = usePage<PageProps>().props;
  const otherSiteCount = (sites?.length ?? 0) - 1;
  const [applyAllOpen, setApplyAllOpen] = useState(false);
  const [applyAllProcessing, setApplyAllProcessing] = useState(false);

  useEffect(() => {
    trackProductEvent(SETTINGS_NOTIFICATIONS_VIEWED);
    trackProductEvent(FEATURE_USED, { feature: 'settings_notifications' });
  }, []);

  const { data, setData, patch, processing, errors, isDirty } = useForm({
    digest_frequency: settings?.digest_frequency ?? 'weekly', // W2-26: default new settings to weekly
    notification_types: settings?.notification_types ?? [],
    digest_type_frequencies:
      settings?.digest_type_frequencies ?? ({} as Record<string, DigestTypeFrequency>),
  });

  const handleTypeFrequencyChange = (type: string, frequency: DigestTypeFrequency) => {
    setData('digest_type_frequencies', { ...data.digest_type_frequencies, [type]: frequency });
  };

  useUnsavedChanges(isDirty);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    patch(route('notification-settings.update', { site: site.id }));
  };

  const handleNotificationTypeToggle = (type: string) => {
    const current = data.notification_types;
    const isCurrentlyEnabled = current.includes(type);
    const updated = isCurrentlyEnabled ? current.filter((t) => t !== type) : [...current, type];
    setData('notification_types', updated);
    // R3FE-010: persist the displayed default 'weekly' when enabling a type without
    // opening its frequency selector so the payload always includes a concrete value.
    if (!isCurrentlyEnabled && !(type in data.digest_type_frequencies)) {
      setData('digest_type_frequencies', { ...data.digest_type_frequencies, [type]: 'weekly' });
    }
  };

  const handleApplyToAllSites = () => {
    setApplyAllProcessing(true);
    router.post(
      route('notification-settings.bulk-apply', { site: site.id }),
      {
        digest_frequency: data.digest_frequency,
        notification_types: data.notification_types,
        digest_type_frequencies: data.digest_type_frequencies,
      },
      {
        onSuccess: () => {
          toast.success(`Settings applied to all ${otherSiteCount + 1} sites.`);
          setApplyAllOpen(false);
        },
        onError: () => {
          toast.error('Could not apply settings to all sites. Please try again.');
        },
        onFinish: () => setApplyAllProcessing(false),
      },
    );
  };

  const isDigestEnabled = data.digest_frequency !== 'off';
  // R3UXA-011: when global digest is monthly, hide per-type selects (they can't be < monthly)
  const isMonthlyDigest = data.digest_frequency === 'monthly';

  // F4UXA-005: hide team/collaboration lifecycle toggle for solo users (persona v1).
  // lifecycle_plg promotes inviting team members — irrelevant to solo bloggers.
  const visibleLifecycleOptions = lifecycleTypeOptions.filter(
    (opt) => opt.value !== 'lifecycle_plg' || features.teams,
  );

  // F4UXA-014: W2-26 recommended defaults (weekly digest + core types)
  const RECOMMENDED_TYPES = ['analysis_complete', 'new_recommendations', 'traffic_alert', 'roi_milestone'];
  const handleResetToDefaults = () => {
    setData('digest_frequency', 'weekly');
    setData('notification_types', RECOMMENDED_TYPES);
    setData('digest_type_frequencies', {});
  };

  return (
    <DashboardLayout>
      <Head title={`${getRouteCanonicalLabel('notification-settings.show')} - ${site.name}`} />

      <EditorialPageHeader
        eyebrow={`Settings · ${site.name}`}
        title={getRouteCanonicalLabel('notification-settings.show')}
        subtitle={`These preferences apply to ${site.name} only.`}
      />

      <div className="container py-8">
        <div className="max-w-3xl mx-auto space-y-6">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="rounded-full bg-primary/10 p-2">
                  <Bell className="size-5 text-primary" />
                </div>
                <div>
                  <CardTitle>Email Notification Settings</CardTitle>
                  <CardDescription>
                    Choose what gets emailed and when for {site.name}. Everything can be turned off.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Digest Frequency Section */}
                <div className="space-y-3">
                  <div className="flex items-center gap-2">
                    <Label htmlFor="digest-frequency" className="text-base font-medium">
                      Digest Frequency
                    </Label>
                    {isDigestEnabled ? (
                      <Badge variant="success">Enabled</Badge>
                    ) : (
                      <Badge variant="secondary">Disabled</Badge>
                    )}
                  </div>
                  <p className="text-sm text-muted-foreground">
                    Choose how often you want to receive email summaries of your site&apos;s SEO
                    performance, recommendations, and traffic changes.
                  </p>
                  <Select
                    value={data.digest_frequency}
                    onValueChange={(value) =>
                      setData('digest_frequency', value as typeof data.digest_frequency)
                    }
                  >
                    <SelectTrigger id="digest-frequency" className="w-full">
                      <SelectValue placeholder="Select frequency" />
                    </SelectTrigger>
                    <SelectContent>
                      {frequencyOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {errors.digest_frequency && (
                    <p className="text-sm text-destructive">{errors.digest_frequency}</p>
                  )}
                </div>

                <hr className="border-t" />

                {/* Notification Types Section — core four toggles, no inline frequency selectors */}
                {/* R6UXA-006: per-type frequency dropdowns moved to Advanced so a solo single-site
                    user sees four clean checkboxes. The global digest cadence above is sufficient
                    for the persona v1 use case. */}
                <div className="space-y-4">
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <Label className="text-base font-medium">Digest Notification Types</Label>
                      <p className="text-sm text-muted-foreground mt-1">
                        Choose which types to include in your digest emails. These preferences apply
                        to digest frequency only — transactional alerts (critical traffic drops,
                        connection failures) are sent immediately and have their own unsubscribe
                        links.
                      </p>
                    </div>
                    {/* F4UXA-014: reset to recommended defaults */}
                    <button
                      type="button"
                      onClick={handleResetToDefaults}
                      className="shrink-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground transition-colors"
                    >
                      Reset to defaults
                    </button>
                  </div>

                  {/* F4UXA-014: hint when digest is off — types are inert */}
                  {!isDigestEnabled && (
                    <p className="text-xs text-muted-foreground italic">
                      Turn the digest on above to choose what&apos;s included.
                    </p>
                  )}

                  {/* Core four toggles — no inline frequency selectors (R6UXA-006) */}
                  <div className="space-y-4">
                    {notificationTypeOptions.map((option) => {
                      const isEnabled = data.notification_types.includes(option.value);
                      return (
                        <div key={option.value} className="flex items-start space-x-3">
                          <Checkbox
                            id={option.value}
                            checked={isEnabled}
                            onCheckedChange={() => handleNotificationTypeToggle(option.value)}
                            className="mt-1"
                          />
                          <div className="flex-1">
                            <label
                              htmlFor={option.value}
                              className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                            >
                              {option.label}
                            </label>
                            <p className="text-sm text-muted-foreground mt-1">
                              {option.description}
                            </p>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  {errors.notification_types && (
                    <p className="text-sm text-destructive">{errors.notification_types}</p>
                  )}
                </div>

                <hr className="border-t" />

                {/* Advanced section — per-type frequency + apply-to-all + lifecycle emails.
                    Collapsed by default (R6UXA-006 persona v1 alignment). */}
                <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
                  <CollapsibleTrigger className="flex w-full items-center justify-between rounded-md py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
                    <div>
                      <Label className="text-base font-medium cursor-pointer">
                        Advanced preferences
                      </Label>
                      <p className="text-sm text-muted-foreground mt-1">
                        Per-type send frequency, multi-site controls, and lifecycle emails. Most
                        users can leave these collapsed.
                      </p>
                    </div>
                    <ChevronDown
                      className={cn(
                        'size-5 shrink-0 text-muted-foreground transition-transform duration-200',
                        advancedOpen && 'rotate-180',
                      )}
                    />
                  </CollapsibleTrigger>

                  <CollapsibleContent className="space-y-6 pt-4">
                    {/* Per-type frequency selectors (R6UXA-006: moved from core section) */}
                    {isDigestEnabled && !isMonthlyDigest && (
                      <div className="space-y-3">
                        <Label className="text-sm font-medium text-muted-foreground">
                          Per-type send frequency
                        </Label>
                        <p className="text-xs text-muted-foreground">
                          Override the global cadence for individual notification types. Only active
                          for the types you have enabled above.
                        </p>
                        <div className="space-y-3">
                          {notificationTypeOptions.map((option) => {
                            const isEnabled = data.notification_types.includes(option.value);
                            const typeFreq = (data.digest_type_frequencies[option.value] ??
                              'weekly') as DigestTypeFrequency;
                            return (
                              <div key={option.value} className="flex items-center justify-between gap-3">
                                <span
                                  className={cn(
                                    'text-sm',
                                    isEnabled ? 'text-foreground' : 'text-muted-foreground',
                                  )}
                                >
                                  {option.label}
                                </span>
                                {isEnabled ? (
                                  <Select
                                    value={typeFreq}
                                    onValueChange={(v) =>
                                      handleTypeFrequencyChange(
                                        option.value,
                                        v as DigestTypeFrequency,
                                      )
                                    }
                                  >
                                    <SelectTrigger
                                      className="h-7 w-[110px] text-xs"
                                      aria-label={`Frequency for ${option.label}`}
                                    >
                                      <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {typeFrequencyOptions.map((fo) => (
                                        <SelectItem
                                          key={fo.value}
                                          value={fo.value}
                                          className="text-xs"
                                        >
                                          {fo.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                ) : (
                                  <span className="text-xs text-muted-foreground">
                                    (disabled above)
                                  </span>
                                )}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    )}

                    {isDigestEnabled && isMonthlyDigest && (
                      <p className="text-xs text-muted-foreground">
                        Per-type frequency overrides are not available when the global digest is set
                        to Monthly.
                      </p>
                    )}

                    {/* Apply to all sites — only shown when the user has multiple sites
                        (R6UXA-006: was in core section, moved here; solo single-site users never see it) */}
                    {otherSiteCount > 0 && (
                      <div className="rounded-lg border bg-muted/30 p-4 space-y-2">
                        <p className="text-sm font-medium">Apply to all sites</p>
                        <p className="text-xs text-muted-foreground">
                          Copy these settings to all {otherSiteCount + 1} of your sites. This
                          overwrites their current notification preferences.
                        </p>
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => setApplyAllOpen(true)}
                        >
                          Apply to all sites
                        </Button>
                      </div>
                    )}

                    {/* Lifecycle / CRM email preferences */}
                    <div className="space-y-4">
                      <div>
                        <Label className="text-sm font-medium text-muted-foreground">
                          Lifecycle emails
                        </Label>
                        <p className="text-xs text-muted-foreground mt-1">
                          Onboarding guidance, milestone celebrations, feature tips, and other
                          optional emails.
                        </p>
                      </div>
                      {/* F4UXA-005: filter out team/collab toggle for solo users */}
                      {visibleLifecycleOptions.map((option) => {
                        const isEnabled = data.notification_types.includes(option.value);
                        const typeFreq = (data.digest_type_frequencies[option.value] ??
                          'weekly') as DigestTypeFrequency;
                        return (
                          <div key={option.value} className="flex items-start space-x-3">
                            <Checkbox
                              id={option.value}
                              checked={isEnabled}
                              onCheckedChange={() => handleNotificationTypeToggle(option.value)}
                              className="mt-1"
                            />
                            <div className="flex-1">
                              <div className="flex items-center gap-3">
                                <label
                                  htmlFor={option.value}
                                  className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                                >
                                  {option.label}
                                </label>
                                {isEnabled && isDigestEnabled && (
                                  isMonthlyDigest ? (
                                    <span className="text-xs text-muted-foreground">Monthly</span>
                                  ) : (
                                    <Select
                                      value={typeFreq}
                                      onValueChange={(v) =>
                                        handleTypeFrequencyChange(
                                          option.value,
                                          v as DigestTypeFrequency,
                                        )
                                      }
                                    >
                                      <SelectTrigger
                                        className="h-7 w-[110px] text-xs"
                                        aria-label={`Frequency for ${option.label}`}
                                      >
                                        <SelectValue />
                                      </SelectTrigger>
                                      <SelectContent>
                                        {typeFrequencyOptions.map((fo) => (
                                          <SelectItem
                                            key={fo.value}
                                            value={fo.value}
                                            className="text-xs"
                                          >
                                            {fo.label}
                                          </SelectItem>
                                        ))}
                                      </SelectContent>
                                    </Select>
                                  )
                                )}
                              </div>
                              <p className="text-sm text-muted-foreground mt-1">
                                {option.description}
                              </p>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </CollapsibleContent>
                </Collapsible>

                <hr className="border-t" />

                {/* Info box about critical alerts */}
                <div className="rounded-lg border bg-muted/50 p-4">
                  <div className="flex gap-2">
                    <Bell className="size-5 text-muted-foreground shrink-0" />
                    <div className="space-y-1">
                      <p className="text-sm font-medium">
                        Critical Alerts &amp; Transactional Emails
                      </p>
                      <p className="text-sm text-muted-foreground">
                        Some emails are sent immediately regardless of your digest settings:
                        critical traffic drops (&gt;50%), connection failures, and direct analysis
                        notifications. These transactional emails include their own unsubscribe
                        links. The digest preferences above control what appears in your periodic
                        summaries only.
                      </p>
                    </div>
                  </div>
                </div>

                {settings?.last_digest_sent_at && (
                  <div className="text-sm text-muted-foreground">
                    Last digest sent: {formatDateTime(settings.last_digest_sent_at)}
                  </div>
                )}

                <div className="flex flex-wrap gap-3">
                  <LoadingButton type="submit" loading={processing} loadingText="Saving...">
                    Save Settings
                  </LoadingButton>
                </div>
              </form>
            </CardContent>
          </Card>

          <ConfirmDialog
            open={applyAllOpen}
            onOpenChange={setApplyAllOpen}
            title="Apply to all sites?"
            description={`This will overwrite the notification settings on all ${otherSiteCount + 1} of your sites with the current values for ${site.name}. This cannot be undone.`}
            confirmLabel={applyAllProcessing ? 'Applying…' : 'Apply to all sites'}
            onConfirm={handleApplyToAllSites}
          />
        </div>
      </div>
    </DashboardLayout>
  );
}
