import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { AdminLayout } from '@/components/admin/AdminLayout';
import { AdminPageHeader } from '@/components/admin/AdminPageHeader';
import { AdminPageContainer } from '@/components/admin/AdminPageContainer';
import { StatCard } from '@/components/admin/StatCard';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { MoneyInput } from '@/components/ui/money-input';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Plus, Briefcase, TrendingUp, Trophy, LayoutGrid, List, Target, Calendar } from 'lucide-react';
import { useDeals, useUpdateDeal, useCreateDeal, useDealStats, getDealStageInfo, type DealStage } from '@/hooks/useDeals';
import { useProducts, formatPrice } from '@/hooks/useProducts';
import { useLeads } from '@/hooks/useLeads';
import { DealKanban } from '@/components/admin/DealKanban';
import { StaleDealsCard } from '@/components/admin/deals/StaleDealsCard';
import { PipelineSummary } from '@/components/admin/deals/PipelineSummary';
import { ScheduleNextActivityDialog } from '@/components/admin/deals/ScheduleNextActivityDialog';
import { SavedViewsMenu } from '@/components/admin/SavedViewsMenu';
import { useForm } from 'react-hook-form';
import { format } from 'date-fns';

type ViewMode = 'kanban' | 'table';

export default function DealsPage() {
  const { data: deals = [], isLoading } = useDeals();
  const { data: stats } = useDealStats();
  const updateDeal = useUpdateDeal();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [viewMode, setViewMode] = useState<ViewMode>('kanban');
  const [activeViewId, setActiveViewId] = useState<string | null>(null);
  const [scheduleFor, setScheduleFor] = useState<{ deal: any; stage: DealStage } | null>(null);

  const maybePromptScheduler = (dealId: string, newStage: DealStage) => {
    if (newStage !== 'closed_won' && newStage !== 'closed_lost') return;
    const deal = deals.find(d => d.id === dealId);
    if (!deal) return;
    if (deal.stage === newStage) return;
    setScheduleFor({ deal, stage: newStage });
  };

  const handleStageChange = (dealId: string, stage: DealStage) => {
    maybePromptScheduler(dealId, stage);
    updateDeal.mutate({ id: dealId, stage });
  };

  const activeDeals = deals.filter(d => d.stage !== 'closed_won' && d.stage !== 'closed_lost');
  const closedDeals = deals.filter(d => d.stage === 'closed_won' || d.stage === 'closed_lost');

  return (
    <AdminLayout>
      <AdminPageContainer>
        <AdminPageHeader
          title="Deals"
          description="Manage your sales pipeline and opportunities"
        >
          <div className="flex items-center gap-2">
            <ToggleGroup 
              type="single" 
              value={viewMode} 
              onValueChange={(v) => v && setViewMode(v as ViewMode)}
              className="border rounded-md"
            >
              <ToggleGroupItem value="kanban" aria-label="Kanban view" className="px-3">
                <LayoutGrid className="h-4 w-4" />
              </ToggleGroupItem>
              <ToggleGroupItem value="table" aria-label="Table view" className="px-3">
                <List className="h-4 w-4" />
              </ToggleGroupItem>
            </ToggleGroup>
            <SavedViewsMenu
              scope="deals"
              currentConfig={{ viewMode }}
              activeViewId={activeViewId}
              onActiveViewChange={setActiveViewId}
              onApply={(cfg) => {
                if (cfg.viewMode === 'kanban' || cfg.viewMode === 'table') setViewMode(cfg.viewMode);
              }}
            />
            <Button onClick={() => setDialogOpen(true)}>
              <Plus className="h-4 w-4 mr-2" />
              New Deal
            </Button>
          </div>
        </AdminPageHeader>

        {/* Forecast row — the numbers that matter */}
        <div className="grid gap-4 md:grid-cols-4">
          <StatCard
            label="Pipeline Value"
            value={stats ? formatPrice(stats.totalPipeline) : null}
            icon={TrendingUp}
            variant="default"
            isLoading={!stats}
            subtext="All open deals"
          />
          <StatCard
            label="Weighted Forecast"
            value={stats ? formatPrice(Math.round(stats.weightedForecast)) : null}
            icon={Target}
            variant="primary"
            isLoading={!stats}
            subtext="Σ value × win probability"
          />
          <StatCard
            label="Won This Month"
            value={stats ? formatPrice(stats.wonThisMonth) : null}
            icon={Trophy}
            variant="success"
            isLoading={!stats}
            subtext={stats ? `${stats.closed_won.count} deal${stats.closed_won.count === 1 ? '' : 's'} closed` : ''}
          />
          <StatCard
            label="In Negotiation"
            value={stats?.negotiation.count}
            icon={Calendar}
            variant="warning"
            isLoading={!stats}
            subtext={stats ? formatPrice(stats.negotiation.value) : ''}
          />
        </div>

        {/* Kanban View */}
        {viewMode === 'kanban' && (
          <>
            <PipelineSummary deals={deals} />
            <DealKanban
              deals={deals}
              isLoading={isLoading}
              onStageChanged={(d, s) => maybePromptScheduler(d.id, s)}
            />
            <StaleDealsCard daysThreshold={14} />
          </>
        )}

        {/* Table View */}
        {viewMode === 'table' && (
          <>
            {/* Active Deals */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="h-5 w-5" />
                  Active Deals
                </CardTitle>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <div className="space-y-3">
                    {[1, 2, 3].map(i => (
                      <Skeleton key={i} className="h-12 w-full" />
                    ))}
                  </div>
                ) : activeDeals.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    <Briefcase className="h-10 w-10 mx-auto mb-3 opacity-50" />
                    <p>No active deals</p>
                    <p className="text-sm">Create a deal to start tracking opportunities</p>
                  </div>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Deal</TableHead>
                        <TableHead>Contact</TableHead>
                        <TableHead>Value</TableHead>
                        <TableHead>Stage</TableHead>
                        <TableHead>Expected Close</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {activeDeals.map(deal => (
                        <TableRow key={deal.id}>
                          <TableCell className="font-medium">
                            {deal.product?.name || 'Custom deal'}
                          </TableCell>
                          <TableCell>
                            <Link 
                              to={`/admin/leads/${deal.lead_id}`}
                              className="text-primary hover:underline"
                            >
                              View Contact
                            </Link>
                          </TableCell>
                          <TableCell className="font-semibold">
                            {formatPrice(deal.value_cents, deal.currency)}
                          </TableCell>
                          <TableCell>
                            <Select
                              value={deal.stage}
                              onValueChange={(value: DealStage) => handleStageChange(deal.id, value)}
                            >
                              <SelectTrigger className="w-[130px]">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="lead">Lead</SelectItem>
                                <SelectItem value="qualified">Qualified</SelectItem>
                                <SelectItem value="proposal">Proposal</SelectItem>
                                <SelectItem value="negotiation">Negotiation</SelectItem>
                                <SelectItem value="closed_won">Won</SelectItem>
                                <SelectItem value="closed_lost">Lost</SelectItem>
                              </SelectContent>
                            </Select>
                          </TableCell>
                          <TableCell className="text-muted-foreground">
                            {deal.expected_close 
                              ? format(new Date(deal.expected_close), 'MMM d, yyyy')
                              : '—'
                            }
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
              </CardContent>
            </Card>

            {/* Closed Deals */}
            {closedDeals.length > 0 && (
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2 text-muted-foreground">
                    Closed Deals
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Deal</TableHead>
                        <TableHead>Contact</TableHead>
                        <TableHead>Value</TableHead>
                        <TableHead>Result</TableHead>
                        <TableHead>Closed At</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {closedDeals.map(deal => {
                        const stageInfo = getDealStageInfo(deal.stage);
                        return (
                          <TableRow key={deal.id} className="opacity-70">
                            <TableCell className="font-medium">
                              {deal.product?.name || 'Custom deal'}
                            </TableCell>
                            <TableCell>
                              <Link 
                                to={`/admin/leads/${deal.lead_id}`}
                                className="text-primary hover:underline"
                              >
                                View Contact
                              </Link>
                            </TableCell>
                            <TableCell className="font-semibold">
                              {formatPrice(deal.value_cents, deal.currency)}
                            </TableCell>
                            <TableCell>
                              <Badge className={stageInfo.color}>
                                {stageInfo.label}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-muted-foreground">
                              {deal.closed_at 
                                ? format(new Date(deal.closed_at), 'MMM d, yyyy')
                                : '—'
                              }
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            )}
          </>
        )}

        <CreateDealDialogWithLeadPicker
          open={dialogOpen}
          onOpenChange={setDialogOpen}
        />

        <ScheduleNextActivityDialog
          deal={scheduleFor?.deal ?? null}
          closedAs={scheduleFor?.stage ?? null}
          onOpenChange={(o) => { if (!o) setScheduleFor(null); }}
        />
      </AdminPageContainer>
    </AdminLayout>
  );
}

// Dialog with lead picker for creating deals from the Deals page
interface CreateDealDialogWithLeadPickerProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

interface FormData {
  lead_id: string;
  product_id: string;
  value: number;
  expected_close: string;
  notes: string;
}

function CreateDealDialogWithLeadPicker({ open, onOpenChange }: CreateDealDialogWithLeadPickerProps) {
  const { data: leads = [] } = useLeads();
  const { data: products = [] } = useProducts();
  const createDeal = useCreateDeal();

  const { register, handleSubmit, watch, setValue, reset } = useForm<FormData>({
    defaultValues: {
      lead_id: '',
      product_id: '',
      value: 0,
      expected_close: '',
      notes: '',
    },
  });

  const selectedProductId = watch('product_id');
  const valueCents = watch('value') || 0;

  useEffect(() => {
    if (selectedProductId) {
      const product = products.find(p => p.id === selectedProductId);
      if (product) {
        setValue('value', product.price_cents);
      }
    }
  }, [selectedProductId, products, setValue]);

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

  const onSubmit = (data: FormData) => {
    createDeal.mutate({
      lead_id: data.lead_id,
      product_id: data.product_id || null,
      value_cents: Math.round(data.value || 0),
      expected_close: data.expected_close || null,
      notes: data.notes || null,
    }, {
      onSuccess: () => {
        onOpenChange(false);
      },
    });
  };

  const availableLeads = leads.filter(l => l.status === 'lead' || l.status === 'opportunity');

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <form onSubmit={handleSubmit(onSubmit)}>
          <DialogHeader>
            <DialogTitle>Create New Deal</DialogTitle>
            <DialogDescription>
              Add a new deal to your pipeline
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="lead_id">Contact *</Label>
              <Select
                value={watch('lead_id')}
                onValueChange={(value) => setValue('lead_id', value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select a contact" />
                </SelectTrigger>
                <SelectContent>
                  {availableLeads.map(lead => (
                    <SelectItem key={lead.id} value={lead.id}>
                      {lead.name || lead.email} {lead.company ? `(${lead.company})` : ''}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {availableLeads.length === 0 && (
                <p className="text-sm text-muted-foreground">
                  No active contacts available. Create a contact first.
                </p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="product_id">Product</Label>
              <Select
                value={watch('product_id')}
                onValueChange={(value) => setValue('product_id', value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select a product (optional)" />
                </SelectTrigger>
                <SelectContent>
                  {products.filter(p => p.is_active).map(product => (
                    <SelectItem key={product.id} value={product.id}>
                      {product.name} - {formatPrice(product.price_cents, product.currency)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="value">Value</Label>
              <MoneyInput
                id="value"
                value={valueCents}
                onChange={(c) => setValue('value', c)}
                placeholder="0"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="expected_close">Expected Close Date</Label>
              <Input
                id="expected_close"
                type="date"
                {...register('expected_close')}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                placeholder="Additional information..."
                {...register('notes')}
              />
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button 
              type="submit" 
              disabled={createDeal.isPending || !watch('lead_id')}
            >
              {createDeal.isPending ? 'Creating...' : 'Create Deal'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
