import { useState } from 'react';
import type { Route } from './+types/coupons';
import { Card, CardHeader, CardTitle, CardContent } from '~/components/ui/card/card';
import { Button } from '~/components/ui/button/button';
import { Input } from '~/components/ui/input/input';
import { Label } from '~/components/ui/label/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '~/components/ui/select/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '~/components/ui/table/table';
import { Badge } from '~/components/ui/badge/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '~/components/ui/dialog/dialog';
import { 
  Ticket, 
  Plus, 
  Edit, 
  Trash2, 
  Copy,
  CheckCircle,
  XCircle,
  Calendar,
  Users,
  Percent
} from 'lucide-react';
import styles from './coupons.module.css';

export const meta: Route.MetaFunction = () => {
  return [{ title: 'Discount Coupons' }];
};

interface Coupon {
  id: string;
  code: string;
  type: 'percentage' | 'fixed';
  value: number;
  maxUses: number;
  usedCount: number;
  expiryDate: string;
  status: 'active' | 'expired' | 'disabled';
  applicablePlans: string[];
  minPurchase?: number;
}

export default function Coupons() {
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [coupons, setCoupons] = useState<Coupon[]>([
    {
      id: '1',
      code: 'WELCOME20',
      type: 'percentage',
      value: 20,
      maxUses: 100,
      usedCount: 45,
      expiryDate: '1403/12/30',
      status: 'active',
      applicablePlans: ['all'],
      minPurchase: 50000
    },
    {
      id: '2',
      code: 'SUMMER50K',
      type: 'fixed',
      value: 50000,
      maxUses: 50,
      usedCount: 12,
      expiryDate: '1403/10/30',
      status: 'active',
      applicablePlans: ['premium', 'pro'],
      minPurchase: 200000
    },
    {
      id: '3',
      code: 'TRIAL',
      type: 'percentage',
      value: 100,
      maxUses: 200,
      usedCount: 200,
      expiryDate: '1403/09/15',
      status: 'expired',
      applicablePlans: ['basic']
    },
    {
      id: '4',
      code: 'FRIEND30',
      type: 'percentage',
      value: 30,
      maxUses: 500,
      usedCount: 234,
      expiryDate: '1404/01/15',
      status: 'active',
      applicablePlans: ['all']
    }
  ]);

  const [newCoupon, setNewCoupon] = useState({
    code: '',
    type: 'percentage' as 'percentage' | 'fixed',
    value: 0,
    maxUses: 0,
    expiryDate: '',
    applicablePlans: 'all',
    minPurchase: 0
  });

  const handleCreateCoupon = () => {
    const coupon: Coupon = {
      id: Date.now().toString(),
      code: newCoupon.code.toUpperCase(),
      type: newCoupon.type,
      value: newCoupon.value,
      maxUses: newCoupon.maxUses,
      usedCount: 0,
      expiryDate: newCoupon.expiryDate,
      status: 'active',
      applicablePlans: newCoupon.applicablePlans === 'all' ? ['all'] : newCoupon.applicablePlans.split(','),
      minPurchase: newCoupon.minPurchase || undefined
    };

    setCoupons([coupon, ...coupons]);
    setIsCreateDialogOpen(false);
    setNewCoupon({
      code: '',
      type: 'percentage',
      value: 0,
      maxUses: 0,
      expiryDate: '',
      applicablePlans: 'all',
      minPurchase: 0
    });
  };

  const deleteCoupon = (id: string) => {
    setCoupons(coupons.filter(c => c.id !== id));
  };

  const toggleCouponStatus = (id: string) => {
    setCoupons(coupons.map(c => 
      c.id === id 
        ? { ...c, status: c.status === 'active' ? 'disabled' : 'active' as 'active' | 'disabled' }
        : c
    ));
  };

  const copyCouponCode = (code: string) => {
    navigator.clipboard.writeText(code);
    // در واقعیت باید toast نمایش داده شود
    console.log(`کد ${code} کپی شد`);
  };

  const generateRandomCode = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = '';
    for (let i = 0; i < 8; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setNewCoupon({ ...newCoupon, code });
  };

  const activeCoupons = coupons.filter(c => c.status === 'active').length;
  const totalUses = coupons.reduce((acc, c) => acc + c.usedCount, 0);
  const totalSavings = coupons.reduce((acc, c) => {
    if (c.type === 'percentage') {
      return acc + (c.usedCount * 100000 * (c.value / 100)); // فرضی
    }
    return acc + (c.usedCount * c.value);
  }, 0);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div>
          <h1 className={styles.title}>
            <Ticket size={28} />
            کدهای تخفیف
          </h1>
          <p className={styles.subtitle}>مدیریت کوپن‌ها و پیشنهادات ویژه</p>
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus size={16} />
              ایجاد کد تخفیف جدید
            </Button>
          </DialogTrigger>
          <DialogContent className={styles.dialog}>
            <DialogHeader>
              <DialogTitle>کد تخفیف جدید</DialogTitle>
            </DialogHeader>
            <div className={styles.form}>
              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <Label htmlFor="code">کد تخفیف</Label>
                  <div className={styles.codeInput}>
                    <Input
                      id="code"
                      value={newCoupon.code}
                      onChange={(e) => setNewCoupon({ ...newCoupon, code: e.target.value.toUpperCase() })}
                      placeholder="SUMMER2024"
                    />
                    <Button variant="outline" onClick={generateRandomCode}>تولید خودکار</Button>
                  </div>
                </div>
              </div>

              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <Label htmlFor="type">نوع تخفیف</Label>
                  <Select value={newCoupon.type} onValueChange={(value: any) => setNewCoupon({ ...newCoupon, type: value })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="percentage">درصدی</SelectItem>
                      <SelectItem value="fixed">مبلغ ثابت</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className={styles.formGroup}>
                  <Label htmlFor="value">{newCoupon.type === 'percentage' ? 'درصد تخفیف' : 'مبلغ تخفیف (تومان)'}</Label>
                  <Input
                    id="value"
                    type="number"
                    value={newCoupon.value}
                    onChange={(e) => setNewCoupon({ ...newCoupon, value: Number(e.target.value) })}
                  />
                </div>
              </div>

              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <Label htmlFor="maxUses">حداکثر استفاده</Label>
                  <Input
                    id="maxUses"
                    type="number"
                    value={newCoupon.maxUses}
                    onChange={(e) => setNewCoupon({ ...newCoupon, maxUses: Number(e.target.value) })}
                  />
                </div>

                <div className={styles.formGroup}>
                  <Label htmlFor="expiryDate">تاریخ انقضا</Label>
                  <Input
                    id="expiryDate"
                    type="text"
                    value={newCoupon.expiryDate}
                    onChange={(e) => setNewCoupon({ ...newCoupon, expiryDate: e.target.value })}
                    placeholder="1403/12/30"
                  />
                </div>
              </div>

              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <Label htmlFor="minPurchase">حداقل خرید (تومان)</Label>
                  <Input
                    id="minPurchase"
                    type="number"
                    value={newCoupon.minPurchase}
                    onChange={(e) => setNewCoupon({ ...newCoupon, minPurchase: Number(e.target.value) })}
                    placeholder="اختیاری"
                  />
                </div>

                <div className={styles.formGroup}>
                  <Label htmlFor="plans">پکیج‌های قابل اعمال</Label>
                  <Select value={newCoupon.applicablePlans} onValueChange={(value) => setNewCoupon({ ...newCoupon, applicablePlans: value })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">همه پکیج‌ها</SelectItem>
                      <SelectItem value="basic">پایه</SelectItem>
                      <SelectItem value="pro">حرفه‌ای</SelectItem>
                      <SelectItem value="premium">پریمیوم</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className={styles.formActions}>
                <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>لغو</Button>
                <Button onClick={handleCreateCoupon}>ایجاد کد تخفیف</Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className={styles.statsGrid}>
        <Card>
          <CardHeader>
            <div className={styles.statHeader}>
              <CardTitle>کدهای فعال</CardTitle>
              <CheckCircle size={20} className={styles.statIcon} />
            </div>
          </CardHeader>
          <CardContent>
            <div className={styles.statValue}>{activeCoupons}</div>
            <div className={styles.statSubtext}>از {coupons.length} کد کل</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <div className={styles.statHeader}>
              <CardTitle>کل استفاده‌ها</CardTitle>
              <Users size={20} className={styles.statIcon} />
            </div>
          </CardHeader>
          <CardContent>
            <div className={styles.statValue}>{totalUses.toLocaleString('fa-IR')}</div>
            <div className={styles.statSubtext}>بار استفاده شده</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <div className={styles.statHeader}>
              <CardTitle>کل تخفیفات</CardTitle>
              <Percent size={20} className={styles.statIcon} />
            </div>
          </CardHeader>
          <CardContent>
            <div className={styles.statValue}>{(totalSavings / 1000000).toFixed(1)} M</div>
            <div className={styles.statSubtext}>تومان تخفیف داده شده</div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>لیست کدهای تخفیف</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>کد</TableHead>
                <TableHead>نوع</TableHead>
                <TableHead>مقدار</TableHead>
                <TableHead>استفاده</TableHead>
                <TableHead>تاریخ انقضا</TableHead>
                <TableHead>وضعیت</TableHead>
                <TableHead>عملیات</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {coupons.map((coupon) => (
                <TableRow key={coupon.id}>
                  <TableCell>
                    <div className={styles.codeCell}>
                      <code className={styles.code}>{coupon.code}</code>
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => copyCouponCode(coupon.code)}
                      >
                        <Copy size={14} />
                      </Button>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {coupon.type === 'percentage' ? 'درصدی' : 'مبلغ ثابت'}
                    </Badge>
                  </TableCell>
                  <TableCell className={styles.value}>
                    {coupon.type === 'percentage' 
                      ? `${coupon.value}%` 
                      : `${coupon.value.toLocaleString('fa-IR')} تومان`
                    }
                  </TableCell>
                  <TableCell>
                    <div className={styles.usage}>
                      <span>{coupon.usedCount} / {coupon.maxUses}</span>
                      <div className={styles.usageBar}>
                        <div 
                          className={styles.usageProgress}
                          style={{ width: `${(coupon.usedCount / coupon.maxUses) * 100}%` }}
                        />
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className={styles.date}>
                    <Calendar size={14} />
                    {coupon.expiryDate}
                  </TableCell>
                  <TableCell>
                    <Badge 
                      variant={
                        coupon.status === 'expired' ? 'secondary' : 
                        coupon.status === 'disabled' ? 'destructive' : 
                        'outline'
                      }
                    >
                      {coupon.status === 'active' && 'فعال'}
                      {coupon.status === 'expired' && 'منقضی شده'}
                      {coupon.status === 'disabled' && 'غیرفعال'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className={styles.actions}>
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => toggleCouponStatus(coupon.id)}
                        disabled={coupon.status === 'expired'}
                      >
                        {coupon.status === 'active' ? <XCircle size={14} /> : <CheckCircle size={14} />}
                      </Button>
                      <Button variant="outline" size="sm">
                        <Edit size={14} />
                      </Button>
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => deleteCoupon(coupon.id)}
                      >
                        <Trash2 size={14} />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
