"use client";

import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { BuyerCard } from "@/components/dashboard/buyer-card";
import { Plus, Search, Filter, LayoutGrid, List, Users, Loader2, AlertCircle } from "lucide-react";
import { mockBuyers } from "@/lib/mock-data";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { getInitials, getStatusColor, formatCurrency, ASSET_TYPES, MARKETS } from "@/lib/utils";
import { useToast } from "@/components/ui/toast";
import type { Buyer } from "@/types";

export default function BuyersPage() {
  const { addToast } = useToast();
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [buyers, setBuyers] = useState<Buyer[]>(mockBuyers);

  // Load custom buyers from localStorage
  useEffect(() => {
    try {
      const customBuyers = JSON.parse(localStorage.getItem("credispo_custom_buyers") || "[]");
      if (customBuyers.length > 0) {
        setBuyers([...customBuyers.reverse(), ...mockBuyers]);
      }
    } catch {
      // silent
    }
  }, []);

  const handleAddBuyer = (newBuyer: Buyer) => {
    setBuyers((prev) => [newBuyer, ...prev]);
    try {
      const existing = JSON.parse(localStorage.getItem("credispo_custom_buyers") || "[]");
      existing.push(newBuyer);
      localStorage.setItem("credispo_custom_buyers", JSON.stringify(existing));
    } catch {
      // silent
    }
    addToast({
      type: "success",
      title: "Buyer Added!",
      description: `${newBuyer.name} has been added to your database.`,
    });
    setShowAddDialog(false);
  };

  const filteredBuyers = buyers.filter((buyer) => {
    const matchesSearch =
      buyer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (buyer.company || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
      buyer.email.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = filterStatus === "all" || buyer.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  return (
    <div className="space-y-6 animate-page-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-navy-900">Buyer Database</h1>
          <p className="text-sm text-navy-500 mt-1">
            {buyers.length} total buyers • {buyers.filter((b) => b.status === "high-intent").length} high-intent
          </p>
        </div>
        <Button variant="gold" onClick={() => setShowAddDialog(true)} className="w-full sm:w-auto active:scale-[0.98] transition-transform">
          <Plus className="mr-2 h-4 w-4" />
          Add Buyer
        </Button>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-navy-400" />
          <Input
            placeholder="Search buyers by name, company, or email..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterStatus} onValueChange={setFilterStatus}>
          <SelectTrigger className="w-full sm:w-44">
            <Filter className="h-4 w-4 mr-2" />
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="high-intent">High-Intent</SelectItem>
            <SelectItem value="unresponsive">Unresponsive</SelectItem>
            <SelectItem value="inactive">Inactive</SelectItem>
          </SelectContent>
        </Select>
        <div className="flex rounded-md border border-navy-200 overflow-hidden">
          <button
            onClick={() => setViewMode("grid")}
            className={`px-3 py-2 transition-colors ${viewMode === "grid" ? "bg-navy-800 text-white" : "bg-white text-navy-600 hover:bg-navy-50"}`}
          >
            <LayoutGrid className="h-4 w-4" />
          </button>
          <button
            onClick={() => setViewMode("list")}
            className={`px-3 py-2 transition-colors ${viewMode === "list" ? "bg-navy-800 text-white" : "bg-white text-navy-600 hover:bg-navy-50"}`}
          >
            <List className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Grid View */}
      {viewMode === "grid" && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 stagger-in">
          {filteredBuyers.map((buyer) => (
            <BuyerCard key={buyer.id} buyer={buyer} />
          ))}
        </div>
      )}

      {/* List View */}
      {viewMode === "list" && (
        <Card>
          <CardContent className="p-0">
            <div className="overflow-x-auto -mx-px">
              <table className="w-full min-w-[700px] zebra-stripe">
                <thead>
                  <tr className="border-b border-navy-100 bg-navy-25">
                    <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">Buyer</th>
                    <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">Asset Types</th>
                    <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">Price Range</th>
                    <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">Engagement</th>
                    <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-navy-50">
                  {filteredBuyers.map((buyer) => (
                    <tr key={buyer.id} className="hover:bg-gold-50/30 transition-colors">
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <Avatar className="h-8 w-8"><AvatarFallback className="text-xs">{getInitials(buyer.name)}</AvatarFallback></Avatar>
                          <div>
                            <p className="text-sm font-medium text-navy-900">{buyer.name}</p>
                            <p className="text-xs text-navy-500">{buyer.company}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex flex-wrap gap-1">
                          {buyer.asset_types.slice(0, 2).map((type) => (
                            <span key={type} className="text-xs bg-navy-50 text-navy-600 rounded px-1.5 py-0.5">{type}</span>
                          ))}
                          {buyer.asset_types.length > 2 && <span className="text-xs text-navy-400">+{buyer.asset_types.length - 2}</span>}
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-navy-700">
                          {buyer.price_min ? formatCurrency(buyer.price_min) : "Any"} — {buyer.price_max ? formatCurrency(buyer.price_max) : "No Max"}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <div className="w-16 h-1.5 rounded-full bg-navy-100">
                            <div className="h-full rounded-full bg-gold-500 transition-all" style={{ width: `${Math.min(buyer.engagement_score, 100)}%` }} />
                          </div>
                          <span className="text-xs text-navy-600 tabular-nums">{buyer.engagement_score}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <Badge className={getStatusColor(buyer.status)} variant="secondary">{buyer.status}</Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}

      {filteredBuyers.length === 0 && (
        <div className="text-center py-16">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-navy-50 mx-auto mb-4">
            <Users className="h-8 w-8 text-navy-300" />
          </div>
          <p className="text-sm font-medium text-navy-700 mb-1">No buyers found</p>
          <p className="text-xs text-navy-500">Try adjusting your search or add a new buyer.</p>
        </div>
      )}

      {/* Add Buyer Dialog */}
      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto mx-4 sm:mx-auto">
          <DialogHeader>
            <DialogTitle>Add New Buyer</DialogTitle>
            <DialogDescription>Enter the buyer&apos;s contact info and acquisition criteria.</DialogDescription>
          </DialogHeader>
          <InlineBuyerForm onSuccess={handleAddBuyer} onCancel={() => setShowAddDialog(false)} />
        </DialogContent>
      </Dialog>
    </div>
  );
}

/* Inline buyer form */
function InlineBuyerForm({ onSuccess, onCancel }: { onSuccess: (buyer: Buyer) => void; onCancel: () => void }) {
  const [loading, setLoading] = useState(false);
  const [selectedAssetTypes, setSelectedAssetTypes] = useState<string[]>([]);
  const [selectedLocations, setSelectedLocations] = useState<string[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formData, setFormData] = useState({
    name: "", company: "", email: "", phone: "",
    price_min: "", price_max: "", cap_rate_min: "", cap_rate_max: "", preferences: "",
  });

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) setErrors((prev) => { const n = { ...prev }; delete n[field]; return n; });
  };

  const validate = () => {
    const e: Record<string, string> = {};
    if (!formData.name.trim()) e.name = "Name is required";
    if (!formData.email.trim()) e.email = "Email is required";
    if (formData.email && !formData.email.includes("@")) e.email = "Invalid email";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setLoading(true);
    await new Promise((resolve) => setTimeout(resolve, 800));

    const newBuyer: Buyer = {
      id: `buyer-${Date.now()}`,
      agent_id: "agent-1",
      name: formData.name,
      company: formData.company || undefined,
      email: formData.email,
      phone: formData.phone || undefined,
      asset_types: selectedAssetTypes as Buyer["asset_types"],
      target_locations: selectedLocations,
      price_min: formData.price_min ? Number(formData.price_min) : undefined,
      price_max: formData.price_max ? Number(formData.price_max) : undefined,
      cap_rate_min: formData.cap_rate_min ? Number(formData.cap_rate_min) : undefined,
      cap_rate_max: formData.cap_rate_max ? Number(formData.cap_rate_max) : undefined,
      preferences: formData.preferences || undefined,
      status: "active",
      engagement_score: 50,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };

    setLoading(false);
    onSuccess(newBuyer);
  };

  const fieldError = (field: string) =>
    errors[field] ? <p className="flex items-center gap-1 text-xs text-red-600 mt-1"><AlertCircle className="h-3 w-3" />{errors[field]}</p> : null;

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div>
        <h4 className="text-sm font-semibold text-navy-700 mb-3">Contact Information</h4>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div>
            <Label htmlFor="buyer-name">Full Name *</Label>
            <Input id="buyer-name" placeholder="John Smith" value={formData.name} onChange={(e) => handleChange("name", e.target.value)} className={`mt-1 ${errors.name ? "border-red-400" : ""}`} />
            {fieldError("name")}
          </div>
          <div>
            <Label htmlFor="buyer-company">Company</Label>
            <Input id="buyer-company" placeholder="Smith Capital Group" value={formData.company} onChange={(e) => handleChange("company", e.target.value)} className="mt-1" />
          </div>
          <div>
            <Label htmlFor="buyer-email">Email *</Label>
            <Input id="buyer-email" type="email" placeholder="john@smithcapital.com" value={formData.email} onChange={(e) => handleChange("email", e.target.value)} className={`mt-1 ${errors.email ? "border-red-400" : ""}`} />
            {fieldError("email")}
          </div>
          <div>
            <Label htmlFor="buyer-phone">Phone</Label>
            <Input id="buyer-phone" type="tel" placeholder="(555) 123-4567" value={formData.phone} onChange={(e) => handleChange("phone", e.target.value)} className="mt-1" />
          </div>
        </div>
      </div>

      <div>
        <h4 className="text-sm font-semibold text-navy-700 mb-2">Target Asset Types</h4>
        <div className="flex flex-wrap gap-2">
          {ASSET_TYPES.map((type) => (
            <button key={type} type="button" onClick={() => setSelectedAssetTypes((prev) => prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type])} className={`text-xs px-3 py-1.5 rounded-full border transition-all active:scale-[0.96] ${selectedAssetTypes.includes(type) ? "bg-navy-800 text-white border-navy-800" : "bg-white text-navy-600 border-navy-200 hover:border-navy-400"}`}>
              {type}
            </button>
          ))}
        </div>
      </div>

      <div>
        <h4 className="text-sm font-semibold text-navy-700 mb-2">Target Locations</h4>
        <div className="flex flex-wrap gap-2 max-h-32 overflow-y-auto">
          {MARKETS.map((loc) => (
            <button key={loc} type="button" onClick={() => setSelectedLocations((prev) => prev.includes(loc) ? prev.filter((l) => l !== loc) : [...prev, loc])} className={`text-xs px-3 py-1.5 rounded-full border transition-all active:scale-[0.96] ${selectedLocations.includes(loc) ? "bg-navy-800 text-white border-navy-800" : "bg-white text-navy-600 border-navy-200 hover:border-navy-400"}`}>
              {loc}
            </button>
          ))}
        </div>
      </div>

      <div>
        <h4 className="text-sm font-semibold text-navy-700 mb-2">Financial Criteria</h4>
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div><Label className="text-xs text-navy-500">Min Price ($)</Label><Input type="number" placeholder="1M" value={formData.price_min} onChange={(e) => handleChange("price_min", e.target.value)} className="mt-1" /></div>
          <div><Label className="text-xs text-navy-500">Max Price ($)</Label><Input type="number" placeholder="10M" value={formData.price_max} onChange={(e) => handleChange("price_max", e.target.value)} className="mt-1" /></div>
          <div><Label className="text-xs text-navy-500">Min Cap (%)</Label><Input type="number" step="0.01" placeholder="5.00" value={formData.cap_rate_min} onChange={(e) => handleChange("cap_rate_min", e.target.value)} className="mt-1" /></div>
          <div><Label className="text-xs text-navy-500">Max Cap (%)</Label><Input type="number" step="0.01" placeholder="8.00" value={formData.cap_rate_max} onChange={(e) => handleChange("cap_rate_max", e.target.value)} className="mt-1" /></div>
        </div>
      </div>

      <div>
        <Label className="text-sm font-semibold text-navy-700">Additional Preferences</Label>
        <Textarea placeholder="Value-add opportunities, 1031 exchange buyer..." value={formData.preferences} onChange={(e) => handleChange("preferences", e.target.value)} rows={2} className="mt-1" maxLength={500} />
        <span className="text-xs text-navy-400">{formData.preferences.length}/500</span>
      </div>

      <div className="flex gap-3 pt-2">
        <Button type="button" variant="outline" className="flex-1" onClick={onCancel}>Cancel</Button>
        <Button type="submit" variant="gold" className="flex-1 active:scale-[0.98] transition-transform" disabled={loading}>
          {loading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" />Adding...</> : "Add Buyer"}
        </Button>
      </div>
    </form>
  );
}
