'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 {
  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,
} from '@/components/ui/dialog';
import { AlertTriangle, Users, RefreshCw, Search, TrendingUp, Mail, Activity } from 'lucide-react';
import Link from 'next/link';
import {
  getAtRiskUsers,
  getUserRiskProfile,
  type AtRiskUser,
  type RiskSegment,
  type UserRiskProfile,
} from '@/lib/predictive-client';

const riskSegmentConfig: Record<
  RiskSegment,
  { color: string; label: string; icon: React.ReactNode }
> = {
  critical: {
    color: 'bg-red-500',
    label: 'Critical Risk',
    icon: <AlertTriangle className="h-3 w-3" />,
  },
  high: { color: 'bg-orange-500', label: 'High Risk', icon: <TrendingUp className="h-3 w-3" /> },
  medium: { color: 'bg-yellow-500', label: 'Medium Risk', icon: <Activity className="h-3 w-3" /> },
  low: { color: 'bg-green-500', label: 'Low Risk', icon: <Users className="h-3 w-3" /> },
};

function UserDetailDialog({ userId }: { userId: string }) {
  const [profile, setProfile] = useState<UserRiskProfile | null>(null);
  const [loading, setLoading] = useState(true);

  const loadProfile = useCallback(async () => {
    try {
      const data = await getUserRiskProfile(userId);
      setProfile(data);
    } catch (err) {
      console.error('Failed to load user profile:', err);
    } finally {
      setLoading(false);
    }
  }, [userId]);

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

  if (loading) {
    return <Skeleton className="h-40" />;
  }

  if (!profile) {
    return <AlertDescription>Failed to load user profile</AlertDescription>;
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <div className="text-sm text-muted-foreground">Churn Probability</div>
          <div className="text-2xl font-bold">{(profile.churnProbability * 100).toFixed(1)}%</div>
        </div>
        <Badge className={riskSegmentConfig[profile.riskSegment].color}>
          {riskSegmentConfig[profile.riskSegment].label}
        </Badge>
      </div>

      {profile.explanation && (
        <div className="space-y-2">
          <div className="font-medium">AI Explanation</div>
          <p className="text-sm text-muted-foreground">{profile.explanation.nlExplanation}</p>

          <div className="font-medium mt-4">Top Risk Factors</div>
          <div className="space-y-1">
            {profile.explanation.topRiskFactors.slice(0, 5).map((factor, idx) => (
              <div key={idx} className="flex items-center justify-between text-sm">
                <span>{factor.feature}</span>
                <span
                  className={factor.direction === 'negative' ? 'text-red-500' : 'text-green-500'}
                >
                  {(factor.contribution * 100).toFixed(1)}%
                </span>
              </div>
            ))}
          </div>

          {profile.explanation.suggestedActions.length > 0 && (
            <>
              <div className="font-medium mt-4">Suggested Actions</div>
              <ul className="text-sm text-muted-foreground list-disc list-inside">
                {profile.explanation.suggestedActions.map((action, idx) => (
                  <li key={idx}>{action}</li>
                ))}
              </ul>
            </>
          )}
        </div>
      )}

      {profile.interventionHistory && profile.interventionHistory.length > 0 && (
        <div>
          <div className="font-medium mt-4">Intervention History</div>
          <div className="space-y-1 text-sm">
            {profile.interventionHistory.map((intervention, idx) => (
              <div key={idx} className="flex items-center gap-2">
                <span>{intervention.action}</span>
                <span className="text-muted-foreground">
                  {new Date(intervention.timestamp).toLocaleDateString()}
                </span>
                {intervention.outcome && (
                  <Badge
                    variant="outline"
                    className={
                      intervention.outcome === 'retained' || intervention.outcome === 'responded'
                        ? 'text-green-500'
                        : 'text-red-500'
                    }
                  >
                    {intervention.outcome}
                  </Badge>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

export default function AtRiskUsersPage() {
  const [users, setUsers] = useState<AtRiskUser[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedSegment, setSelectedSegment] = useState<RiskSegment | undefined>(undefined);
  const [selectedProduct, setSelectedProduct] = useState<string>('');
  const [searchQuery, setSearchQuery] = useState('');
  const [offset, setOffset] = useState(0);
  const limit = 20;

  const loadUsers = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const result = await getAtRiskUsers({
        productId: selectedProduct || undefined,
        segment: selectedSegment,
        limit,
        offset,
      });
      setUsers(result.users);
      setTotal(result.total);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load users');
    } finally {
      setLoading(false);
    }
  }, [offset, selectedProduct, selectedSegment]);

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

  const filteredUsers = users.filter(user =>
    searchQuery ? user.userId.toLowerCase().includes(searchQuery.toLowerCase()) : true
  );

  const segmentCounts = {
    critical: users.filter(u => u.riskSegment === 'critical').length,
    high: users.filter(u => u.riskSegment === 'high').length,
    medium: users.filter(u => u.riskSegment === 'medium').length,
    low: users.filter(u => u.riskSegment === 'low').length,
  };

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">At-Risk Users</h1>
          <p className="text-muted-foreground">
            ML-powered churn prediction identifying users likely to churn in the next 30 days
          </p>
        </div>
        <Button onClick={loadUsers} variant="outline" size="icon">
          <RefreshCw className="h-4 w-4" />
        </Button>
      </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">Critical Risk</CardTitle>
            <AlertTriangle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{segmentCounts.critical}</div>
            <p className="text-xs text-muted-foreground">Immediate action required</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">High Risk</CardTitle>
            <TrendingUp className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">{segmentCounts.high}</div>
            <p className="text-xs text-muted-foreground">Proactive outreach recommended</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Medium Risk</CardTitle>
            <Activity className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">{segmentCounts.medium}</div>
            <p className="text-xs text-muted-foreground">Monitor closely</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 At-Risk</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{total}</div>
            <p className="text-xs text-muted-foreground">Users tracked</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by user ID..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <Select value={selectedSegment} onValueChange={v => setSelectedSegment(v as RiskSegment)}>
          <SelectTrigger className="w-40">
            <SelectValue placeholder="Risk segment" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="">All Segments</SelectItem>
            <SelectItem value="critical">Critical</SelectItem>
            <SelectItem value="high">High</SelectItem>
            <SelectItem value="medium">Medium</SelectItem>
            <SelectItem value="low">Low</SelectItem>
          </SelectContent>
        </Select>
        <Select value={selectedProduct} onValueChange={setSelectedProduct}>
          <SelectTrigger className="w-40">
            <SelectValue placeholder="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>
        <Link href="/predictive/campaigns">
          <Button variant="outline" className="gap-2">
            <Mail className="h-4 w-4" />
            Campaigns
          </Button>
        </Link>
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* Users Table */}
      <Card>
        <CardHeader>
          <CardTitle>At-Risk Users</CardTitle>
          <CardDescription>
            Users ranked by churn probability. Click a row to view detailed risk analysis.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-12" />
              ))}
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>User ID</TableHead>
                    <TableHead>Product</TableHead>
                    <TableHead>Risk Segment</TableHead>
                    <TableHead>Churn Probability</TableHead>
                    <TableHead>Confidence</TableHead>
                    <TableHead>Last Active</TableHead>
                    <TableHead>Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredUsers.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center text-muted-foreground">
                        No at-risk users found
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredUsers.map(user => (
                      <TableRow key={`${user.userId}-${user.productId}`}>
                        <TableCell className="font-mono text-xs">{user.userId}</TableCell>
                        <TableCell>{user.productId}</TableCell>
                        <TableCell>
                          <Badge className={riskSegmentConfig[user.riskSegment].color}>
                            {riskSegmentConfig[user.riskSegment].icon}
                            <span className="ml-1 capitalize">{user.riskSegment}</span>
                          </Badge>
                        </TableCell>
                        <TableCell>{(user.churnProbability * 100).toFixed(1)}%</TableCell>
                        <TableCell>{(user.confidenceScore * 100).toFixed(0)}%</TableCell>
                        <TableCell>{user.daysSinceLastSession} days ago</TableCell>
                        <TableCell>
                          <Dialog>
                            <DialogTrigger asChild>
                              <Button variant="ghost" size="sm">
                                View Details
                              </Button>
                            </DialogTrigger>
                            <DialogContent className="max-w-lg">
                              <DialogHeader>
                                <DialogTitle>User Risk Profile</DialogTitle>
                              </DialogHeader>
                              <UserDetailDialog userId={user.userId} />
                            </DialogContent>
                          </Dialog>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>

              {/* Pagination */}
              <div className="flex items-center justify-between mt-4">
                <div className="text-sm text-muted-foreground">
                  Showing {offset + 1}-{Math.min(offset + filteredUsers.length, total)} of {total}{' '}
                  users
                </div>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={offset === 0}
                    onClick={() => setOffset(Math.max(0, offset - limit))}
                  >
                    Previous
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={offset + limit >= total}
                    onClick={() => setOffset(offset + limit)}
                  >
                    Next
                  </Button>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
