"use client";

import { useState } from "react";
import { 
  FileText, CheckCircle, XCircle, DollarSign, 
  TrendingUp, Activity, Plus, Search, MoreHorizontal,
  Download, Mail, Send, Save, Printer
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Label } from "@/components/ui/label";
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 {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, 
  DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu";

const kpiData = [
  { title: "Quotes Sent", value: "145", icon: FileText, color: "text-blue-500" },
  { title: "Accepted Quotes", value: "82", icon: CheckCircle, color: "text-emerald-500" },
  { title: "Rejected Quotes", value: "12", icon: XCircle, color: "text-brand-red" },
  { title: "Revenue (Monthly)", value: "12.5M DZD", icon: DollarSign, color: "text-amber-500" },
  { title: "Monthly Sales", value: "24", icon: TrendingUp, color: "text-purple-500" },
  { title: "Conversion Rate", value: "56.5%", icon: Activity, color: "text-blue-400" },
];

const mockInvoices = [
  { id: "INV-2024-001", client: "SARL Plastique Algerie", amount: "4,500,000 DZD", date: "2024-03-15", status: "Paid" },
  { id: "INV-2024-002", client: "EURL Metal Works", amount: "1,250,000 DZD", date: "2024-03-14", status: "Sent" },
  { id: "INV-2024-003", client: "Global Waste Solutions", amount: "8,900,000 DZD", date: "2024-02-28", status: "Overdue" },
  { id: "INV-2024-004", client: "Industrie Papier Nord", amount: "750,000 DZD", date: "2024-03-18", status: "Draft" },
  { id: "INV-2024-005", client: "Recyclage Est", amount: "3,200,000 DZD", date: "2024-01-10", status: "Cancelled" },
];

const getStatusBadge = (status: string) => {
  switch (status) {
    case "Paid": return <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30">Paid</Badge>;
    case "Sent": return <Badge className="bg-blue-500/20 text-blue-400 border-blue-500/30">Sent</Badge>;
    case "Draft": return <Badge className="bg-gray-500/20 text-gray-400 border-gray-500/30">Draft</Badge>;
    case "Overdue": return <Badge className="bg-amber-500/20 text-amber-500 border-amber-500/30">Overdue</Badge>;
    case "Cancelled": return <Badge className="bg-brand-red/20 text-brand-red border-brand-red/30">Cancelled</Badge>;
    default: return <Badge>{status}</Badge>;
  }
};

export default function SalesCRM() {
  const [activeTab, setActiveTab] = useState("overview");

  // Quote Generator State
  const [qty, setQty] = useState(1);
  const [price, setPrice] = useState(2500000);
  const [discount, setDiscount] = useState(0);
  const [delivery, setDelivery] = useState(50000);
  
  const subtotal = (qty * price) - discount;
  const vat = subtotal * 0.19; // 19% TVA
  const total = subtotal + vat + delivery;

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-bold text-white tracking-tight">Sales & Quotes</h2>
          <p className="text-gray-400 mt-1">Manage quotations, invoices, and sales performance.</p>
        </div>
        <div className="flex gap-2">
          <Button 
            variant="outline" 
            className="border-white/10 bg-transparent text-white hover:bg-white/5"
            onClick={() => setActiveTab("invoices")}
          >
            <FileText className="w-4 h-4 mr-2" /> View Invoices
          </Button>
          <Button 
            className="bg-brand-red hover:bg-brand-red/90 text-white font-semibold"
            onClick={() => setActiveTab("create-quote")}
          >
            <Plus className="w-4 h-4 mr-2" /> Create Quote
          </Button>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="bg-brand-charcoal border border-white/10 p-1">
          <TabsTrigger value="overview" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">Overview</TabsTrigger>
          <TabsTrigger value="invoices" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">Invoices</TabsTrigger>
          <TabsTrigger value="create-quote" className="data-[state=active]:bg-brand-red data-[state=active]:text-white">Quote Generator</TabsTrigger>
        </TabsList>

        {/* OVERVIEW TAB */}
        <TabsContent value="overview" className="mt-6 space-y-6">
          <div className="grid gap-4 grid-cols-2 md:grid-cols-3 lg:grid-cols-6">
            {kpiData.map((kpi, index) => (
              <Card key={index} className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2 px-4 pt-4">
                  <CardTitle className="text-xs font-medium text-gray-400">
                    {kpi.title}
                  </CardTitle>
                  <kpi.icon className={`h-4 w-4 ${kpi.color}`} />
                </CardHeader>
                <CardContent className="px-4 pb-4">
                  <div className="text-xl font-bold text-white">{kpi.value}</div>
                </CardContent>
              </Card>
            ))}
          </div>

          <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
            <CardHeader>
              <CardTitle className="text-white">Recent Activity</CardTitle>
              <CardDescription className="text-gray-400">Latest quotes sent and invoices paid.</CardDescription>
            </CardHeader>
            <CardContent>
              {/* Timeline mockup */}
              <div className="space-y-4">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="flex items-start gap-4">
                    <div className="w-2 h-2 mt-2 rounded-full bg-brand-red"></div>
                    <div>
                      <p className="text-sm text-white font-medium">Quote #QT-2024-08{i} Sent to SARL Plastique</p>
                      <p className="text-xs text-gray-500">2 hours ago by Super Admin</p>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* INVOICES TAB */}
        <TabsContent value="invoices" className="mt-6">
          <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm overflow-hidden">
            <div className="p-4 border-b border-white/10 flex items-center justify-between bg-black/20">
              <div className="relative w-full max-w-sm">
                <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-500" />
                <Input 
                  placeholder="Search invoice number, client..." 
                  className="pl-9 bg-black/40 border-white/10 focus-visible:ring-brand-red text-white"
                />
              </div>
            </div>
            
            <div className="overflow-x-auto">
              <Table>
                <TableHeader className="bg-black/40 hover:bg-black/40">
                  <TableRow className="border-white/10 hover:bg-transparent">
                    <TableHead className="text-gray-400 font-semibold">Invoice ID</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Client</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Date</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Amount</TableHead>
                    <TableHead className="text-gray-400 font-semibold">Status</TableHead>
                    <TableHead className="text-right text-gray-400 font-semibold">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockInvoices.map((inv) => (
                    <TableRow key={inv.id} className="border-white/5 hover:bg-white/5 transition-colors">
                      <TableCell className="font-semibold text-white">{inv.id}</TableCell>
                      <TableCell className="text-gray-300">{inv.client}</TableCell>
                      <TableCell className="text-gray-400">{inv.date}</TableCell>
                      <TableCell className="text-white font-medium">{inv.amount}</TableCell>
                      <TableCell>{getStatusBadge(inv.status)}</TableCell>
                      <TableCell className="text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0 text-gray-400 hover:text-white hover:bg-white/10">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="bg-brand-charcoal border-white/10 text-white">
                            <DropdownMenuItem className="focus:bg-white/10 cursor-pointer"><Download className="w-4 h-4 mr-2"/> Download PDF</DropdownMenuItem>
                            <DropdownMenuItem className="focus:bg-white/10 cursor-pointer"><Mail className="w-4 h-4 mr-2"/> Send Email</DropdownMenuItem>
                            <DropdownMenuSeparator className="bg-white/10" />
                            <DropdownMenuItem className="focus:bg-white/10 cursor-pointer text-emerald-400"><CheckCircle className="w-4 h-4 mr-2"/> Mark as Paid</DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>

        {/* QUOTE GENERATOR TAB */}
        <TabsContent value="create-quote" className="mt-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            {/* Form Section */}
            <Card className="col-span-2 bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-white">Quote Generator</CardTitle>
                <CardDescription className="text-gray-400">Create a new professional quote for a client.</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="text-gray-300">Quote Number</Label>
                    <Input value="QT-2024-084" readOnly className="bg-black/20 border-white/10 text-gray-400" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Client</Label>
                    <Select>
                      <SelectTrigger className="bg-black/40 border-white/10 text-white focus:ring-brand-red">
                        <SelectValue placeholder="Select Client" />
                      </SelectTrigger>
                      <SelectContent className="bg-brand-charcoal border-white/10 text-white">
                        <SelectItem value="c1" className="focus:bg-white/10 focus:text-white cursor-pointer">SARL Plastique Algerie</SelectItem>
                        <SelectItem value="c2" className="focus:bg-white/10 focus:text-white cursor-pointer">Global Waste Solutions</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2 border border-white/10 p-4 rounded-lg bg-black/20">
                  <Label className="text-white font-semibold block mb-2">Product Line Item</Label>
                  <div className="grid grid-cols-12 gap-2">
                    <div className="col-span-6">
                      <Select>
                        <SelectTrigger className="bg-brand-charcoal border-white/10 text-white">
                          <SelectValue placeholder="Select Product" />
                        </SelectTrigger>
                        <SelectContent className="bg-brand-charcoal border-white/10 text-white">
                          <SelectItem value="p1" className="focus:bg-white/10 focus:text-white cursor-pointer">K-SHRED 5000 (Industrial)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="col-span-2">
                      <Input type="number" value={qty} onChange={(e) => setQty(Number(e.target.value))} className="bg-brand-charcoal border-white/10 text-white" />
                    </div>
                    <div className="col-span-4">
                      <Input type="number" value={price} onChange={(e) => setPrice(Number(e.target.value))} className="bg-brand-charcoal border-white/10 text-white" />
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="text-gray-300">Discount (DZD)</Label>
                    <Input type="number" value={discount} onChange={(e) => setDiscount(Number(e.target.value))} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Delivery Cost (DZD)</Label>
                    <Input type="number" value={delivery} onChange={(e) => setDelivery(Number(e.target.value))} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label className="text-gray-300">Internal Notes</Label>
                  <Textarea className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red resize-none h-24" placeholder="Add notes here..." />
                </div>

              </CardContent>
            </Card>

            {/* Preview & Actions Section */}
            <div className="space-y-6">
              
              {/* Calculation Preview */}
              <Card className="bg-black border-white/10 shadow-2xl relative overflow-hidden">
                {/* Red edge accent */}
                <div className="absolute left-0 top-0 w-1 h-full bg-brand-red"></div>
                <CardHeader>
                  <CardTitle className="text-white text-lg">Quote Summary</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Subtotal</span>
                    <span className="text-white font-medium">{subtotal.toLocaleString()} DZD</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Discount</span>
                    <span className="text-brand-red font-medium">-{discount.toLocaleString()} DZD</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">VAT (19%)</span>
                    <span className="text-white font-medium">{vat.toLocaleString()} DZD</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Delivery</span>
                    <span className="text-white font-medium">{delivery.toLocaleString()} DZD</span>
                  </div>
                  <div className="border-t border-white/10 pt-3 mt-3 flex justify-between items-center">
                    <span className="text-white font-bold">TOTAL</span>
                    <span className="text-2xl font-black text-brand-red">{total.toLocaleString()} DZD</span>
                  </div>
                </CardContent>
              </Card>

              {/* Actions */}
              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardContent className="p-4 space-y-3">
                  <Button className="w-full bg-white text-black hover:bg-gray-200 font-semibold">
                    <Printer className="w-4 h-4 mr-2" /> Generate PDF
                  </Button>
                  <Button className="w-full bg-brand-red hover:bg-brand-red/90 text-white font-semibold">
                    <Mail className="w-4 h-4 mr-2" /> Send by Email
                  </Button>
                  <Button className="w-full bg-[#25D366] hover:bg-[#25D366]/90 text-white font-semibold">
                    <Send className="w-4 h-4 mr-2" /> Send via WhatsApp
                  </Button>
                  <div className="border-t border-white/10 pt-3 mt-3"></div>
                  <Button variant="outline" className="w-full border-white/10 bg-transparent text-white hover:bg-white/5">
                    <Save className="w-4 h-4 mr-2" /> Save Draft
                  </Button>
                </CardContent>
              </Card>
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
