
'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Users, TrendingUp, DollarSign, Target, Plus, Copy, Check } from 'lucide-react';
import { toast } from 'sonner';

export default function ReferralsPage() {
  const { data: session } = useSession() || {};
  const [referralCodes, setReferralCodes] = useState<any[]>([]);
  const [analytics, setAnalytics] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState<string | null>(null);

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

  const fetchData = async () => {
    try {
      setLoading(true);
      
      // Fetch referral codes
      const codesRes = await fetch('/api/referrals');
      const codesData = await codesRes.json();
      setReferralCodes(codesData.referralCodes || []);

      // Fetch analytics
      const analyticsRes = await fetch('/api/referrals/analytics');
      const analyticsData = await analyticsRes.json();
      setAnalytics(analyticsData.analytics);
    } catch (error) {
      console.error('Error fetching referral data:', error);
      toast.error('Failed to fetch referral data');
    } finally {
      setLoading(false);
    }
  };

  const createReferralCode = async () => {
    try {
      const res = await fetch('/api/referrals', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          rewardType: 'FIXED_AMOUNT',
          rewardAmount: 100,
        }),
      });

      if (res.ok) {
        toast.success('Referral code created successfully');
        fetchData();
      } else {
        toast.error('Failed to create referral code');
      }
    } catch (error) {
      console.error('Error creating referral code:', error);
      toast.error('Failed to create referral code');
    }
  };

  const copyToClipboard = (code: string) => {
    navigator.clipboard.writeText(code);
    setCopied(code);
    toast.success('Code copied to clipboard');
    setTimeout(() => setCopied(null), 2000);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading referral data...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Referral Rewards Engine</h1>
          <p className="text-gray-600 mt-1">Track and manage referral codes and conversions</p>
        </div>
        <Button onClick={createReferralCode}>
          <Plus className="h-4 w-4 mr-2" />
          Create New Code
        </Button>
      </div>

      {/* Analytics Cards */}
      {analytics && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-600">Total Codes</CardTitle>
              <Users className="h-4 w-4 text-blue-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{analytics.totalCodes}</div>
              <p className="text-xs text-gray-500 mt-1">
                {analytics.activeCodes} active
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-600">Total Referrals</CardTitle>
              <Target className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{analytics.totalReferrals}</div>
              <p className="text-xs text-gray-500 mt-1">
                {analytics.totalConversions} converted
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-600">Conversion Rate</CardTitle>
              <TrendingUp className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{analytics.conversionRate}%</div>
              <p className="text-xs text-gray-500 mt-1">Average conversion</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-600">Total Revenue</CardTitle>
              <DollarSign className="h-4 w-4 text-yellow-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">R {analytics.totalRevenue.toLocaleString()}</div>
              <p className="text-xs text-gray-500 mt-1">From referrals</p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Referral Codes Table */}
      <Card>
        <CardHeader>
          <CardTitle>Your Referral Codes</CardTitle>
          <CardDescription>
            Share these codes to earn rewards when customers sign up
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Code</TableHead>
                <TableHead>Reward</TableHead>
                <TableHead>Times Used</TableHead>
                <TableHead>Conversions</TableHead>
                <TableHead>Revenue</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {referralCodes.map((code) => (
                <TableRow key={code.id}>
                  <TableCell className="font-mono font-semibold">{code.code}</TableCell>
                  <TableCell>
                    {code.rewardType === 'FIXED_AMOUNT' && `R ${code.rewardAmount}`}
                    {code.rewardType === 'PERCENTAGE' && `${code.rewardAmount}%`}
                    {code.rewardType === 'CREDIT' && `${code.rewardAmount} credits`}
                  </TableCell>
                  <TableCell>{code.timesUsed}</TableCell>
                  <TableCell>{code.conversions}</TableCell>
                  <TableCell>R {code.totalRevenue.toLocaleString()}</TableCell>
                  <TableCell>
                    <Badge variant={code.isActive ? 'default' : 'secondary'}>
                      {code.isActive ? 'Active' : 'Inactive'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => copyToClipboard(code.code)}
                    >
                      {copied === code.code ? (
                        <Check className="h-4 w-4 text-green-600" />
                      ) : (
                        <Copy className="h-4 w-4" />
                      )}
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
              {referralCodes.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                    No referral codes yet. Create your first code to get started!
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Top Performing Codes */}
      {analytics?.topPerformingCodes?.length > 0 && (
        <Card className="mt-8">
          <CardHeader>
            <CardTitle>Top Performing Codes</CardTitle>
            <CardDescription>Your most successful referral codes</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {analytics.topPerformingCodes.map((code: any, index: number) => (
                <div key={index} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <p className="font-mono font-semibold">{code.code}</p>
                    <p className="text-sm text-gray-600">{code.conversions} conversions</p>
                  </div>
                  <div className="text-right">
                    <p className="font-bold text-green-600">R {code.revenue.toLocaleString()}</p>
                    <p className="text-xs text-gray-500">Revenue</p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
