'use client';

import { useCallback, useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Mail,
  RefreshCw,
  Plus,
  Play,
  Pause,
  BarChart3,
  Users,
  MousePointer,
  CheckCircle,
  TrendingUp,
  AlertTriangle,
} from 'lucide-react';
import Link from 'next/link';
import {
  listCampaigns,
  createCampaign,
  updateCampaign,
  triggerCampaign,
  getCampaignStats,
  type Campaign,
  type CampaignStatus,
  type CampaignTriggerType,
  type CampaignChannel,
} from '@/lib/predictive-client';

const statusConfig: Record<CampaignStatus, { color: string; icon: React.ReactNode }> = {
  draft: { color: 'bg-gray-500', icon: <span className="text-xs">•</span> },
  active: { color: 'bg-green-500', icon: <Play className="h-3 w-3" /> },
  paused: { color: 'bg-yellow-500', icon: <Pause className="h-3 w-3" /> },
  completed: { color: 'bg-blue-500', icon: <CheckCircle className="h-3 w-3" /> },
};

const triggerLabels: Record<CampaignTriggerType, string> = {
  churn_risk: 'Churn Risk Detected',
  health_score_drop: 'Health Score Drop',
  behavioral: 'Behavioral Trigger',
  scheduled: 'Scheduled',
};

const channelLabels: Record<CampaignChannel, string> = {
  email: 'Email',
  push: 'Push Notification',
  in_app: 'In-App Message',
  slack_cs: 'Slack CS Alert',
};

function CreateCampaignDialog({ onCreated }: { onCreated: () => void }) {
  const [open, setOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [productId, setProductId] = useState('');
  const [triggerType, setTriggerType] = useState<CampaignTriggerType>('churn_risk');
  const [riskSegments, setRiskSegments] = useState<string[]>(['critical', 'high']);

  async function handleCreate() {
    try {
      setCreating(true);
      await createCampaign({
        name,
        description,
        productId,
        trigger: {
          type: triggerType,
          conditions: [{ field: 'riskSegment', operator: 'in', value: riskSegments }],
        },
        audience: {
          riskSegments,
          excludeRecentContact: 24,
        },
        messages: [
          {
            channel: 'email',
            templateId: 'retention_check_in',
            delayHours: 0,
          },
        ],
      });
      setOpen(false);
      onCreated();
    } catch (err) {
      console.error('Failed to create campaign:', err);
    } finally {
      setCreating(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className="gap-2">
          <Plus className="h-4 w-4" />
          New Campaign
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Create Retention Campaign</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Campaign Name</Label>
            <Input
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="e.g., Q1 Churn Prevention"
            />
          </div>
          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea
              value={description}
              onChange={e => setDescription(e.target.value)}
              placeholder="What does this campaign do?"
            />
          </div>
          <div className="space-y-2">
            <Label>Product</Label>
            <Select value={productId} onValueChange={setProductId}>
              <SelectTrigger>
                <SelectValue placeholder="Select product" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="lysnrai">LysnrAI</SelectItem>
                <SelectItem value="chronomind">ChronoMind</SelectItem>
                <SelectItem value="mindlyst">MindLyst</SelectItem>
                <SelectItem value="jarvisjr">JarvisJr</SelectItem>
                <SelectItem value="nomgap">NomGap</SelectItem>
                <SelectItem value="peakpulse">PeakPulse</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Trigger</Label>
            <Select
              value={triggerType}
              onValueChange={v => setTriggerType(v as CampaignTriggerType)}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="churn_risk">Churn Risk Detected</SelectItem>
                <SelectItem value="health_score_drop">Health Score Drop</SelectItem>
                <SelectItem value="behavioral">Behavioral Trigger</SelectItem>
                <SelectItem value="scheduled">Scheduled</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Target Risk Segments</Label>
            <div className="flex gap-2">
              {(['critical', 'high', 'medium', 'low'] as const).map(segment => (
                <Badge
                  key={segment}
                  variant={riskSegments.includes(segment) ? 'default' : 'outline'}
                  className="cursor-pointer capitalize"
                  onClick={() =>
                    setRiskSegments(prev =>
                      prev.includes(segment) ? prev.filter(s => s !== segment) : [...prev, segment]
                    )
                  }
                >
                  {segment}
                </Badge>
              ))}
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => setOpen(false)}>
            Cancel
          </Button>
          <Button onClick={handleCreate} disabled={!name || !productId || creating}>
            {creating ? 'Creating...' : 'Create Campaign'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function CampaignStatsDialog({ campaign }: { campaign: Campaign }) {
  const [stats, setStats] = useState<Campaign['stats'] | null>(null);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);

  const loadStats = useCallback(async () => {
    try {
      setLoading(true);
      const data = await getCampaignStats(campaign.id);
      setStats(data);
    } catch (err) {
      console.error('Failed to load stats:', err);
    } finally {
      setLoading(false);
    }
  }, [campaign.id]);

  useEffect(() => {
    if (open) {
      loadStats();
    }
  }, [open, loadStats]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="ghost" size="sm">
          <BarChart3 className="h-4 w-4 mr-1" />
          Stats
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{campaign.name} — Performance</DialogTitle>
        </DialogHeader>
        {loading ? (
          <Skeleton className="h-40" />
        ) : stats ? (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <Card>
                <CardContent className="pt-6">
                  <div className="text-2xl font-bold">{stats.triggered}</div>
                  <p className="text-xs text-muted-foreground">Users Triggered</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-6">
                  <div className="text-2xl font-bold">{stats.sent}</div>
                  <p className="text-xs text-muted-foreground">Messages Sent</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-6">
                  <div className="text-2xl font-bold">{stats.opened}</div>
                  <p className="text-xs text-muted-foreground">Opened</p>
                  <p className="text-xs text-green-600">
                    {stats.sent > 0 ? ((stats.opened / stats.sent) * 100).toFixed(1) : 0}% open rate
                  </p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-6">
                  <div className="text-2xl font-bold">{stats.clicked}</div>
                  <p className="text-xs text-muted-foreground">Clicked</p>
                  <p className="text-xs text-blue-600">
                    {stats.sent > 0 ? ((stats.clicked / stats.sent) * 100).toFixed(1) : 0}% CTR
                  </p>
                </CardContent>
              </Card>
            </div>
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="text-2xl font-bold">{stats.converted}</div>
                    <p className="text-xs text-muted-foreground">Converted (Retained)</p>
                  </div>
                  <div className="text-right">
                    <div className="text-sm font-medium">
                      Control: {(stats.controlChurnRate * 100).toFixed(1)}% churn
                    </div>
                    <div className="text-sm font-medium text-green-600">
                      Treatment: {(stats.treatmentChurnRate * 100).toFixed(1)}% churn
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        ) : (
          <AlertDescription>Failed to load statistics</AlertDescription>
        )}
      </DialogContent>
    </Dialog>
  );
}

export default function CampaignsPage() {
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<string>('');

  const loadCampaigns = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await listCampaigns(selectedProduct || undefined);
      setCampaigns(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load campaigns');
    } finally {
      setLoading(false);
    }
  }, [selectedProduct]);

  useEffect(() => {
    loadCampaigns();
  }, [loadCampaigns]);

  async function handleToggleStatus(campaign: Campaign) {
    const newStatus = campaign.status === 'active' ? 'paused' : 'active';
    try {
      await updateCampaign(campaign.id, { status: newStatus });
      loadCampaigns();
    } catch (err) {
      console.error('Failed to update campaign:', err);
    }
  }

  async function handleTrigger(campaign: Campaign) {
    try {
      const result = await triggerCampaign(campaign.id);
      alert(`Campaign triggered for ${result.triggered} users`);
    } catch (err) {
      console.error('Failed to trigger campaign:', err);
    }
  }

  const activeCount = campaigns.filter(c => c.status === 'active').length;
  const totalTriggered = campaigns.reduce((sum, c) => sum + c.stats.triggered, 0);
  const totalConverted = campaigns.reduce((sum, c) => sum + c.stats.converted, 0);

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Retention Campaigns</h1>
          <p className="text-muted-foreground">
            Automated campaigns to re-engage at-risk users and reduce churn
          </p>
        </div>
        <div className="flex items-center gap-4">
          <Select value={selectedProduct} onValueChange={setSelectedProduct}>
            <SelectTrigger className="w-40">
              <SelectValue placeholder="Filter by product" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="">All Products</SelectItem>
              <SelectItem value="lysnrai">LysnrAI</SelectItem>
              <SelectItem value="chronomind">ChronoMind</SelectItem>
              <SelectItem value="mindlyst">MindLyst</SelectItem>
              <SelectItem value="jarvisjr">JarvisJr</SelectItem>
              <SelectItem value="nomgap">NomGap</SelectItem>
              <SelectItem value="peakpulse">PeakPulse</SelectItem>
            </SelectContent>
          </Select>
          <Button onClick={loadCampaigns} variant="outline" size="icon">
            <RefreshCw className="h-4 w-4" />
          </Button>
          <CreateCampaignDialog onCreated={loadCampaigns} />
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Active Campaigns</CardTitle>
            <Play className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{activeCount}</div>
            <p className="text-xs text-muted-foreground">Currently running</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Users Reached</CardTitle>
            <Users className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalTriggered.toLocaleString()}</div>
            <p className="text-xs text-muted-foreground">Campaign triggers</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Conversions</CardTitle>
            <CheckCircle className="h-4 w-4 text-emerald-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-emerald-600">
              {totalConverted.toLocaleString()}
            </div>
            <p className="text-xs text-muted-foreground">Users retained</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Conversion Rate</CardTitle>
            <TrendingUp className="h-4 w-4 text-purple-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">
              {totalTriggered > 0 ? ((totalConverted / totalTriggered) * 100).toFixed(1) : 0}%
            </div>
            <p className="text-xs text-muted-foreground">Avg across campaigns</p>
          </CardContent>
        </Card>
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* Campaigns Table */}
      <Card>
        <CardHeader>
          <CardTitle>All Campaigns</CardTitle>
          <CardDescription>
            Manage automated retention campaigns and view performance
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-12" />
              ))}
            </div>
          ) : campaigns.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <Mail className="h-12 w-12 mx-auto mb-4 opacity-20" />
              <p>No campaigns yet</p>
              <p className="text-sm">Create your first retention campaign to get started</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Campaign</TableHead>
                  <TableHead>Product</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Trigger</TableHead>
                  <TableHead>Messages</TableHead>
                  <TableHead>Performance</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {campaigns.map(campaign => (
                  <TableRow key={campaign.id}>
                    <TableCell>
                      <div className="font-medium">{campaign.name}</div>
                      <div className="text-xs text-muted-foreground truncate max-w-[200px]">
                        {campaign.description}
                      </div>
                    </TableCell>
                    <TableCell>{campaign.productId}</TableCell>
                    <TableCell>
                      <Badge className={statusConfig[campaign.status].color}>
                        {statusConfig[campaign.status].icon}
                        <span className="ml-1 capitalize">{campaign.status}</span>
                      </Badge>
                    </TableCell>
                    <TableCell>{triggerLabels[campaign.trigger.type]}</TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1">
                        {campaign.messages.map((msg, idx) => (
                          <Badge key={idx} variant="outline" className="text-xs w-fit">
                            {channelLabels[msg.channel]}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">
                        <span className="font-medium">{campaign.stats.converted}</span>
                        <span className="text-muted-foreground">
                          {' '}
                          / {campaign.stats.triggered} converted
                        </span>
                      </div>
                      <div className="text-xs text-muted-foreground">
                        {campaign.stats.opened} opens, {campaign.stats.clicked} clicks
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleToggleStatus(campaign)}
                        >
                          {campaign.status === 'active' ? (
                            <Pause className="h-4 w-4" />
                          ) : (
                            <Play className="h-4 w-4" />
                          )}
                        </Button>
                        <CampaignStatsDialog campaign={campaign} />
                        <Button variant="ghost" size="sm" onClick={() => handleTrigger(campaign)}>
                          <MousePointer className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex gap-4">
        <Link href="/health-dashboard">
          <Button variant="outline" className="gap-2">
            View Health Dashboard
            <TrendingUp className="h-4 w-4" />
          </Button>
        </Link>
        <Link href="/predictive/at-risk">
          <Button variant="outline" className="gap-2">
            View At-Risk Users
            <AlertTriangle className="h-4 w-4" />
          </Button>
        </Link>
      </div>
    </div>
  );
}
