import { useEffect, useState } from 'react'
import { Card } from '@/components/ui/Card'
import { Skeleton } from '@/components/ui/Skeleton'
import {
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableHeader,
  TableCell,
} from '@/components/ui/Table'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { EmptyState } from '@/components/ui/EmptyState'
import { formatDate } from '@/lib/utils'
import { crmApi } from '@/lib/api'
import {
  Users,
  Search,
  Plus,
  Filter,
  Mail,
  Building2,
  MoreHorizontal,
} from 'lucide-react'

interface Customer {
  id: string
  name: string
  email: string
  phone?: string
  company: string
  org_number?: string
  status: string
  source?: string
  tags?: string[] | null
  assigned_to?: string | null
  created_at: string
  updated_at: string
}

interface Lead {
  id: string
  name: string
  email: string
  phone?: string
  company: string
  org_number?: string
  status: string
  source?: string
  tags?: string[] | null
  assigned_to?: string | null
  created_at: string
  updated_at: string
}

interface PipelineStage {
  id: string
  name: string
  order: number
  deals: number
  value: number
}

const tabs = ['Customers', 'Leads', 'Pipeline']

export function CRMPage() {
  const [activeTab, setActiveTab] = useState('Customers')
  const [searchQuery, setSearchQuery] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const [customers, setCustomers] = useState<Customer[]>([])
  const [customerTotal, setCustomerTotal] = useState(0)
  const [leads, setLeads] = useState<Lead[]>([])
  const [pipelineStages, setPipelineStages] = useState<PipelineStage[]>([])

  useEffect(() => {
    async function fetchData() {
      setLoading(true)
      setError('')
      try {
        const [customersRes, leadsRes, pipelineRes] = await Promise.all([
          crmApi.customers(),
          crmApi.leads(),
          crmApi.pipeline(),
        ])
        setCustomers(customersRes.customers as Customer[])
        setCustomerTotal(customersRes.total)
        setLeads(leadsRes.leads as Lead[])
        const p = pipelineRes as { stages?: PipelineStage[]; pipeline?: PipelineStage[] }
        setPipelineStages(p.stages || p.pipeline || [])
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load CRM data')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  const filteredCustomers = customers.filter(
    (c) =>
      c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (c.company || '').toLowerCase().includes(searchQuery.toLowerCase())
  )

  const filteredLeads = leads.filter(
    (l) =>
      l.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (l.company || '').toLowerCase().includes(searchQuery.toLowerCase())
  )

  const totalPipelineValue = pipelineStages.reduce((sum, s) => sum + (s.value || 0), 0)

  if (loading) {
    return (
      <div className="space-y-8">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
        </div>
        <Skeleton className="h-[400px]" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-danger">{error}</p>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-xl font-semibold text-text-primary">CRM</h1>
          <p className="text-sm text-text-secondary mt-0.5">Manage customers, leads, and pipeline</p>
        </div>
        <Button icon={<Plus size={16} />}>Add Contact</Button>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary-light flex items-center justify-center text-primary">
              <Users size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{customerTotal}</p>
              <p className="text-xs text-text-secondary">Total Customers</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-success-light flex items-center justify-center text-success">
              <Mail size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">{leads.length}</p>
              <p className="text-xs text-text-secondary">Active Leads</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-warning-light flex items-center justify-center text-warning">
              <Building2 size={18} />
            </div>
            <div>
              <p className="text-2xl font-semibold text-text-primary">
                {new Intl.NumberFormat('sv-SE', { style: 'currency', currency: 'SEK', maximumFractionDigits: 0 }).format(totalPipelineValue)}
              </p>
              <p className="text-xs text-text-secondary">Pipeline Value</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Tabs + Search */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div className="flex items-center gap-1 bg-bg rounded-xl p-1">
          {tabs.map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                activeTab === tab
                  ? 'bg-surface text-text-primary shadow-sm'
                  : 'text-text-secondary hover:text-text-primary'
              }`}
            >
              {tab}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-2 w-full sm:w-auto">
          <div className="relative flex-1 sm:flex-initial">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
            <input
              type="text"
              placeholder="Search..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full sm:w-64 h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm text-text-primary placeholder:text-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary/30"
            />
          </div>
          <Button variant="secondary" size="sm" icon={<Filter size={14} />}>
            Filter
          </Button>
        </div>
      </div>

      {/* Tab Content */}
      {activeTab === 'Customers' && (
        <Card>
          <Table>
            <TableHead>
              <TableRow>
                <TableHeader>Customer</TableHeader>
                <TableHeader>Company</TableHeader>
                <TableHeader>Status</TableHeader>
                <TableHeader>Phone</TableHeader>
                <TableHeader>Created</TableHeader>
                <TableHeader align="right"></TableHeader>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredCustomers.map((customer) => (
                <TableRow key={customer.id}>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold">
                        {customer.name.charAt(0)}
                      </div>
                      <div>
                        <p className="font-medium text-text-primary">{customer.name}</p>
                        <p className="text-xs text-text-secondary">{customer.email}</p>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{customer.company || '—'}</TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        customer.status === 'active'
                          ? 'success'
                          : customer.status === 'lead'
                          ? 'primary'
                          : 'default'
                      }
                    >
                      {customer.status}
                    </Badge>
                  </TableCell>
                  <TableCell>{customer.phone || '—'}</TableCell>
                  <TableCell>{formatDate(customer.created_at)}</TableCell>
                  <TableCell align="right">
                    <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                      <MoreHorizontal size={16} />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          {filteredCustomers.length === 0 && (
            <EmptyState
              icon={<Users size={32} />}
              title="No customers found"
              description="Try adjusting your search or filters"
            />
          )}
        </Card>
      )}

      {activeTab === 'Leads' && (
        <Card>
          <Table>
            <TableHead>
              <TableRow>
                <TableHeader>Lead</TableHeader>
                <TableHeader>Company</TableHeader>
                <TableHeader>Source</TableHeader>
                <TableHeader>Status</TableHeader>
                <TableHeader>Created</TableHeader>
                <TableHeader align="right"></TableHeader>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredLeads.map((lead) => (
                <TableRow key={lead.id}>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold">
                        {lead.name.charAt(0)}
                      </div>
                      <div>
                        <p className="font-medium text-text-primary">{lead.name}</p>
                        <p className="text-xs text-text-secondary">{lead.email}</p>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{lead.company || '—'}</TableCell>
                  <TableCell>{lead.source || '—'}</TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        lead.status === 'qualified'
                          ? 'success'
                          : lead.status === 'contacted'
                          ? 'primary'
                          : lead.status === 'lost'
                          ? 'danger'
                          : 'default'
                      }
                    >
                      {lead.status}
                    </Badge>
                  </TableCell>
                  <TableCell>{formatDate(lead.created_at)}</TableCell>
                  <TableCell align="right">
                    <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                      <MoreHorizontal size={16} />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          {filteredLeads.length === 0 && (
            <EmptyState
              icon={<Mail size={32} />}
              title="No leads found"
              description="Try adjusting your search or filters"
            />
          )}
        </Card>
      )}

      {activeTab === 'Pipeline' && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
          {pipelineStages.length === 0 && (
            <div className="col-span-full text-center text-text-secondary py-12">
              No pipeline stages found
            </div>
          )}
          {pipelineStages.map((stage) => (
            <Card key={stage.id} hover>
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-semibold text-text-primary">{stage.name}</h3>
                <Badge variant="default">{stage.deals} deals</Badge>
              </div>
              <p className="text-2xl font-semibold text-text-primary">
                {stage.value > 0
                  ? new Intl.NumberFormat('sv-SE', { style: 'currency', currency: 'SEK', maximumFractionDigits: 0 }).format(stage.value)
                  : '—'}
              </p>
              <div className="mt-4 h-1.5 bg-bg rounded-full overflow-hidden">
                <div
                  className="h-full bg-primary rounded-full transition-all"
                  style={{
                    width: `${totalPipelineValue > 0 ? (stage.value / totalPipelineValue) * 100 : 0}%`,
                  }}
                />
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}
